{"text":"\/\/This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. \/ Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir \/ Website: iasbs.ac.ir\/~hkhojasteh, hadiabdikhojasteh.ir\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::ml;\n\ntypedef tuple enumerate;\nstruct IncGenerator {\n\tuint32_t current_;\n\tIncGenerator(uint32_t start) : current_(start) {}\n\tuint32_t operator() () { return current_++; }\n};\n\nvector sample(Mat1d, uint32_t, uint32_t);\nvoid lossFun(vector inputs, vector targets, Mat1d hprev);\n\nuint32_t data_size, vocab_size;\nMat1d Wxh, Whh, Why, bh, by;\t\t\t\t\t\t\t\/\/model parameters\n\nuint32_t main() {\n\tsrand(time(NULL));\n\n\tvector data;\n\tvector chars;\n\tvector charenum;\n\tFILE* inputfile;\n\tstring fileName = \"input.txt\";\n\tinputfile = fopen(fileName.c_str(), \"r\");\n\n\tuint32_t i = 0;\n\twhile (!feof(inputfile)) {\n\t\tchar inchar[1] = { 0 };\n\t\tfscanf(inputfile, \"%c\", inchar);\n\t\tdata.push_back(inchar[0]);\n\n\t\tauto it = find_if(chars.begin(), chars.end(),\n\t\t\t[&](const char element) { return element == inchar[0]; });\n\t\t\/\/If this is not in the char set\n\t\tif (it == end(chars)) {\n\t\t\tchars.push_back(inchar[0]);\n\t\t\tcharenum.push_back(make_tuple(inchar[0], i));\n\t\t\ti++;\n\t\t}\n\t}\n\tfclose(inputfile);\n\n\tdata_size = data.size();\n\tvocab_size = chars.size();\n\tprintf(\"data has %d characters, %d unique.\\n\", data_size, vocab_size);\n\tvector char_to_ix = charenum;\n\treverse(charenum.begin(), charenum.end());\n\tvector ix_to_char = charenum;\n\n\t\/\/hyperparameters\n\tuint32_t hidden_size = 100;\t\t\t\t\t\t\t\/\/size of hidden layer of neurons\n\tuint32_t seq_length = 25;\t\t\t\t\t\t\t\/\/number of steps to unroll the RNN for\n\tdouble learning_rate = 1e-1;\n\n\tWxh.create(hidden_size, vocab_size);\t\t\t\t\/\/Or: Mat mat(2, 4, CV_64FC1);\n\tWhh.create(hidden_size, hidden_size);\n\tWhy.create(vocab_size, hidden_size);\n\tdouble mean = 0.0, stddev = 1.0 \/ 3.0;\t\t\t\t\/\/99.7% of values will be inside [-1, +1] interval\n\trandn(Wxh, Scalar(mean), Scalar(stddev));\t\t\t\/\/input to hidden\n\trandn(Whh, Scalar(mean), Scalar(stddev));\t\t\t\/\/hidden to hidden\n\trandn(Why, Scalar(mean), Scalar(stddev));\t\t\t\/\/hidden to output\n\tbh = Mat::zeros(hidden_size, 1, CV_32F);\t\t\t\/\/hidden bias\n\tby = Mat::zeros(vocab_size, 1, CV_32F);\t\t\t\t\/\/output bias\n\n\tuint32_t n = 0, p = 0;\n\t\/\/Make an array of zeros with the same shape and type as a Ws array.\n\tMat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());\n\tMat1d mWhh = Mat::zeros(Whh.size(), Whh.type());\n\tMat1d mWhy = Mat::zeros(Why.size(), Why.type());\n\tMat1d mbh = Mat::zeros(bh.size(), bh.type());\t\t\/\/memory variables for Adagrad\n\tMat1d mby = Mat::zeros(by.size(), by.type());\t\t\/\/memory variables for Adagrad\n\t\/\/loss at iteration 0\n\tdouble smooth_loss = -log(1.0 \/ vocab_size) * seq_length;\n\n\tMat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev;\n\tvector inputs, targets;\n\tfor (uint32_t i = 0; i < 1000; i++) {\n\t\t\/\/Prepare inputs (we're sweeping from left to right in steps seq_length long)\n\t\tif (p + seq_length + 1 >= data.size() || n == 0) {\n\t\t\thprev = Mat::zeros(hidden_size, 1, CV_32F);\t\/\/reset RNN memory\n\t\t\tp = 0;\t\t\t\t\t\t\t\t\t\t\/\/go from start of data\n\t\t}\n\n\t\tinputs.clear();\n\t\ttargets.clear();\n\t\tfor (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) {\n\t\t\tinputs.push_back(char_to_ix[p + i]);\n\t\t\ttargets.push_back(char_to_ix[p + 1 + i]);\n\t\t}\n\n\t\t\/\/Sample from the model now and then\n\t\tif (n % 100 == 0) {\n\t\t\tvector sampWords = sample(hprev, p + i, 200);\n\t\t\tfor (uint32_t i = 0; i < sampWords.size(); i++) {\n\t\t\t\tprintf(\"%c\", get<0>(ix_to_char[sampWords[i]]));\n\t\t\t}\n\t\t}\n\t\t\n\t\tlossFun(inputs, targets, hprev);\n\n\t\tp += seq_length;\t\t\t\t\t\t\t\t\/\/move data pointer\n\t\tn += 1;\t\t\t\t\t\t\t\t\t\t\t\/\/iteration counter\n\t}\n\treturn 0;\n}\n\nvector sample(Mat1d h, uint32_t seed_ix, uint32_t n) {\n\t\/\/sample a sequence of integers from the model h is memory state,\n\t\/\/ seed_ix is seed letter for first time step\n\tMat1d x = Mat::zeros(vocab_size, 1, CV_32F);\n\tx[seed_ix][0] = 1.0;\n\tvector ixes; \n\tfor (uint32_t i = 0; i < n; i++) {\n\t\tMat1d t = (Wxh * x) + (Whh * h) + bh;\n\t\tMat1d h = Mat::zeros(t.size(), t.type());\n\t\tfor (uint32_t i = 0; i < t.rows; i++) {\n\t\t\th[i][0] = tanh(t[i][0]);\n\t\t}\n\t\tMat1d y = (Why * h) + by;\n\t\tMat1d expy;\n\t\texp(y, expy);\n\t\tMat1d p = expy \/ sum(expy)[0];\n\t\tp = p.reshape(1, 1);\n\n\t\t\/\/Generates a random sample from a given 1-D array\n\t\tdefault_random_engine generator;\n\t\tdiscrete_distribution distribution(p.begin(), p.end());\n\t\tvector indices(p.size().width);\n\t\tgenerate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });\n\t\tvector incNumbers(p.size().width);\n\t\tIncGenerator gi(0);\n\t\tgenerate(incNumbers.begin(), incNumbers.end(), gi);\n\t\tMat1d x = Mat::zeros(vocab_size, 1, CV_32F);\n\t\tint randSelect = (uint32_t)rand() % vocab_size;\n\t\tx[randSelect][0] = 1.0;\n\t\tixes.push_back(randSelect);\n\t}\n\treturn ixes;\n}\n\nvoid lossFun(vector inputs, vector targets, Mat1d hprev) {\n\t\/\/inputs, targets are both list of integers.\n\t\/\/ hprev is Hx1 array of initial hidden state\n\t\/\/ returns the loss, gradients on model parameters, and last hidden state\n\tMat1d hs = hprev;\n\tdouble loss = 0.0;\n\t\/\/forward pass\n\tfor (uint32_t t = 0; t < inputs.size(); t++) {\n\t\t\/\/encode in 1-of-k\n\t\tMat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);\n\t\txs[t][get<1>(inputs[t])] = 1;\n\t\tMat1d val = (Wxh * xs.row(t).t());\n\t\tfor (uint32_t i = 0; i < val.rows; i++) {\n\t\t\ths[i][0] = tanh(val[i][0]);\n\t\t\tMat1d temp = (Whh * hs[i - 1][0]);\n\t\t\ths[i][0] += temp[i][0] + bh[i][0];\t\t\t\t\/\/hidden state\n\t\t}\n\t\tMat1d ys = (Why * hs[t][0]) + by[t][0];\t\t\t\t\/\/unnormalized log probabilities for next chars\n\t\tfor (uint32_t i = 0; i < ys.rows; i++) {\n\t\t\ths[i][0] = tanh(val[i][0]);\n\t\t\tMat1d temp = (Whh * hs[i - 1][0]);\n\t\t\ths[i][0] += temp[i][0] + bh[i][0];\t\t\t\t\/\/hidden state\n\t\t}\n\t}\n}\nsoftmax (cross-entropy loss)\/\/This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. \/ Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir \/ Website: iasbs.ac.ir\/~hkhojasteh, hadiabdikhojasteh.ir\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::ml;\n\ntypedef tuple enumerate;\nstruct IncGenerator {\n\tuint32_t current_;\n\tIncGenerator(uint32_t start) : current_(start) {}\n\tuint32_t operator() () { return current_++; }\n};\n\nvector sample(Mat1d, uint32_t, uint32_t);\nvoid lossFun(vector inputs, vector targets, Mat1d hprev);\n\nuint32_t data_size, vocab_size;\nMat1d Wxh, Whh, Why, bh, by;\t\t\t\t\t\t\t\/\/model parameters\n\nuint32_t main() {\n\tsrand(time(NULL));\n\n\tvector data;\n\tvector chars;\n\tvector charenum;\n\tFILE* inputfile;\n\tstring fileName = \"input.txt\";\n\tinputfile = fopen(fileName.c_str(), \"r\");\n\n\tuint32_t i = 0;\n\twhile (!feof(inputfile)) {\n\t\tchar inchar[1] = { 0 };\n\t\tfscanf(inputfile, \"%c\", inchar);\n\t\tdata.push_back(inchar[0]);\n\n\t\tauto it = find_if(chars.begin(), chars.end(),\n\t\t\t[&](const char element) { return element == inchar[0]; });\n\t\t\/\/If this is not in the char set\n\t\tif (it == end(chars)) {\n\t\t\tchars.push_back(inchar[0]);\n\t\t\tcharenum.push_back(make_tuple(inchar[0], i));\n\t\t\ti++;\n\t\t}\n\t}\n\tfclose(inputfile);\n\n\tdata_size = data.size();\n\tvocab_size = chars.size();\n\tprintf(\"data has %d characters, %d unique.\\n\", data_size, vocab_size);\n\tvector char_to_ix = charenum;\n\treverse(charenum.begin(), charenum.end());\n\tvector ix_to_char = charenum;\n\n\t\/\/hyperparameters\n\tuint32_t hidden_size = 100;\t\t\t\t\t\t\t\/\/size of hidden layer of neurons\n\tuint32_t seq_length = 25;\t\t\t\t\t\t\t\/\/number of steps to unroll the RNN for\n\tdouble learning_rate = 1e-1;\n\n\tWxh.create(hidden_size, vocab_size);\t\t\t\t\/\/Or: Mat mat(2, 4, CV_64FC1);\n\tWhh.create(hidden_size, hidden_size);\n\tWhy.create(vocab_size, hidden_size);\n\tdouble mean = 0.0, stddev = 1.0 \/ 3.0;\t\t\t\t\/\/99.7% of values will be inside [-1, +1] interval\n\trandn(Wxh, Scalar(mean), Scalar(stddev));\t\t\t\/\/input to hidden\n\trandn(Whh, Scalar(mean), Scalar(stddev));\t\t\t\/\/hidden to hidden\n\trandn(Why, Scalar(mean), Scalar(stddev));\t\t\t\/\/hidden to output\n\tbh = Mat::zeros(hidden_size, 1, CV_32F);\t\t\t\/\/hidden bias\n\tby = Mat::zeros(vocab_size, 1, CV_32F);\t\t\t\t\/\/output bias\n\n\tuint32_t n = 0, p = 0;\n\t\/\/Make an array of zeros with the same shape and type as a Ws array.\n\tMat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());\n\tMat1d mWhh = Mat::zeros(Whh.size(), Whh.type());\n\tMat1d mWhy = Mat::zeros(Why.size(), Why.type());\n\tMat1d mbh = Mat::zeros(bh.size(), bh.type());\t\t\/\/memory variables for Adagrad\n\tMat1d mby = Mat::zeros(by.size(), by.type());\t\t\/\/memory variables for Adagrad\n\t\/\/loss at iteration 0\n\tdouble smooth_loss = -log(1.0 \/ vocab_size) * seq_length;\n\n\tMat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev;\n\tvector inputs, targets;\n\tfor (uint32_t i = 0; i < 1000; i++) {\n\t\t\/\/Prepare inputs (we're sweeping from left to right in steps seq_length long)\n\t\tif (p + seq_length + 1 >= data.size() || n == 0) {\n\t\t\thprev = Mat::zeros(hidden_size, 1, CV_32F);\t\/\/reset RNN memory\n\t\t\tp = 0;\t\t\t\t\t\t\t\t\t\t\/\/go from start of data\n\t\t}\n\n\t\tinputs.clear();\n\t\ttargets.clear();\n\t\tfor (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) {\n\t\t\tinputs.push_back(char_to_ix[p + i]);\n\t\t\ttargets.push_back(char_to_ix[p + 1 + i]);\n\t\t}\n\n\t\t\/\/Sample from the model now and then\n\t\tif (n % 100 == 0) {\n\t\t\tvector sampWords = sample(hprev, p + i, 200);\n\t\t\tfor (uint32_t i = 0; i < sampWords.size(); i++) {\n\t\t\t\tprintf(\"%c\", get<0>(ix_to_char[sampWords[i]]));\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\t\n\t\tlossFun(inputs, targets, hprev);\n\n\t\tp += seq_length;\t\t\t\t\t\t\t\t\/\/move data pointer\n\t\tn += 1;\t\t\t\t\t\t\t\t\t\t\t\/\/iteration counter\n\t}\n\treturn 0;\n}\n\nvector sample(Mat1d h, uint32_t seed_ix, uint32_t n) {\n\t\/\/sample a sequence of integers from the model h is memory state,\n\t\/\/ seed_ix is seed letter for first time step\n\tMat1d x = Mat::zeros(vocab_size, 1, CV_32F);\n\tx[seed_ix][0] = 1.0;\n\tvector ixes; \n\tfor (uint32_t i = 0; i < n; i++) {\n\t\tMat1d t = (Wxh * x) + (Whh * h) + bh;\n\t\tMat1d h = Mat::zeros(t.size(), t.type());\n\t\tfor (uint32_t i = 0; i < t.rows; i++) {\n\t\t\th[i][0] = tanh(t[i][0]);\n\t\t}\n\t\tMat1d y = (Why * h) + by;\n\t\tMat1d expy;\n\t\texp(y, expy);\n\t\tMat1d p = expy \/ sum(expy)[0];\n\t\tp = p.reshape(1, 1);\n\n\t\t\/\/Generates a random sample from a given 1-D array\n\t\tdefault_random_engine generator;\n\t\tdiscrete_distribution distribution(p.begin(), p.end());\n\t\tvector indices(p.size().width);\n\t\tgenerate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });\n\t\tvector incNumbers(p.size().width);\n\t\tIncGenerator gi(0);\n\t\tgenerate(incNumbers.begin(), incNumbers.end(), gi);\n\t\tMat1d x = Mat::zeros(vocab_size, 1, CV_32F);\n\t\tint randSelect = (uint32_t)rand() % vocab_size;\n\t\tx[randSelect][0] = 1.0;\n\t\tixes.push_back(randSelect);\n\t}\n\treturn ixes;\n}\n\nvoid lossFun(vector inputs, vector targets, Mat1d hprev) {\n\t\/\/inputs, targets are both list of integers.\n\t\/\/ hprev is Hx1 array of initial hidden state\n\t\/\/ returns the loss, gradients on model parameters, and last hidden state\n\tMat1d hs = hprev;\n\tdouble loss = 0.0;\n\t\/\/forward pass\n\tfor (uint32_t t = 0; t < inputs.size(); t++) {\n\t\t\/\/encode in 1-of-k\n\t\tMat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);\n\t\txs[t][get<1>(inputs[t])] = 1;\n\t\tMat1d val = (Wxh * xs.row(t).t());\n\t\tfor (uint32_t i = 0; i < val.rows; i++) {\n\t\t\ths[i][0] = tanh(val[i][0]);\n\t\t\tMat1d temp = (Whh * hs[i - 1][0]);\n\t\t\ths[i][0] += temp[i][0] + bh[i][0];\t\t\t\t\/\/hidden state\n\t\t}\n\t\tMat1d ys = (Why * hs[t][0]) + by[t][0];\t\t\t\t\/\/unnormalized log probabilities for next chars\n\t\t\/\/probabilities for next chars\n\t\tMat1d ps = Mat::zeros(ys.size(), ys.type());\n\t\tdouble sum = 0.0;\n\t\tfor (uint32_t i = 0; i < ys.rows; i++) {\n\t\t\tsum += ps[t][i];\n\t\t\tps[t][i] = exp(ys[t][i]);\n\t\t}\n\t\tfor (uint32_t i = 0; i < ys.rows; i++) {\n\t\t\tps[t][0] = ps[t][0] \/ sum;\n\t\t}\n\t\tloss += -log(ps[t][get<1>(targets[t])]);\t\t\t\/\/softmax (cross-entropy loss)\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \nusing namespace std;\n\n#define min(a,b) ( (a) < (b) ? (a) : (b) )\n\nconst int maxn = 1111;\nint N;\nint code[maxn];\nint guess[maxn];\nint hash_code[9], hash_guess[9];\n\nvoid solve() {\n int x = 0, y = 0;\n memset(hash_code, 0, sizeof(hash_code));\n memset(hash_guess, 0, sizeof(hash_guess));\n for(int i = 0; i < N; ++i) {\n if(code[i] == guess[i]) {\n ++x;\n } else {\n ++hash_code[code[i]-1];\n ++hash_guess[guess[i]-1];\n }\n }\n for(int i = 0; i < 9; ++i)\n y += min(hash_code[i], hash_guess[i]);\n printf(\" (%d,%d)\\n\", x, y);\n}\n\nint main()\n{\n \/\/freopen(\"in.txt\", \"r\", stdin);\n int kase = 1;\n while(scanf(\"%d\", &N) == 1 && N) {\n printf(\"Game %d:\\n\", kase++);\n for(int i = 0; i < N; ++i)\n scanf(\"%d\", &code[i]);\n while(scanf(\"%d\", &guess[0]) == 1) {\n for(int i = 1; i < N; ++i)\n scanf(\"%d\", &guess[i]);\n if(guess[0] == 0) break;\n solve();\n }\n }\n return 0;\n}\n\nMaster-Mind Hints#include \n#include \nusing namespace std;\n\n#define min(a,b) ( (a) < (b) ? (a) : (b) )\n\nconst int maxn = 1111;\nint N;\nint code[maxn];\nint guess[maxn];\nint hash_code[9], hash_guess[9];\n\nvoid solve() {\n int x = 0, y = 0;\n memset(hash_code, 0, sizeof(hash_code));\n memset(hash_guess, 0, sizeof(hash_guess));\n for(int i = 0; i < N; ++i) {\n if(code[i] == guess[i]) {\n ++x;\n } \n ++hash_code[code[i]-1];\n ++hash_guess[guess[i]-1];\n }\n for(int i = 0; i < 9; ++i)\n y += min(hash_code[i], hash_guess[i]);\n printf(\" (%d,%d)\\n\", x, y-x);\n}\n\nint main()\n{\n \/\/freopen(\"in.txt\", \"r\", stdin);\n int kase = 1;\n while(scanf(\"%d\", &N) == 1 && N) {\n printf(\"Game %d:\\n\", kase++);\n for(int i = 0; i < N; ++i)\n scanf(\"%d\", &code[i]);\n while(scanf(\"%d\", &guess[0]) == 1) {\n for(int i = 1; i < N; ++i)\n scanf(\"%d\", &guess[i]);\n if(guess[0] == 0) break;\n solve();\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"cookie.hpp\"\n\nusing namespace cookie;\n\n\/*\nCookie::Cookie(std::string& key, std::string& value)\n : key_(key), value_(value) {\n\n}\n\nCookie::Cookie(std::string& key, std::string& value, std::string& options)\n : key_(key), value_(value), options_(options) {\n\n}\n\nCookie::~Cookie() {\n\n}\n*\/\n\nconst std::string Cookie::no_entry_value_;\n\ninline static bool equiv_strs(std::string& s1, std::string& s2) {\n std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower());\n std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower());\n return s1 == s2;\n}\n\ninline auto Cookie::find(const std::string& keyword) const {\n return std::find_if(data_.begin(), data_.end(), [&keyword](const auto& k) {\n return equiv_strs(k.first, keyword);\n });\n}\n\ninline Cookie::Cookie(const std::string& data, Parser parser) : data_{}, parser_{parser} {\n parse(data);\n}\n\ninline const std::string& Cookie::name() const {\n return data_.at(0).first;\n}\n\ninline const std::string& Cookie::value() const {\n return data_.at(0).second;\n}\n\ninline const std::string& Cookie::expires() const {\n auto it = find(\"Expires\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::max_age() const {\n auto it = find(\"Max-Age\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::domanin() const {\n auto it = find(\"Domain\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::path() const {\n auto it = find(\"Path\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const bool Cookie::is_secure() const noexcept {\n return find(\"Secure\") not_eq data_.end();\n}\n\ninline const bool Cookie::is_http_only() const noexcept {\n return find(\"HttpOnly\") not_eq data_.end();\n}\n\n\/\/ Fill in\nstd::string Cookie::to_string() const {\n std::string cookieString = \"\";\n\n cookieString += \"\";\n\n return cookieString;\n}\n\nCookie::operator std::string () const {\n return to_string();\n}\n\ninline void Cookie::parse(const std::string& data) {\n if(parser_) {\n data_ = parser_(data);\n } else {\n static const std::regex pattern{\"[^;]+\"};\n auto position = std::sregex_iterator(data.begin(), data.end(), pattern);\n auto end = std::sregex_iterator();\n\n \/\/ And more ...\n\n }\n}\n\ninline std::ostream& operator << (std::ostream& output_device, const Cookie& cookie) {\n return output_device << cookie.to_string();\n}\n\n\/\/ ?\nstd::string Cookie::serialize(std::string& key, std::string& value) {\n \/\/if(key.empty())\n\n std::string cookieString = \"\";\n\n cookieString += \"\";\n\n return cookieString;\n}\n\n\/\/ ?\nstd::string Cookie::serialize(std::string& key, std::string& value, std::string& options) {\n\n}\n\n\/\/ ?\nbool Cookie::deserialize() {\n\n}\n\n\/\/ ?\nstd::shared_ptr Cookie::parse(std::string& str, std::string& options) {\n std::shared_ptr cookie(new Cookie());\n\n return cookie;\n}\nRefactored Cookie::find\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"cookie.hpp\"\n\nusing namespace cookie;\n\n\/*\nCookie::Cookie(std::string& key, std::string& value)\n : key_(key), value_(value) {\n\n}\n\nCookie::Cookie(std::string& key, std::string& value, std::string& options)\n : key_(key), value_(value), options_(options) {\n\n}\n\nCookie::~Cookie() {\n\n}\n*\/\n\nconst std::string Cookie::no_entry_value_;\n\ninline auto Cookie::find(const std::string& keyword) const {\n return std::find_if(data_.begin(), data_.end(), [&keyword](const auto& k){\n return std::equal(k.first.begin(), k.first.end(), keyword.begin(), keyword.end(),\n [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);\n });\n });\n}\n\ninline Cookie::Cookie(const std::string& data, Parser parser) : data_{}, parser_{parser} {\n parse(data);\n}\n\ninline const std::string& Cookie::name() const {\n return data_.at(0).first;\n}\n\ninline const std::string& Cookie::value() const {\n return data_.at(0).second;\n}\n\ninline const std::string& Cookie::expires() const {\n auto it = find(\"Expires\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::max_age() const {\n auto it = find(\"Max-Age\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::domanin() const {\n auto it = find(\"Domain\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const std::string& Cookie::path() const {\n auto it = find(\"Path\");\n return (it not_eq data_.end()) ? it->second : no_entry_value_;\n}\n\ninline const bool Cookie::is_secure() const noexcept {\n return find(\"Secure\") not_eq data_.end();\n}\n\ninline const bool Cookie::is_http_only() const noexcept {\n return find(\"HttpOnly\") not_eq data_.end();\n}\n\n\/\/ Fill in\nstd::string Cookie::to_string() const {\n std::string cookieString = \"\";\n\n cookieString += \"\";\n\n return cookieString;\n}\n\nCookie::operator std::string () const {\n return to_string();\n}\n\ninline void Cookie::parse(const std::string& data) {\n if(parser_) {\n data_ = parser_(data);\n } else {\n static const std::regex pattern{\"[^;]+\"};\n auto position = std::sregex_iterator(data.begin(), data.end(), pattern);\n auto end = std::sregex_iterator();\n\n \/\/ And more ...\n\n }\n}\n\ninline std::ostream& operator << (std::ostream& output_device, const Cookie& cookie) {\n return output_device << cookie.to_string();\n}\n\n\/\/ ?\nstd::string Cookie::serialize(std::string& key, std::string& value) {\n \/\/if(key.empty())\n\n std::string cookieString = \"\";\n\n cookieString += \"\";\n\n return cookieString;\n}\n\n\/\/ ?\nstd::string Cookie::serialize(std::string& key, std::string& value, std::string& options) {\n\n}\n\n\/\/ ?\nbool Cookie::deserialize() {\n\n}\n\n\/\/ ?\nstd::shared_ptr Cookie::parse(std::string& str, std::string& options) {\n std::shared_ptr cookie(new Cookie());\n\n return cookie;\n}\n<|endoftext|>"} {"text":"#include \"docking.h\"\n#include \"docks.h\"\n#include \"runtime\/system\/engine.h\"\n#include \"..\/gui_window.h\"\n#include \"core\/logging\/logging.h\"\n\nbool DockingSystem::initialize()\n{\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\n\tauto& scene = _docks[0];\n\tscene->initialize(\"Scene\", true, ImVec2(200.0f, 200.0f), &Docks::render_scene);\n\n\tauto& game = _docks[1];\n\tgame->initialize(\"Game\", true, ImVec2(200.0f, 200.0f), &Docks::render_game);\n\n\tauto& hierarchy = _docks[2];\n\thierarchy->initialize(\"Hierarchy\", true, ImVec2(300.0f, 200.0f), &Docks::render_hierarchy);\n\n\tauto& inspector = _docks[3];\n\tinspector->initialize(\"Inspector\", true, ImVec2(300.0f, 200.0f), &Docks::render_inspector);\n\n\tauto& assets = _docks[4];\n\tassets->initialize(\"Assets\", true, ImVec2(200.0f, 200.0f), &Docks::render_assets);\n\n\tauto& console = _docks[5];\n\tconsole->initialize(\"Console\", true, ImVec2(200.0f, 200.0f), [this](ImVec2 area)\n\t{\n\t\tDocks::render_console(area, *_console_log.get());\n\t});\n\n\tauto& style = _docks[6];\n\tstyle->initialize(\"Style\", true, ImVec2(300.0f, 200.0f), &Docks::render_style);\n\n\tauto engine = core::get_subsystem();\n\tconst auto& windows = engine->get_windows();\n\tauto& window = static_cast(*windows[0]);\n\tauto& dockspace = window.get_dockspace();\n\tdockspace.dock(scene.get(), ImGuiDock::DockSlot::None, 200, true);\n\tdockspace.dock_with(game.get(), scene.get(), ImGuiDock::DockSlot::Tab, 300, false);\n\tdockspace.dock_with(inspector.get(), scene.get(), ImGuiDock::DockSlot::Right, 300, true);\n\tdockspace.dock_with(hierarchy.get(), scene.get(), ImGuiDock::DockSlot::Left, 300, true);\n\tdockspace.dock(assets.get(), ImGuiDock::DockSlot::Bottom, 250, true);\n\tdockspace.dock_with(console.get(), assets.get(), ImGuiDock::DockSlot::Tab, 250, true);\n\tdockspace.dock_with(style.get(), assets.get(), ImGuiDock::DockSlot::Right, 300, true);\n\n\tauto logger = logging::get(\"Log\");\n\tlogger->add_sink(_console_log);\n\n\tstd::function logVersion = [logger]()\n\t{\n\t\tlogger->info() << \"Version 1.0\";\n\t};\n\t_console_log->register_command(\n\t\t\"version\",\n\t\t\"Returns the current version of the Editor.\",\n\t\t{},\n\t\t{},\n\t\tlogVersion\n\t);\n\n\treturn true;\n}\nCleanup.#include \"docking.h\"\n#include \"docks.h\"\n#include \"runtime\/system\/engine.h\"\n#include \"..\/gui_window.h\"\n#include \"core\/logging\/logging.h\"\n\nbool DockingSystem::initialize()\n{\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\t_docks.emplace_back(std::make_unique());\n\n\tauto& scene = _docks[0];\n\tscene->initialize(\"Scene\", true, ImVec2(200.0f, 200.0f), &Docks::render_scene);\n\n\tauto& game = _docks[1];\n\tgame->initialize(\"Game\", true, ImVec2(200.0f, 200.0f), &Docks::render_game);\n\n\tauto& hierarchy = _docks[2];\n\thierarchy->initialize(\"Hierarchy\", true, ImVec2(300.0f, 200.0f), &Docks::render_hierarchy);\n\n\tauto& inspector = _docks[3];\n\tinspector->initialize(\"Inspector\", true, ImVec2(300.0f, 200.0f), &Docks::render_inspector);\n\n\tauto& assets = _docks[4];\n\tassets->initialize(\"Assets\", true, ImVec2(200.0f, 200.0f), &Docks::render_assets);\n\n\tauto& console = _docks[5];\n\tconsole->initialize(\"Console\", true, ImVec2(200.0f, 200.0f), [this](ImVec2 area)\n\t{\n\t\tDocks::render_console(area, *_console_log.get());\n\t});\n\n\tauto& style = _docks[6];\n\tstyle->initialize(\"Style\", true, ImVec2(300.0f, 200.0f), &Docks::render_style);\n\n\tauto engine = core::get_subsystem();\n\tconst auto& windows = engine->get_windows();\n\tauto& window = static_cast(*windows[0]);\n\tauto& dockspace = window.get_dockspace();\n\tdockspace.dock(scene.get(), ImGuiDock::DockSlot::None, 200, true);\n\tdockspace.dock_with(game.get(), scene.get(), ImGuiDock::DockSlot::Tab, 300, false);\n\tdockspace.dock_with(inspector.get(), scene.get(), ImGuiDock::DockSlot::Right, 300, true);\n\tdockspace.dock_with(hierarchy.get(), scene.get(), ImGuiDock::DockSlot::Left, 300, true);\n\tdockspace.dock(console.get(), ImGuiDock::DockSlot::Bottom, 250, true);\n\tdockspace.dock_with(assets.get(), console.get(), ImGuiDock::DockSlot::Tab, 250, true);\n\tdockspace.dock_with(style.get(), assets.get(), ImGuiDock::DockSlot::Right, 300, true);\n\n\tauto logger = logging::get(\"Log\");\n\tlogger->add_sink(_console_log);\n\n\tstd::function logVersion = [logger]()\n\t{\n\t\tlogger->info() << \"Version 1.0\";\n\t};\n\t_console_log->register_command(\n\t\t\"version\",\n\t\t\"Returns the current version of the Editor.\",\n\t\t{},\n\t\t{},\n\t\tlogVersion\n\t);\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"#include \"Riostream.h\" \n\n#include \"Coefficient.h\" \n#include \"RooAbsReal.h\" \n#include \"RooAbsCategory.h\"\n#include \"RooCategory.h\" \n#include \n#include \"TMath.h\" \n\nClassImp(doofit::roofit::functions::bdecay::Coefficient) \n\nnamespace doofit {\nnamespace roofit {\nnamespace functions {\nnamespace bdecay {\n\nCoefficient::Coefficient(const std::string& name, \n RooAbsReal& _cp_coeff_,\n CoeffType _coeff_type_,\n RooAbsCategory& _tag_,\n RooAbsReal& _eta_,\n RooAbsReal& _avg_eta_,\n RooAbsReal& _p0_,\n RooAbsReal& _p1_,\n RooAbsReal& _delta_p0_,\n RooAbsReal& _delta_p1_,\n RooAbsReal& _production_asym_,\n int _tag_sign_) :\n RooAbsReal(name.c_str(),name.c_str()), \n cp_coeff_(\"cp_coeff_\",\"cp_coeff_\",this,_cp_coeff_),\n coeff_type_(_coeff_type_),\n tag_(\"tag_\",\"tag_\",this,_tag_),\n eta_(\"eta_\",\"eta_\",this,_eta_),\n avg_eta_(\"avg_eta_\",\"avg_eta_\",this,_avg_eta_),\n p0_(\"p0_\",\"p0_\",this,_p0_),\n p1_(\"p1_\",\"p1_\",this,_p1_),\n delta_p0_(\"delta_p0_\",\"delta_p0_\",this,_delta_p0_),\n delta_p1_(\"delta_p1_\",\"delta_p1_\",this,_delta_p1_),\n production_asym_(\"production_asym_\",\"production_asym_\",this,_production_asym_),\n tag_sign_(_tag_sign_)\n{ \n} \n\n\nCoefficient::Coefficient(const Coefficient& other, const char* name) : \n RooAbsReal(other,name), \n cp_coeff_(\"cp_coeff_\",this,other.cp_coeff_),\n coeff_type_(other.coeff_type_),\n tag_(\"tag_\",this,other.tag_),\n eta_(\"eta_\",this,other.eta_),\n avg_eta_(\"avg_eta_\",this,other.avg_eta_),\n p0_(\"p0_\",this,other.p0_),\n p1_(\"p1_\",this,other.p1_),\n delta_p0_(\"delta_p0_\",this,other.delta_p0_),\n delta_p1_(\"delta_p1_\",this,other.delta_p1_),\n production_asym_(\"production_asym_\",this,other.production_asym_),\n tag_sign_(other.tag_sign_)\n{ \n} \n\n\nDouble_t Coefficient::evaluate() const \n{ \n return evaluate(cp_coeff_, coeff_type_, tag_, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n}\n\n\nInt_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* \/*rangeName*\/) const \n{ \n \/\/ debug\n \/\/ std::printf(\"CHECK: In %s line %u (%s): #Vars = %d : allVars = \", __func__, __LINE__, __FILE__, allVars.getSize());\n \/\/ allVars.Print();\n\n if (matchArgs(allVars, analVars, tag_)) return 1 ;\n return 0 ;\n} \n\nInt_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* \/*rangeName*\/) const \n{ \n \/\/ debug\n std::printf(\"CHECK: In %s line %u (%s): #Vars = %d : allVars = \", __func__, __LINE__, __FILE__, allVars.getSize());\n allVars.Print();\n if (normSet) normSet->Print();\n\n if (matchArgs(allVars, analVars, tag_)) return 1 ;\n return 0 ;\n} \n\nDouble_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const \n{ \n \/\/ debug\n \/\/ std::printf(\"CHECK: In %s line %u (%s): Range: %s : Code: %d \\n\", __func__, __LINE__, __FILE__, rangeName, code);\n \n \/\/ first return analytical integral for defined range\n if (rangeName){\n double integral = 0;\n if (isTagInRange(tag_, +1, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0B0 : \" << integral << std::endl;\n }\n if (isTagInRange(tag_, -1, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0barB0 : \" << integral << std::endl;\n }\n if (isTagInRange(tag_, 0, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0barB0 : \" << integral << std::endl;\n }\n return integral;\n }\n else{\n if (code == 1){\n double integral = 0.;\n if (hasTagState(tag_, +1)) integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n if (hasTagState(tag_, -1)) integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n if (hasTagState(tag_, 0)) integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" : OS Integral : \" << integral << std::endl;\n return integral;\n }\n return 0;\n }\n\n \/\/ OLD: Explicit integrals\n \/\/ if (coeff_type_ == kSin){\n \/\/ return +2.0 * production_asym_ * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kCos){\n \/\/ return -2.0 * production_asym_ * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kSinh){\n \/\/ return 2.0 * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kCosh){\n \/\/ return 2.0 * cp_coeff_;\n \/\/ }\n \/\/ else{\n \/\/ std::printf(\"ERROR: In %s line %u (%s) : No valid coefficent! \\n\", __func__, __LINE__, __FILE__);\n \/\/ return 0;\n \/\/ abort();\n \/\/ }\n} \n\n\nstd::pair Coefficient::calibrate(double eta, double avg_eta, double p0, double p1, double delta_p0, double delta_p1) const\n{\n double eta_cal = 0;\n double eta_cal_b = 0;\n double eta_cal_bbar = 0;\n\n \/\/ calculate calibrated average eta\n eta_cal = p0 + p1 * ( eta - avg_eta );\n \n \/\/ if eta is larger or equal 0.5 return 0.5\n if (eta >= 0.5){\n eta_cal = 0.5;\n eta_cal_b = 0.5;\n eta_cal_bbar = 0.5;\n }\n else{\n \/\/ calibrate eta\n eta_cal_b = p0 + 0.5 * delta_p0 + ( p1 + 0.5 * delta_p1 ) * ( eta - avg_eta );\n eta_cal_bbar = p0 - 0.5 * delta_p0 + ( p1 - 0.5 * delta_p1 ) * ( eta - avg_eta );\n }\n \/\/ if calibrated average eta is larger or equal 0.5 return 0.5\n if (eta_cal >= 0.5){\n eta_cal_b = 0.5;\n eta_cal_bbar = 0.5;\n }\n \/\/ if calibrated eta is smaller than 0 return 0\n if (eta_cal_b < 0.0) eta_cal_b = 0;\n if (eta_cal_bbar < 0.0) eta_cal_bbar = 0;\n\n \/\/ the next few lines set every eta value (avg and high\/low from asymmetries) to zero\n \/\/ if only one of them is below zero. This seems to introduce a fit bias on our CP\n \/\/ observables. (CC)\n \/\/ if (eta_cal < 0.0 || eta_cal_b < 0.0 || eta_cal_bbar < 0.0){\n \/\/ eta_cal_b = 0.0;\n \/\/ eta_cal_bbar = 0.0;\n \/\/ }\n return std::make_pair(eta_cal_b, eta_cal_bbar);\n}\n\n\nDouble_t Coefficient::evaluate(double cp_coeff,\n CoeffType coeff_type,\n int tag,\n double eta,\n double avg_eta,\n double p0,\n double p1,\n double delta_p0,\n double delta_p1,\n double production_asym,\n int tag_sign) const \n{\n \/\/ calibrate single tagger\n std::pair calibrated_mistag = calibrate(eta, avg_eta, p0, p1, delta_p0, delta_p1);\n\n double eta_b = calibrated_mistag.first;\n double eta_bbar = calibrated_mistag.second;\n\n \/\/ calculate coefficients\n if (coeff_type == kSin){\n return -1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );\n }\n else if (coeff_type == kCos){\n return +1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );\n }\n else if (coeff_type == kSinh){\n return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );\n }\n else if (coeff_type == kCosh){\n return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );\n }\n else{\n std::cout << \"ERROR\\t\" << \"Coefficient::evaluate(): No valid coefficient type!\" << std::endl;\n abort();\n }\n}\n\n\nbool Coefficient::isTagInRange(const RooCategoryProxy& tag, int tag_state, const char* rangeName) const \n{\n return dynamic_cast(tag.arg()).isStateInRange(rangeName, tag.arg().lookupType(tag_state)->GetName());\n}\n\n\nbool Coefficient::hasTagState(const RooCategoryProxy& tag, int tag_state) const\n{ \n return dynamic_cast(tag.arg()).isValidIndex(tag_state);\n}\n\n\nint Coefficient::getIndex(const RooCategoryProxy& tag) const\n{\n return dynamic_cast(tag.arg()).getIndex();\n}\n\n\n} \/\/ namespace bdecay\n} \/\/ namespace functions\n} \/\/ namespace roofit\n} \/\/ namespace doofit\nroofit::functions::bdecay::Coefficient: fixed isTagInRange method#include \"Riostream.h\" \n\n#include \"Coefficient.h\" \n#include \"RooAbsReal.h\" \n#include \"RooAbsCategory.h\"\n#include \"RooCategory.h\" \n#include \n#include \"TMath.h\" \n\nClassImp(doofit::roofit::functions::bdecay::Coefficient) \n\nnamespace doofit {\nnamespace roofit {\nnamespace functions {\nnamespace bdecay {\n\nCoefficient::Coefficient(const std::string& name, \n RooAbsReal& _cp_coeff_,\n CoeffType _coeff_type_,\n RooAbsCategory& _tag_,\n RooAbsReal& _eta_,\n RooAbsReal& _avg_eta_,\n RooAbsReal& _p0_,\n RooAbsReal& _p1_,\n RooAbsReal& _delta_p0_,\n RooAbsReal& _delta_p1_,\n RooAbsReal& _production_asym_,\n int _tag_sign_) :\n RooAbsReal(name.c_str(),name.c_str()), \n cp_coeff_(\"cp_coeff_\",\"cp_coeff_\",this,_cp_coeff_),\n coeff_type_(_coeff_type_),\n tag_(\"tag_\",\"tag_\",this,_tag_),\n eta_(\"eta_\",\"eta_\",this,_eta_),\n avg_eta_(\"avg_eta_\",\"avg_eta_\",this,_avg_eta_),\n p0_(\"p0_\",\"p0_\",this,_p0_),\n p1_(\"p1_\",\"p1_\",this,_p1_),\n delta_p0_(\"delta_p0_\",\"delta_p0_\",this,_delta_p0_),\n delta_p1_(\"delta_p1_\",\"delta_p1_\",this,_delta_p1_),\n production_asym_(\"production_asym_\",\"production_asym_\",this,_production_asym_),\n tag_sign_(_tag_sign_)\n{ \n} \n\n\nCoefficient::Coefficient(const Coefficient& other, const char* name) : \n RooAbsReal(other,name), \n cp_coeff_(\"cp_coeff_\",this,other.cp_coeff_),\n coeff_type_(other.coeff_type_),\n tag_(\"tag_\",this,other.tag_),\n eta_(\"eta_\",this,other.eta_),\n avg_eta_(\"avg_eta_\",this,other.avg_eta_),\n p0_(\"p0_\",this,other.p0_),\n p1_(\"p1_\",this,other.p1_),\n delta_p0_(\"delta_p0_\",this,other.delta_p0_),\n delta_p1_(\"delta_p1_\",this,other.delta_p1_),\n production_asym_(\"production_asym_\",this,other.production_asym_),\n tag_sign_(other.tag_sign_)\n{ \n} \n\n\nDouble_t Coefficient::evaluate() const \n{ \n return evaluate(cp_coeff_, coeff_type_, tag_, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n}\n\n\nInt_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* \/*rangeName*\/) const \n{ \n \/\/ debug\n \/\/ std::printf(\"CHECK: In %s line %u (%s): #Vars = %d : allVars = \", __func__, __LINE__, __FILE__, allVars.getSize());\n \/\/ allVars.Print();\n\n if (matchArgs(allVars, analVars, tag_)) return 1 ;\n return 0 ;\n} \n\nInt_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* \/*rangeName*\/) const \n{ \n \/\/ debug\n std::printf(\"CHECK: In %s line %u (%s): #Vars = %d : allVars = \", __func__, __LINE__, __FILE__, allVars.getSize());\n allVars.Print();\n if (normSet) normSet->Print();\n\n if (matchArgs(allVars, analVars, tag_)) return 1 ;\n return 0 ;\n} \n\nDouble_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const \n{ \n \/\/ debug\n \/\/ std::printf(\"CHECK: In %s line %u (%s): Range: %s : Code: %d \\n\", __func__, __LINE__, __FILE__, rangeName, code);\n \n \/\/ first return analytical integral for defined range\n if (rangeName){\n double integral = 0;\n if (isTagInRange(tag_, +1, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0B0 : \" << integral << std::endl;\n }\n if (isTagInRange(tag_, -1, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0barB0 : \" << integral << std::endl;\n }\n if (isTagInRange(tag_, 0, rangeName)){\n integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" Range: B0barB0 : \" << integral << std::endl;\n }\n return integral;\n }\n else{\n if (code == 1){\n double integral = 0.;\n if (hasTagState(tag_, +1)) integral += evaluate(cp_coeff_, coeff_type_, +1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n if (hasTagState(tag_, -1)) integral += evaluate(cp_coeff_, coeff_type_, -1, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n if (hasTagState(tag_, 0)) integral += evaluate(cp_coeff_, coeff_type_, 0, eta_, avg_eta_, p0_, p1_, delta_p0_, delta_p1_, production_asym_, tag_sign_);\n \/\/ debug\n \/\/ std::cout << \"Coeff: \" << coeff_type_ << \" : OS Integral : \" << integral << std::endl;\n return integral;\n }\n return 0;\n }\n\n \/\/ OLD: Explicit integrals\n \/\/ if (coeff_type_ == kSin){\n \/\/ return +2.0 * production_asym_ * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kCos){\n \/\/ return -2.0 * production_asym_ * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kSinh){\n \/\/ return 2.0 * cp_coeff_;\n \/\/ }\n \/\/ else if (coeff_type_ == kCosh){\n \/\/ return 2.0 * cp_coeff_;\n \/\/ }\n \/\/ else{\n \/\/ std::printf(\"ERROR: In %s line %u (%s) : No valid coefficent! \\n\", __func__, __LINE__, __FILE__);\n \/\/ return 0;\n \/\/ abort();\n \/\/ }\n} \n\n\nstd::pair Coefficient::calibrate(double eta, double avg_eta, double p0, double p1, double delta_p0, double delta_p1) const\n{\n double eta_cal = 0;\n double eta_cal_b = 0;\n double eta_cal_bbar = 0;\n\n \/\/ calculate calibrated average eta\n eta_cal = p0 + p1 * ( eta - avg_eta );\n \n \/\/ if eta is larger or equal 0.5 return 0.5\n if (eta >= 0.5){\n eta_cal = 0.5;\n eta_cal_b = 0.5;\n eta_cal_bbar = 0.5;\n }\n else{\n \/\/ calibrate eta\n eta_cal_b = p0 + 0.5 * delta_p0 + ( p1 + 0.5 * delta_p1 ) * ( eta - avg_eta );\n eta_cal_bbar = p0 - 0.5 * delta_p0 + ( p1 - 0.5 * delta_p1 ) * ( eta - avg_eta );\n }\n \/\/ if calibrated average eta is larger or equal 0.5 return 0.5\n if (eta_cal >= 0.5){\n eta_cal_b = 0.5;\n eta_cal_bbar = 0.5;\n }\n \/\/ if calibrated eta is smaller than 0 return 0\n if (eta_cal_b < 0.0) eta_cal_b = 0;\n if (eta_cal_bbar < 0.0) eta_cal_bbar = 0;\n\n \/\/ the next few lines set every eta value (avg and high\/low from asymmetries) to zero\n \/\/ if only one of them is below zero. This seems to introduce a fit bias on our CP\n \/\/ observables. (CC)\n \/\/ if (eta_cal < 0.0 || eta_cal_b < 0.0 || eta_cal_bbar < 0.0){\n \/\/ eta_cal_b = 0.0;\n \/\/ eta_cal_bbar = 0.0;\n \/\/ }\n return std::make_pair(eta_cal_b, eta_cal_bbar);\n}\n\n\nDouble_t Coefficient::evaluate(double cp_coeff,\n CoeffType coeff_type,\n int tag,\n double eta,\n double avg_eta,\n double p0,\n double p1,\n double delta_p0,\n double delta_p1,\n double production_asym,\n int tag_sign) const \n{\n \/\/ calibrate single tagger\n std::pair calibrated_mistag = calibrate(eta, avg_eta, p0, p1, delta_p0, delta_p1);\n\n double eta_b = calibrated_mistag.first;\n double eta_bbar = calibrated_mistag.second;\n\n \/\/ calculate coefficients\n if (coeff_type == kSin){\n return -1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );\n }\n else if (coeff_type == kCos){\n return +1.0 * cp_coeff * ( tag_sign * tag - production_asym * ( 1.0 - tag_sign * tag * eta_b + tag_sign * tag * eta_bbar ) - tag_sign * tag * ( eta_b + eta_bbar ) );\n }\n else if (coeff_type == kSinh){\n return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );\n }\n else if (coeff_type == kCosh){\n return cp_coeff * ( 1.0 - tag_sign * tag * production_asym * ( 1.0 - eta_b - eta_bbar ) - tag_sign * tag * ( eta_b - eta_bbar ) );\n }\n else{\n std::cout << \"ERROR\\t\" << \"Coefficient::evaluate(): No valid coefficient type!\" << std::endl;\n abort();\n }\n}\n\n\nbool Coefficient::isTagInRange(const RooCategoryProxy& tag, int tag_state, const char* rangeName) const \n{\n if (tag.arg().lookupType(tag_state) == nullptr){\n return false;\n }\n else{\n return dynamic_cast(tag.arg()).isStateInRange(rangeName, tag.arg().lookupType(tag_state)->GetName());\n }\n}\n\n\nbool Coefficient::hasTagState(const RooCategoryProxy& tag, int tag_state) const\n{ \n return dynamic_cast(tag.arg()).isValidIndex(tag_state);\n}\n\n\nint Coefficient::getIndex(const RooCategoryProxy& tag) const\n{\n return dynamic_cast(tag.arg()).getIndex();\n}\n\n\n} \/\/ namespace bdecay\n} \/\/ namespace functions\n} \/\/ namespace roofit\n} \/\/ namespace doofit\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n\nnamespace rack {\nnamespace logger {\n\n\nstatic FILE *outputFile = NULL;\nstatic std::chrono::high_resolution_clock::time_point startTime;\nstatic std::mutex logMutex;\n\n\nvoid init() {\n\tstartTime = std::chrono::high_resolution_clock::now();\n\tif (settings::devMode) {\n\t\toutputFile = stderr;\n\t}\n\telse {\n\t\tstd::string logFilename = asset::user(\"log.txt\");\n\t\toutputFile = fopen(logFilename.c_str(), \"w\");\n\t}\n}\n\nvoid destroy() {\n\tif (outputFile != stderr) {\n\t\tfclose(outputFile);\n\t}\n}\n\nstatic const char* const levelLabels[] = {\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"fatal\"\n};\n\nstatic const int levelColors[] = {\n\t35,\n\t34,\n\t33,\n\t31\n};\n\nstatic void logVa(Level level, const char *filename, int line, const char *format, va_list args) {\n\tstd::lock_guard lock(logMutex);\n\n\tauto nowTime = std::chrono::high_resolution_clock::now();\n\tint duration = std::chrono::duration_cast(nowTime - startTime).count();\n\tif (outputFile == stderr)\n\t\tfprintf(outputFile, \"\\x1B[%dm\", levelColors[level]);\n\tfprintf(outputFile, \"[%.03f %s %s:%d] \", duration \/ 1000.0, levelLabels[level], filename, line);\n\tif (outputFile == stderr)\n\t\tfprintf(outputFile, \"\\x1B[0m\");\n\tvfprintf(outputFile, format, args);\n\tfprintf(outputFile, \"\\n\");\n\tfflush(outputFile);\n}\n\nvoid log(Level level, const char *filename, int line, const char *format, ...) {\n\tva_list args;\n\tva_start(args, format);\n\tlogVa(level, filename, line, format, args);\n\tva_end(args);\n}\n\n\n} \/\/ namespace logger\n} \/\/ namespace rack\nAdd error message to stderr if cannot open log.txt file.#include \n#include \n#include \n#include \n#include \n\n\nnamespace rack {\nnamespace logger {\n\n\nstatic FILE *outputFile = NULL;\nstatic std::chrono::high_resolution_clock::time_point startTime;\nstatic std::mutex logMutex;\n\n\nvoid init() {\n\tstartTime = std::chrono::high_resolution_clock::now();\n\tif (settings::devMode) {\n\t\toutputFile = stderr;\n\t\treturn;\n\t}\n\n\tstd::string logFilename = asset::user(\"log.txt\");\n\toutputFile = fopen(logFilename.c_str(), \"w\");\n\tif (!outputFile) {\n\t\tfprintf(stderr, \"Could not open log at %s\\n\", logFilename.c_str());\n\t}\n}\n\nvoid destroy() {\n\tif (outputFile != stderr) {\n\t\tfclose(outputFile);\n\t}\n}\n\nstatic const char* const levelLabels[] = {\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"fatal\"\n};\n\nstatic const int levelColors[] = {\n\t35,\n\t34,\n\t33,\n\t31\n};\n\nstatic void logVa(Level level, const char *filename, int line, const char *format, va_list args) {\n\tstd::lock_guard lock(logMutex);\n\n\tauto nowTime = std::chrono::high_resolution_clock::now();\n\tint duration = std::chrono::duration_cast(nowTime - startTime).count();\n\tif (outputFile == stderr)\n\t\tfprintf(outputFile, \"\\x1B[%dm\", levelColors[level]);\n\tfprintf(outputFile, \"[%.03f %s %s:%d] \", duration \/ 1000.0, levelLabels[level], filename, line);\n\tif (outputFile == stderr)\n\t\tfprintf(outputFile, \"\\x1B[0m\");\n\tvfprintf(outputFile, format, args);\n\tfprintf(outputFile, \"\\n\");\n\tfflush(outputFile);\n}\n\nvoid log(Level level, const char *filename, int line, const char *format, ...) {\n\tva_list args;\n\tva_start(args, format);\n\tlogVa(level, filename, line, format, args);\n\tva_end(args);\n}\n\n\n} \/\/ namespace logger\n} \/\/ namespace rack\n<|endoftext|>"} {"text":"\/\/ REQUIRES: x86-registered-target\n\/\/ RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s\n\n\/\/ FIXME: This testcase shouldn't rely on assembly emission.\n\/\/CHECK: LpubTypes_begin[[SECNUM:[0-9]:]]\n\/\/CHECK: .asciz \"G\"\n\/\/CHECK-NEXT: .long 0\n\/\/CHECK-NEXT: LpubTypes_end[[SECNUM]]\n\nclass G {\npublic:\n void foo();\n};\n\nvoid G::foo() {\n}\nDebugInfo: Remove debug-info-pubtypes.ccp - pubnames\/pubtypes are adequately tested in LLVM now.<|endoftext|>"} {"text":"#ifndef UVPP_ZSOCK_HPP\n#define UVPP_ZSOCK_HPP\n\n#include \"uvpp.hpp\"\n\nnamespace uvpp\n{\n class ZsockWatcher\n {\n public:\n ZsockWatcher(Loop& uvloop)\n : m_zsock(nullptr), m_events(0),\n m_prepare(uvloop), m_check(uvloop), m_idle(uvloop),\n m_poll(uvloop)\n {\n m_prepare.set_callback([this](){\n int revents = get_revents(m_zsock, m_events);\n if (revents) {\n \/\/ idle ensures that libuv will not block\n m_idle.start();\n }\n });\n\n m_check.set_callback([this](){\n m_idle.stop();\n int revents = get_revents(m_zsock, m_events);\n if (revents) {\n m_callback();\n }\n });\n\n m_idle.set_callback([](){});\n m_poll.set_callback([](int status, int events){});\n }\n\n ZsockWatcher(Loop& uvloop, void *zsock)\n : ZsockWatcher(uvloop)\n {\n init(zsock);\n }\n\n void init(void *zsock)\n {\n assert(m_zsock==nullptr);\n\n m_zsock = zsock;\n\n uv_os_sock_t sockfd;\n size_t optlen = sizeof(sockfd);\n int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);\n assert(rc==0);\n\n m_poll.init(sockfd);\n }\n\n void set_callback(BasicCallback cb)\n {\n m_callback = cb;\n }\n\n void start(int events = UV_READABLE)\n {\n assert(m_zsock != nullptr);\n\n m_events = events;\n m_prepare.start();\n m_check.start();\n m_poll.start(m_events ? UV_READABLE : 0);\n }\n\n void stop()\n {\n m_prepare.stop();\n m_check.stop();\n m_idle.stop();\n m_poll.stop();\n }\n\n private:\n int get_revents(void *zsock, int events)\n {\n int revents = 0;\n\n int zmq_events;\n size_t optlen = sizeof(zmq_events);\n int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);\n\n if (rc==-1) {\n \/\/ on error, make callback get called\n return events;\n }\n\n if (zmq_events & ZMQ_POLLOUT)\n revents |= events & UV_WRITABLE;\n if (zmq_events & ZMQ_POLLIN)\n revents |= events & UV_READABLE;\n\n return revents;\n }\n\n private:\n BasicCallback m_callback;\n\n void *m_zsock;\n int m_events;\n Prepare m_prepare;\n Check m_check;\n Idle m_idle;\n Poll m_poll;\n };\n}\n\n#endif\nimplement alternate Zsock watcher#ifndef UVPP_ZSOCK_HPP\n#define UVPP_ZSOCK_HPP\n\n#include \"uvpp.hpp\"\n\nnamespace uvpp\n{\n class ZsockWatcher\n {\n public:\n ZsockWatcher(Loop& uvloop)\n : m_zsock(nullptr), m_events(0),\n m_prepare(uvloop), m_check(uvloop), m_idle(uvloop),\n m_poll(uvloop)\n {\n m_prepare.set_callback([this](){\n int revents = get_revents(m_zsock, m_events);\n if (revents) {\n \/\/ idle ensures that libuv will not block\n m_idle.start();\n }\n });\n\n m_check.set_callback([this](){\n m_idle.stop();\n int revents = get_revents(m_zsock, m_events);\n if (revents) {\n m_callback();\n }\n });\n\n m_idle.set_callback([](){});\n m_poll.set_callback([](int status, int events){});\n }\n\n ZsockWatcher(Loop& uvloop, void *zsock)\n : ZsockWatcher(uvloop)\n {\n init(zsock);\n }\n\n void init(void *zsock)\n {\n assert(m_zsock==nullptr);\n\n m_zsock = zsock;\n\n uv_os_sock_t sockfd;\n size_t optlen = sizeof(sockfd);\n int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);\n assert(rc==0);\n\n m_poll.init(sockfd);\n }\n\n void set_callback(BasicCallback cb)\n {\n m_callback = cb;\n }\n\n void start(int events = UV_READABLE)\n {\n assert(m_zsock != nullptr);\n\n m_events = events;\n m_prepare.start();\n m_check.start();\n m_poll.start(m_events ? UV_READABLE : 0);\n }\n\n void stop()\n {\n m_prepare.stop();\n m_check.stop();\n m_idle.stop();\n m_poll.stop();\n }\n\n private:\n int get_revents(void *zsock, int events)\n {\n int revents = 0;\n\n int zmq_events;\n size_t optlen = sizeof(zmq_events);\n int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);\n\n if (rc==-1) {\n \/\/ on error, make callback get called\n return events;\n }\n\n if (zmq_events & ZMQ_POLLOUT)\n revents |= events & UV_WRITABLE;\n if (zmq_events & ZMQ_POLLIN)\n revents |= events & UV_READABLE;\n\n return revents;\n }\n\n private:\n BasicCallback m_callback;\n\n void *m_zsock;\n int m_events;\n Prepare m_prepare;\n Check m_check;\n Idle m_idle;\n Poll m_poll;\n };\n\n \/\/ alternate implementation that doesn't use prepare and check watchers.\n \/\/ after performing send on this zsock, you need to call Zsock::check()\n class Zsock\n {\n public:\n Zsock(Loop& uvloop)\n : m_zsock(nullptr), m_events(0),\n m_idle(uvloop), m_poll(uvloop)\n {\n m_idle.set_callback([this](){\n int revents = get_revents(m_zsock, m_events);\n if (revents) {\n m_callback();\n } else {\n \/\/ set level low\n m_idle.stop();\n }\n });\n\n m_poll.set_callback([this](int status, int events){\n \/\/ set level high\n m_idle.start();\n });\n }\n\n Zsock(Loop& uvloop, void *zsock)\n : Zsock(uvloop)\n {\n init(zsock);\n }\n\n void check()\n {\n m_idle.start();\n }\n\n void init(void *zsock)\n {\n assert(m_zsock==nullptr);\n\n m_zsock = zsock;\n\n uv_os_sock_t sockfd;\n size_t optlen = sizeof(sockfd);\n int rc = zmq_getsockopt(zsock, ZMQ_FD, &sockfd, &optlen);\n assert(rc==0);\n\n m_poll.init(sockfd);\n }\n\n void set_callback(BasicCallback cb)\n {\n m_callback = cb;\n }\n\n void start(int events = UV_READABLE)\n {\n assert(m_zsock != nullptr);\n\n m_events = events;\n m_poll.start(m_events ? UV_READABLE : 0);\n }\n\n void stop()\n {\n m_idle.stop();\n m_poll.stop();\n }\n\n private:\n int get_revents(void *zsock, int events)\n {\n int revents = 0;\n\n int zmq_events;\n size_t optlen = sizeof(zmq_events);\n int rc = zmq_getsockopt(zsock, ZMQ_EVENTS, &zmq_events, &optlen);\n\n if (rc==-1) {\n \/\/ on error, make callback get called\n return events;\n }\n\n if (zmq_events & ZMQ_POLLOUT)\n revents |= events & UV_WRITABLE;\n if (zmq_events & ZMQ_POLLIN)\n revents |= events & UV_READABLE;\n\n return revents;\n }\n\n private:\n BasicCallback m_callback;\n\n void *m_zsock;\n int m_events;\n Idle m_idle;\n Poll m_poll;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"..\/include\/pixkit-ml.hpp\"\n\nusing namespace std;\n\ndouble Euclidean_Distance(const vector& v1, const vector& v2){\n\tassert(v1.size() == v2.size());\n\tdouble ret = 0.0;\n\tfor (vector::size_type i = 0; i != v1.size(); ++i){\n\t\tret += (v1[i] - v2[i]) * (v1[i] - v2[i]);\n\t}\n\treturn sqrt(ret);\n}\nvoid DistanceMatrix(std::vector >& dm, const std::vector &dataset,const std::vector &sample){\n\tfor ( vector::size_type i = 0; i != sample.size(); ++i){\n\t\tvector DM_data;\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j){\n\t\t\tDM_data.push_back(Euclidean_Distance(sample[i].features, dataset[j].features));\n\t\t}\n\t\tdm.push_back(DM_data);\n\t}\n}\nvector kappa_Matrix(const vector& v1, const vector& v2, vector& kappa)\n{\t\n\tassert(v1.size() == v2.size()); \/\/featureƥn@P test[i].features.size()\n\n\tfor (vector::size_type i = 0; i != v1.size(); ++i)\n\t{\n\t\tkappa[i] +=sqrt((v1[i] - v2[i]) * (v1[i] - v2[i])) ;\n\t}\n\n\treturn (kappa);\n\n}\n\nvoid BandwidthMatrix(vector >& Bw, const vector& sample, const vector& dataset)\n{\n\n\tfor (vector::size_type i = 0; i !=sample.size(); ++i)\n\t{\n\t\tvector kappa_data,kappa(sample[i].features.size());\n\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j)\n\t\t{\n\n\n\t\t\tkappa_data=kappa_Matrix(sample[i].features, dataset[j].features,kappa);\n\n\t\t}\n\n\t\tBw.push_back(kappa_data);\n\n\t}\n\n\n}\n\nvoid Tradition_KNN_Process(vector& sample, const vector& dataset, const vector >& dm, unsigned int k){\n\tfor (vector::size_type i = 0; i != sample.size(); ++i){\n\t\tmultimap dts;\n\t\tfor (vector::size_type j = 0; j != dm[i].size(); ++j){\n\t\t\tif (dts.size() < k){\n\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber)); \n\t\t\t}else{\n\t\t\t\tmultimap::iterator it = dts.end();\n\t\t\t\t--it;\n\t\t\t\tif (dm[i][j] < (it->first)){\n\t\t\t\t\tdts.erase(it);\n\t\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmap tds;\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit){\n\t\t\t++tds[cit->second];\n\t\t\tif (tds[cit->second] > weight){\n\t\t\t\tweight = tds[cit->second];\n\t\t\t\ttype = cit->second;\n\t\t\t}\n\t\t}\n\t\tfor (map::const_iterator cit = tds.begin(); cit != tds.end(); ++cit){\n\t\t\tcout<first <<\"=\"<second<<'\\n'<& sample, const vector& dataset, const vector >& dm, unsigned int k)\n{\n\tfor (vector::size_type i = 0; i != sample.size(); ++i)\n\t{\n\t\tmultimap dts;\n\t\tfor (vector::size_type j = 0; j != dm[i].size(); ++j)\n\t\t{\n\t\t\tif (dts.size() < k ) \n\t\t\t{\n\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber)); \n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmultimap::iterator it = dts.end();\n\t\t\t\t--it;\n\t\t\t\tif (dm[i][j] < (it->first))\n\t\t\t\t{\n\t\t\t\t\tdts.erase(it);\n\t\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmap tds,fin;\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\t\tdouble now_weight = 0.0;\n\t\tdouble total_weight= 0.0;\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t{\n\n\t\t\tif (cit->first==0)\n\t\t\t{\n\t\t\t\ttds[cit->second] += 1.0 \/ (cit->first+1);\n\t\t\t\ttotal_weight=total_weight+(1.0 \/ (cit->first+1));\n\n\t\t\t}else{\n\n\t\t\t\ttds[cit->second] += 1.0 \/ cit->first;\n\t\t\t\ttotal_weight=total_weight+(1.0 \/ (cit->first));\n\t\t\t}\n\n\n\n\n\t\t}\n\n\t\tfor (map::const_iterator cit = tds.begin(); cit != tds.end(); ++cit)\n\t\t{\n\n\t\t\tnow_weight=(cit->second\/total_weight);\n\n\t\t\tif (now_weight > weight)\n\t\t\t{\n\t\t\t\tweight = now_weight;\n\t\t\t\ttype = cit->first;\n\n\t\t\t}\n\n\t\t}\n\n\t\tsample[i].classnumber = type;\n\t\tcout<<\"Result Class = \"<& sample, const vector& dataset, const vector >& dm,const vector >& Bw)\n{\n\tfor (vector::size_type i = 0; i != sample.size(); ++i)\n\t{\n\t\tmultimap dts,dist,dist1;\n\t\tmap tds,fin,merbership,countnmber;\n\t\t\n\n\t\tfor (vector::size_type k = 0; k != dm[i].size(); ++k)\n\t\t{\n\t\t\tdist.insert(make_pair(dm[i][k], dataset[k].classnumber));\n\n\t\t}\n\n\n\t\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j)\n\t\t{\n\t\t\tdouble d=0.0;\n\t\t\tfor (vector::size_type x = 0; x != Bw[i].size(); ++x)\n\t\t\t{\n\t\t\t\tif (Bw[i][x]==0)\n\t\t\t\t{\n\t\t\t\t\td+=(dataset.size()\/(2))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\t\n\t\t\t\t\td+=(dataset.size()\/(2*Bw[i][x]))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\t\t\td=d+(1\/dataset.size())*exp(-d);\n\n\t\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t\t{\n\n\t\t\t\tif (cit->first==0)\n\t\t\t\t{\n\t\t\t\t\ttds[cit->second] += 1.0 \/ (cit->first+1);\n\n\t\t\t\t}else{\n\n\t\t\t\t\ttds[cit->second] += 1.0 \/ cit->first;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t{\n\n\t\t\t\n\t\t\ttds[cit->second] += cit->first;\n\n\t\t\tif (1\/tds[cit->second] > weight)\n\t\t\t{\n\t\t\t\tweight = 1\/tds[cit->second];\n\t\t\t\ttype = cit->second;\n\n\t\t\t}\n\t\t\t\n\t\t}\n\n\n\t\tsample[i].classnumber = type;\n\t\tcout<<\"Result Class = \"< &sample,const std::vector &dataset,int k){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\tif(k<0){\n\t\tCV_Error(CV_StsBadArg,\"[pixkit::classification::KNN] k should >= 1.\");\n\t}\n\n\tvector > DM;\n DistanceMatrix(DM, dataset, sample);\n\tTradition_KNN_Process(sample, dataset, DM, k);\n\n\treturn\ttrue;\n}\n\nbool pixkit::classification::FKNN(std::vector &sample,const std::vector &dataset,int k){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\tif(k<0){\n\t\tCV_Error(CV_StsBadArg,\"[pixkit::classification::KNN] k should >= 1.\");\n\t}\n\n\tvector > DM;\n\tDistanceMatrix(DM, dataset, sample);\n\tFKNN_Process(sample, dataset, DM, k);\n\n\treturn\ttrue;\n}\n\nbool pixkit::classification::FRNN(std::vector &sample,const std::vector &dataset){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\n\tvector > DM,Bw;\n\tDistanceMatrix(DM, dataset, sample);\n\tBandwidthMatrix(Bw, dataset, sample);\n\tFRNN_Process(sample, dataset, DM,Bw);\n\n\treturn\ttrue;\n}那個沒是我自己的東西~#include \"..\/include\/pixkit-ml.hpp\"\n\nusing namespace std;\n\ndouble Euclidean_Distance(const vector& v1, const vector& v2){\n\tassert(v1.size() == v2.size());\n\tdouble ret = 0.0;\n\tfor (vector::size_type i = 0; i != v1.size(); ++i){\n\t\tret += (v1[i] - v2[i]) * (v1[i] - v2[i]);\n\t}\n\treturn sqrt(ret);\n}\nvoid DistanceMatrix(std::vector >& dm, const std::vector &dataset,const std::vector &sample){\n\tfor ( vector::size_type i = 0; i != sample.size(); ++i){\n\t\tvector DM_data;\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j){\n\t\t\tDM_data.push_back(Euclidean_Distance(sample[i].features, dataset[j].features));\n\t\t}\n\t\tdm.push_back(DM_data);\n\t}\n}\nvector kappa_Matrix(const vector& v1, const vector& v2, vector& kappa)\n{\t\n\tassert(v1.size() == v2.size()); \n\n\tfor (vector::size_type i = 0; i != v1.size(); ++i)\n\t{\n\t\tkappa[i] +=sqrt((v1[i] - v2[i]) * (v1[i] - v2[i])) ;\n\t}\n\n\treturn (kappa);\n\n}\n\nvoid BandwidthMatrix(vector >& Bw, const vector& sample, const vector& dataset)\n{\n\n\tfor (vector::size_type i = 0; i !=sample.size(); ++i)\n\t{\n\t\tvector kappa_data,kappa(sample[i].features.size());\n\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j)\n\t\t{\n\n\n\t\t\tkappa_data=kappa_Matrix(sample[i].features, dataset[j].features,kappa);\n\n\t\t}\n\n\t\tBw.push_back(kappa_data);\n\n\t}\n\n\n}\n\nvoid Tradition_KNN_Process(vector& sample, const vector& dataset, const vector >& dm, unsigned int k){\n\tfor (vector::size_type i = 0; i != sample.size(); ++i){\n\t\tmultimap dts;\n\t\tfor (vector::size_type j = 0; j != dm[i].size(); ++j){\n\t\t\tif (dts.size() < k){\n\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber)); \n\t\t\t}else{\n\t\t\t\tmultimap::iterator it = dts.end();\n\t\t\t\t--it;\n\t\t\t\tif (dm[i][j] < (it->first)){\n\t\t\t\t\tdts.erase(it);\n\t\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmap tds;\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit){\n\t\t\t++tds[cit->second];\n\t\t\tif (tds[cit->second] > weight){\n\t\t\t\tweight = tds[cit->second];\n\t\t\t\ttype = cit->second;\n\t\t\t}\n\t\t}\n\t\tfor (map::const_iterator cit = tds.begin(); cit != tds.end(); ++cit){\n\t\t\tcout<first <<\"=\"<second<<'\\n'<& sample, const vector& dataset, const vector >& dm, unsigned int k)\n{\n\tfor (vector::size_type i = 0; i != sample.size(); ++i)\n\t{\n\t\tmultimap dts;\n\t\tfor (vector::size_type j = 0; j != dm[i].size(); ++j)\n\t\t{\n\t\t\tif (dts.size() < k ) \n\t\t\t{\n\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber)); \n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmultimap::iterator it = dts.end();\n\t\t\t\t--it;\n\t\t\t\tif (dm[i][j] < (it->first))\n\t\t\t\t{\n\t\t\t\t\tdts.erase(it);\n\t\t\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmap tds,fin;\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\t\tdouble now_weight = 0.0;\n\t\tdouble total_weight= 0.0;\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t{\n\n\t\t\tif (cit->first==0)\n\t\t\t{\n\t\t\t\ttds[cit->second] += 1.0 \/ (cit->first+1);\n\t\t\t\ttotal_weight=total_weight+(1.0 \/ (cit->first+1));\n\n\t\t\t}else{\n\n\t\t\t\ttds[cit->second] += 1.0 \/ cit->first;\n\t\t\t\ttotal_weight=total_weight+(1.0 \/ (cit->first));\n\t\t\t}\n\n\n\n\n\t\t}\n\n\t\tfor (map::const_iterator cit = tds.begin(); cit != tds.end(); ++cit)\n\t\t{\n\n\t\t\tnow_weight=(cit->second\/total_weight);\n\n\t\t\tif (now_weight > weight)\n\t\t\t{\n\t\t\t\tweight = now_weight;\n\t\t\t\ttype = cit->first;\n\n\t\t\t}\n\n\t\t}\n\n\t\tsample[i].classnumber = type;\n\t\tcout<<\"Result Class = \"<& sample, const vector& dataset, const vector >& dm,const vector >& Bw)\n{\n\tfor (vector::size_type i = 0; i != sample.size(); ++i)\n\t{\n\t\tmultimap dts,dist,dist1;\n\t\tmap tds,fin,merbership,countnmber;\n\t\t\n\n\t\tfor (vector::size_type k = 0; k != dm[i].size(); ++k)\n\t\t{\n\t\t\tdist.insert(make_pair(dm[i][k], dataset[k].classnumber));\n\n\t\t}\n\n\n\t\n\t\tfor (vector::size_type j = 0; j != dataset.size(); ++j)\n\t\t{\n\t\t\tdouble d=0.0;\n\t\t\tfor (vector::size_type x = 0; x != Bw[i].size(); ++x)\n\t\t\t{\n\t\t\t\tif (Bw[i][x]==0)\n\t\t\t\t{\n\t\t\t\t\td+=(dataset.size()\/(2))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\t\n\t\t\t\t\td+=(dataset.size()\/(2*Bw[i][x]))*(sample[i].features[x]-dataset[j].features[x])*(sample[i].features[x]-dataset[j].features[x]);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tdts.insert(make_pair(dm[i][j], dataset[j].classnumber));\n\t\t\td=d+(1\/dataset.size())*exp(-d);\n\n\t\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t\t{\n\n\t\t\t\tif (cit->first==0)\n\t\t\t\t{\n\t\t\t\t\ttds[cit->second] += 1.0 \/ (cit->first+1);\n\n\t\t\t\t}else{\n\n\t\t\t\t\ttds[cit->second] += 1.0 \/ cit->first;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tstring type = \"\";\n\t\tdouble weight = 0.0;\n\n\t\tfor (multimap::const_iterator cit = dts.begin(); cit != dts.end(); ++cit)\n\t\t{\n\n\t\t\t\n\t\t\ttds[cit->second] += cit->first;\n\n\t\t\tif (1\/tds[cit->second] > weight)\n\t\t\t{\n\t\t\t\tweight = 1\/tds[cit->second];\n\t\t\t\ttype = cit->second;\n\n\t\t\t}\n\t\t\t\n\t\t}\n\n\n\t\tsample[i].classnumber = type;\n\t\tcout<<\"Result Class = \"< &sample,const std::vector &dataset,int k){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\tif(k<0){\n\t\tCV_Error(CV_StsBadArg,\"[pixkit::classification::KNN] k should >= 1.\");\n\t}\n\n\tvector > DM;\n DistanceMatrix(DM, dataset, sample);\n\tTradition_KNN_Process(sample, dataset, DM, k);\n\n\treturn\ttrue;\n}\n\nbool pixkit::classification::FKNN(std::vector &sample,const std::vector &dataset,int k){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\tif(k<0){\n\t\tCV_Error(CV_StsBadArg,\"[pixkit::classification::KNN] k should >= 1.\");\n\t}\n\n\tvector > DM;\n\tDistanceMatrix(DM, dataset, sample);\n\tFKNN_Process(sample, dataset, DM, k);\n\n\treturn\ttrue;\n}\n\nbool pixkit::classification::FRNN(std::vector &sample,const std::vector &dataset){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\n\tvector > DM,Bw;\n\tDistanceMatrix(DM, dataset, sample);\n\tBandwidthMatrix(Bw, dataset, sample);\n\tFRNN_Process(sample, dataset, DM,Bw);\n\n\treturn\ttrue;\n}<|endoftext|>"} {"text":"\/*\nThe MIT License (MIT)\n\nCopyright (c) 2015 Nrupatunga\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#pragma comment(lib, \"opencv_core300d.lib\") \/\/ core functionalities\n#pragma comment(lib, \"opencv_highgui300d.lib\") \/\/GUI\n#pragma comment(lib, \"opencv_imgcodecs300d.lib\")\n#pragma comment(lib, \"opencv_imgproc300d.lib\") \/\/ Histograms, Edge detection\n#pragma comment(lib, \"opencv_video300d.lib\")\n#pragma comment(lib, \"opencv_videoio300d.lib\")\n\nusing namespace cv;\nusing namespace std;\n\n#define PI (3.1412)\n\n\/* \n * === FUNCTION ======================================================================\n * Name: main\n * Description: \n * =====================================================================================\n *\/\n\nint main ( int argc, char *argv[] )\n{\n\t Mat sMatInput = imread(\"..\\\\flower.jpg\", IMREAD_GRAYSCALE);\n\t Mat sMatOutput;\n\n\t String strWinIn = \"Input\";\n\t String strWinOut = \"Output\";\n\n\t CannyED(sMatInput, sMatOutput, 10, 40);\n\t namedWindow(strWinIn, WINDOW_NORMAL);\n\t namedWindow(strWinOut, WINDOW_NORMAL);\n\t imshow(strWinIn, sMatInput);\n\t imshow(strWinOut, sMatOutput);\n\t waitKey(0);\n\treturn EXIT_SUCCESS;\n\n} \/* ---------- end of function main ---------- *\/\n\nremoving unused code from main.cpp\/*\nThe MIT License (MIT)\n\nCopyright (c) 2015 Nrupatunga\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n\n#pragma comment(lib, \"opencv_core300d.lib\") \/\/ core functionalities\n#pragma comment(lib, \"opencv_highgui300d.lib\") \/\/GUI\n#pragma comment(lib, \"opencv_imgcodecs300d.lib\")\n#pragma comment(lib, \"opencv_imgproc300d.lib\") \/\/ Histograms, Edge detection\n\nusing namespace cv;\nusing namespace std;\n\n#define PI (3.1412)\n\n\/* \n* === FUNCTION ======================================================================\n* Name: main\n* Description: \n* =====================================================================================\n*\/\n\nint main ( int argc, char *argv[] )\n{\n\tMat sMatInput = imread(\"..\\\\flower.jpg\", IMREAD_GRAYSCALE);\n\tMat sMatOutput;\n\n\tString strWinIn = \"Input\";\n\tString strWinOut = \"Output\";\n\n\tCannyED(sMatInput, sMatOutput, 10, 40);\n\tnamedWindow(strWinIn, WINDOW_NORMAL);\n\tnamedWindow(strWinOut, WINDOW_NORMAL);\n\timshow(strWinIn, sMatInput);\n\timshow(strWinOut, sMatOutput);\n\n\timwrite(\"Input.jpg\", sMatInput);\n\timwrite(\"OutputEdge.jpg\", sMatOutput);\n\twaitKey(0);\n\treturn EXIT_SUCCESS;\n\n} \/* ---------- end of function main ---------- *\/\n\n<|endoftext|>"} {"text":"\n#include \"cmdline\/cmdline.h\"\n#include \"mhap\/overlap.h\"\n#include \"mhap\/parser.h\"\n#include \"ra\/include\/ra\/ra.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ trimming params\nint READ_LEN_THRESHOLD = 100000;\nuint32_t MAX_READS_IN_TIP = 2;\nuint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5;\n\n\/\/ BFS params in bubble popping\nsize_t MAX_NODES = 2000;\nint MAX_DISTANCE = MAX_NODES * 10000;\ndouble MAX_DIFFERENCE = 0.25;\n\n\/\/ contig extraction params\nsize_t MAX_BRANCHES = 18;\nsize_t MAX_START_NODES = 100;\ndouble LENGTH_THRESHOLD = 0.2;\ndouble QUALITY_THRESHOLD = 0.2;\n\n\/\/ filter reads param\nsize_t READS_MIN_LEN = 3000;\n\nusing std::cerr;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::fstream;\nusing std::max;\nusing std::string;\nusing std::vector;\n\n\/\/ map reads so we can access reads with mapped[read_id]\nvoid map_reads(vector* mapped, vector& reads) {\n\n int max_id = -1;\n for (auto r: reads) {\n max_id = max(max_id, r->getId());\n }\n\n mapped->resize(max_id + 1, nullptr);\n for (auto r: reads) {\n (*mapped)[r->getId()] = r;\n }\n}\n\nstring output_dir_name() {\n time_t rawtime;\n struct tm* timeinfo;\n char buffer[80];\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n\n strftime(buffer, 80, \"layout_%Y%m%d_%H%M%S\", timeinfo);\n return string(buffer);\n}\n\nvoid must_mkdir(const string& path) {\n if (mkdir(path.c_str(), 0755) == -1) {\n fprintf(stderr, \"Can't create directory %s\\n\", path.c_str());\n exit(1);\n }\n}\n\nvoid print_contigs_info(const vector& contigs, const vector& reads) {\n\n for (uint32_t i = 0; i < contigs.size(); ++i) {\n const auto& contig = contigs[i];\n const auto& parts = contig->getParts();\n const auto& last_part = contig->getParts().back();\n\n fprintf(stdout, \"contig %u; length: ≈%lu, reads: %lu\\n\",\n i, last_part.offset + reads[last_part.src]->getLength(), parts.size()\n );\n for (const auto& p: parts) {\n fprintf(stdout, \"%d \", p.src);\n }\n fprintf(stdout, \"\\n\");\n }\n}\n\nint main(int argc, char **argv) {\n\n cmdline::parser args;\n\n \/\/ input params\n args.add(\"reads\", 'r', \"reads file\", true);\n args.add(\"reads_format\", 's', \"reads format; supported: fasta, fastq, afg\", false, \"fasta\");\n args.add(\"reads_id_offset\", 'a', \"reads id offset (first read id)\", false, 0);\n args.add(\"overlaps\", 'x', \"overlaps file\", true);\n args.add(\"overlaps_format\", 'f', \"overlaps file format; supported: afg, mhap\", false, \"afg\");\n\n args.add(\"verbose\", 'v', \"verbose output\", false);\n\n \/\/ bubble popping params\n args.add(\"bp_max_nodes\", 'm', \"max nodes in bubble branch\", false, 750);\n args.add(\"bp_max_diff\", 'n', \"max difference between bubble branches\", false, 0.25);\n\n args.parse_check(argc, argv);\n\n const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);\n const string reads_filename = args.get(\"reads\");\n const string reads_format = args.get(\"reads_format\");\n const string overlaps_filename = args.get(\"overlaps\");\n const string overlaps_format = args.get(\"overlaps_format\");\n const bool verbose_output = args.get(\"verbose\");\n const int reads_id_offset = args.get(\"reads_id_offset\");\n const string output_dir = output_dir_name();\n\n MAX_NODES = args.get(\"bp_max_nodes\");\n MAX_DISTANCE = MAX_NODES * 10000;\n MAX_DIFFERENCE = args.get(\"bp_max_diff\");\n\n vector overlaps, filtered;\n vector reads;\n vector reads_mapped;\n\n must_mkdir(output_dir);\n std::cerr << \"Output dir: \" << output_dir << std::endl;\n\n if (reads_format == \"fasta\") {\n readFastaReads(reads, reads_filename.c_str());\n } else if (reads_format == \"fastq\") {\n readFastqReads(reads, reads_filename.c_str());\n } else if (reads_format == \"afg\") {\n readAfgReads(reads, reads_filename.c_str());\n } else {\n assert(false);\n }\n\n \/\/ map reads so we have reads_mapped[read_id] -> read\n map_reads(&reads_mapped, reads);\n\n std::cerr << \"Read \" << reads.size() << \" reads\" << std::endl;\n\n if (overlaps_format == \"afg\") {\n readAfgOverlaps(overlaps, overlaps_filename.c_str());\n } else if (overlaps_format == \"mhap\") {\n fstream overlaps_file(overlaps_filename);\n MHAP::read_overlaps(overlaps_file, &overlaps);\n overlaps_file.close();\n } else {\n assert(false);\n }\n\n \/\/ fix overlap read ids\n for (auto o: overlaps) {\n o->setA(o->getA() - reads_id_offset);\n o->setB(o->getB() - reads_id_offset);\n }\n\n for (auto o: overlaps) {\n const auto a = o->getA();\n const auto b = o->getB();\n if (reads_mapped[a] == nullptr) {\n cerr << \"Read \" << a << \" not found\" << endl;\n exit(1);\n }\n if (reads_mapped[b] == nullptr) {\n cerr << \"Read \" << b << \" not found\" << endl;\n exit(1);\n }\n\n o->setReadA(reads_mapped[a]);\n o->setReadB(reads_mapped[b]);\n }\n\n cerr << overlaps.size() << \" overlaps read\" << endl;\n\n int skipped = 0;\n for (uint32_t i = 0; i < overlaps.size(); ++i) {\n const auto o = overlaps[i];\n\n if (o->getReadA()->getLength() < READS_MIN_LEN || o->getReadB()->getLength() < READS_MIN_LEN) {\n skipped++;\n continue;\n }\n\n overlaps[i - skipped] = overlaps[i];\n }\n overlaps.resize(overlaps.size() - skipped);\n\n vector nocontainments;\n filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);\n\n if (verbose_output) {\n writeOverlaps(nocontainments, (output_dir + \"\/nocont.afg\").c_str());\n }\n\n vector notransitives;\n filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);\n\n if (verbose_output) {\n writeOverlaps(notransitives, (output_dir + \"\/nocont.notran.afg\").c_str());\n }\n\n createReverseComplements(reads, thread_num);\n\n StringGraph* graph = new StringGraph(reads, notransitives);\n graph->simplify();\n\n if (verbose_output) {\n vector simplified_overlaps;\n graph->extractOverlaps(simplified_overlaps);\n writeOverlaps(simplified_overlaps, (output_dir + \"\/simplified.afg\").c_str());\n }\n\n std::vector components;\n graph->extractComponents(components);\n\n std::vector contigs;\n\n auto contigs_fast = fopen((output_dir + \"\/contigs_fast.fasta\").c_str(), \"w\");\n int idx = 0;\n for (const auto& component : components) {\n string seq;\n component->extractSequence(seq);\n fprintf(contigs_fast, \">seq%d\\n\", idx);\n fprintf(contigs_fast, \"%s\\n\", seq.c_str());\n idx++;\n\n ContigExtractor* extractor = new ContigExtractor(component);\n const auto& contig = extractor->extractContig();\n\n if (contig == nullptr) {\n continue;\n }\n\n contigs.emplace_back(contig);\n }\n fclose(contigs_fast);\n\n std::cerr << \"number of contigs \" << contigs.size() << std::endl;\n print_contigs_info(contigs, reads_mapped);\n\n writeAfgContigs(contigs, (output_dir + \"\/contigs.afg\").c_str());\n\n for (auto r: reads) delete r;\n for (auto o: overlaps) delete o;\n for (auto c: components) delete c;\n for (auto c: contigs) delete c;\n\n delete graph;\n\n return 0;\n}\nadd writing settings file to output directory (resolves #12)\n#include \"cmdline\/cmdline.h\"\n#include \"mhap\/overlap.h\"\n#include \"mhap\/parser.h\"\n#include \"ra\/include\/ra\/ra.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::fstream;\nusing std::max;\nusing std::string;\nusing std::vector;\n\n\/\/ trimming params\nint READ_LEN_THRESHOLD = 100000;\nuint32_t MAX_READS_IN_TIP = 2;\nuint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5;\n\n\/\/ BFS params in bubble popping\nsize_t MAX_NODES = 2000;\nint MAX_DISTANCE = MAX_NODES * 10000;\ndouble MAX_DIFFERENCE = 0.25;\n\n\/\/ contig extraction params\nsize_t MAX_BRANCHES = 18;\nsize_t MAX_START_NODES = 100;\ndouble LENGTH_THRESHOLD = 0.2;\ndouble QUALITY_THRESHOLD = 0.2;\n\n\/\/ filter reads param\nsize_t READS_MIN_LEN = 3000;\n\n\/\/ global vars\ncmdline::parser args;\nint thread_num;\nstring reads_filename;\nstring reads_format;\nstring overlaps_filename;\nstring overlaps_format;\nbool verbose_output;\nint reads_id_offset;\n\n\/\/ map reads so we can access reads with mapped[read_id]\nvoid map_reads(vector* mapped, vector& reads) {\n\n int max_id = -1;\n for (auto r: reads) {\n max_id = max(max_id, r->getId());\n }\n\n mapped->resize(max_id + 1, nullptr);\n for (auto r: reads) {\n (*mapped)[r->getId()] = r;\n }\n}\n\nstring output_dir_name() {\n time_t rawtime;\n struct tm* timeinfo;\n char buffer[80];\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n\n strftime(buffer, 80, \"layout_%Y%m%d_%H%M%S\", timeinfo);\n return string(buffer);\n}\n\nvoid must_mkdir(const string& path) {\n if (mkdir(path.c_str(), 0755) == -1) {\n fprintf(stderr, \"Can't create directory %s\\n\", path.c_str());\n exit(1);\n }\n}\n\nvoid print_contigs_info(const vector& contigs, const vector& reads) {\n\n for (uint32_t i = 0; i < contigs.size(); ++i) {\n const auto& contig = contigs[i];\n const auto& parts = contig->getParts();\n const auto& last_part = contig->getParts().back();\n\n fprintf(stdout, \"contig %u; length: ≈%lu, reads: %lu\\n\",\n i, last_part.offset + reads[last_part.src]->getLength(), parts.size()\n );\n for (const auto& p: parts) {\n fprintf(stdout, \"%d \", p.src);\n }\n fprintf(stdout, \"\\n\");\n }\n}\n\nvoid init_args(int argc, char** argv) {\n \/\/ input params\n args.add(\"reads\", 'r', \"reads file\", true);\n args.add(\"reads_format\", 's', \"reads format; supported: fasta, fastq, afg\", false, \"fasta\");\n args.add(\"reads_id_offset\", 'a', \"reads id offset (first read id)\", false, 0);\n args.add(\"overlaps\", 'x', \"overlaps file\", true);\n args.add(\"overlaps_format\", 'f', \"overlaps file format; supported: afg, mhap\", false, \"afg\");\n\n args.add(\"verbose\", 'v', \"verbose output\", false);\n\n \/\/ bubble popping params\n args.add(\"bp_max_nodes\", 'm', \"max nodes in bubble branch\", false, 750);\n args.add(\"bp_max_diff\", 'n', \"max difference between bubble branches\", false, 0.25);\n\n args.parse_check(argc, argv);\n}\n\nvoid read_args() {\n thread_num = std::max(std::thread::hardware_concurrency(), 1U);\n reads_filename = args.get(\"reads\");\n reads_format = args.get(\"reads_format\");\n overlaps_filename = args.get(\"overlaps\");\n overlaps_format = args.get(\"overlaps_format\");\n verbose_output = args.get(\"verbose\");\n reads_id_offset = args.get(\"reads_id_offset\");\n\n MAX_NODES = args.get(\"bp_max_nodes\");\n MAX_DISTANCE = MAX_NODES * 10000;\n MAX_DIFFERENCE = args.get(\"bp_max_diff\");\n}\n\nFILE* must_fopen(const char* path, const char* mode) {\n FILE* res = fopen(path, mode);\n if (res == nullptr) {\n fprintf(stderr, \"Cannot open %s with mode %s\\n\", path, mode);\n exit(1);\n }\n\n return res;\n}\n\nvoid write_settings(FILE *fd) {\n fprintf(fd, \"# filter reads parameters\\n\");\n fprintf(fd, \"READS_MIN_LEN: %lu\\n\", READS_MIN_LEN);\n fprintf(fd, \"\\n\");\n\n fprintf(fd, \"# trimming parameters\\n\");\n fprintf(fd, \"READ_LEN_THRESHOLD: %d\\n\", READ_LEN_THRESHOLD);\n fprintf(fd, \"MAX_READS_IN_TIP: %d\\n\", MAX_READS_IN_TIP);\n fprintf(fd, \"MAX_DEPTH_WITHOUT_EXTRA_FORK: %d\\n\", MAX_DEPTH_WITHOUT_EXTRA_FORK);\n fprintf(fd, \"\\n\");\n\n fprintf(fd, \"# bubble popping parameters\\n\");\n fprintf(fd, \"MAX_NODES: %lu\\n\", MAX_NODES);\n fprintf(fd, \"MAX_DISTANCE: %d\\n\", MAX_DISTANCE);\n fprintf(fd, \"MAX_DIFFERENCE: %f\\n\", MAX_DIFFERENCE);\n fprintf(fd, \"\\n\");\n\n fprintf(fd, \"# contig extraction parameters\\n\");\n fprintf(fd, \"MAX_BRANCHES: %lu\\n\", MAX_BRANCHES);\n fprintf(fd, \"MAX_START_NODES: %lu\\n\", MAX_START_NODES);\n fprintf(fd, \"LENGTH_THRESHOLD: %f\\n\", LENGTH_THRESHOLD);\n fprintf(fd, \"QUALITY_THRESHOLD: %f\\n\", QUALITY_THRESHOLD);\n fprintf(fd, \"\\n\");\n}\n\nint main(int argc, char **argv) {\n\n init_args(argc, argv);\n read_args();\n\n string output_dir = output_dir_name();\n\n must_mkdir(output_dir);\n std::cerr << \"Output dir: \" << output_dir << std::endl;\n\n auto settings_file = must_fopen((output_dir + \"\/run_args.txt\").c_str(), \"w\");\n write_settings(settings_file);\n fclose(settings_file);\n\n vector overlaps, filtered;\n vector reads;\n vector reads_mapped;\n\n if (reads_format == \"fasta\") {\n readFastaReads(reads, reads_filename.c_str());\n } else if (reads_format == \"fastq\") {\n readFastqReads(reads, reads_filename.c_str());\n } else if (reads_format == \"afg\") {\n readAfgReads(reads, reads_filename.c_str());\n } else {\n assert(false);\n }\n\n \/\/ map reads so we have reads_mapped[read_id] -> read\n map_reads(&reads_mapped, reads);\n\n std::cerr << \"Read \" << reads.size() << \" reads\" << std::endl;\n\n if (overlaps_format == \"afg\") {\n readAfgOverlaps(overlaps, overlaps_filename.c_str());\n } else if (overlaps_format == \"mhap\") {\n fstream overlaps_file(overlaps_filename);\n MHAP::read_overlaps(overlaps_file, &overlaps);\n overlaps_file.close();\n } else {\n assert(false);\n }\n\n \/\/ fix overlap read ids\n for (auto o: overlaps) {\n o->setA(o->getA() - reads_id_offset);\n o->setB(o->getB() - reads_id_offset);\n }\n\n for (auto o: overlaps) {\n const auto a = o->getA();\n const auto b = o->getB();\n if (reads_mapped[a] == nullptr) {\n cerr << \"Read \" << a << \" not found\" << endl;\n exit(1);\n }\n if (reads_mapped[b] == nullptr) {\n cerr << \"Read \" << b << \" not found\" << endl;\n exit(1);\n }\n\n o->setReadA(reads_mapped[a]);\n o->setReadB(reads_mapped[b]);\n }\n\n cerr << overlaps.size() << \" overlaps read\" << endl;\n\n int skipped = 0;\n for (uint32_t i = 0; i < overlaps.size(); ++i) {\n const auto o = overlaps[i];\n\n if (o->getReadA()->getLength() < READS_MIN_LEN || o->getReadB()->getLength() < READS_MIN_LEN) {\n skipped++;\n continue;\n }\n\n overlaps[i - skipped] = overlaps[i];\n }\n overlaps.resize(overlaps.size() - skipped);\n\n vector nocontainments;\n filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);\n\n if (verbose_output) {\n writeOverlaps(nocontainments, (output_dir + \"\/nocont.afg\").c_str());\n }\n\n vector notransitives;\n filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);\n\n if (verbose_output) {\n writeOverlaps(notransitives, (output_dir + \"\/nocont.notran.afg\").c_str());\n }\n\n createReverseComplements(reads, thread_num);\n\n StringGraph* graph = new StringGraph(reads, notransitives);\n graph->simplify();\n\n if (verbose_output) {\n vector simplified_overlaps;\n graph->extractOverlaps(simplified_overlaps);\n writeOverlaps(simplified_overlaps, (output_dir + \"\/simplified.afg\").c_str());\n }\n\n std::vector components;\n graph->extractComponents(components);\n\n std::vector contigs;\n\n auto contigs_fast = must_fopen((output_dir + \"\/contigs_fast.fasta\").c_str(), \"w\");\n int idx = 0;\n for (const auto& component : components) {\n string seq;\n component->extractSequence(seq);\n fprintf(contigs_fast, \">seq%d\\n\", idx);\n fprintf(contigs_fast, \"%s\\n\", seq.c_str());\n idx++;\n\n ContigExtractor* extractor = new ContigExtractor(component);\n const auto& contig = extractor->extractContig();\n\n if (contig == nullptr) {\n continue;\n }\n\n contigs.emplace_back(contig);\n }\n fclose(contigs_fast);\n\n std::cerr << \"number of contigs \" << contigs.size() << std::endl;\n print_contigs_info(contigs, reads_mapped);\n\n writeAfgContigs(contigs, (output_dir + \"\/contigs.afg\").c_str());\n\n for (auto r: reads) delete r;\n for (auto o: overlaps) delete o;\n for (auto c: components) delete c;\n for (auto c: contigs) delete c;\n\n delete graph;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"network.h\"\n#include \"string.h\"\n#include \"mutex.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Platforms supporting Socket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(__WIN32__)\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n\/\/#include \n\/\/#include \ntypedef int socklen_t;\n#define SHUT_RDWR 0x2\n#else \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define SOCKET int\n#define closesocket close\n#endif\n\n\/*! ignore if not supported *\/\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0 \n#endif\n\n#define BUFFERING 1\n\nnamespace embree\n{\n namespace network \n {\n __forceinline void initialize() {\n#ifdef __WIN32__\n static bool initialized = false;\n static MutexSys initMutex;\n Lock lock(initMutex);\n WSADATA wsaData;\n short version = MAKEWORD(1,1);\n if (WSAStartup(version,&wsaData) != 0)\n THROW_RUNTIME_ERROR(\"Winsock initialization failed\");\n initialized = true;\n#endif\n }\n\n struct buffered_socket_t \n {\n buffered_socket_t (SOCKET fd, size_t isize = 64*1024, size_t osize = 64*1024)\n : fd(fd), \n ibuf(new char[isize]), isize(isize), istart(0), iend(0),\n obuf(new char[osize]), osize(osize), oend(0) {\n }\n\n ~buffered_socket_t () {\n delete[] ibuf; ibuf = nullptr;\n delete[] obuf; obuf = nullptr;\n }\n \n SOCKET fd; \/\/!< file descriptor of the socket\n char* ibuf;\n size_t isize;\n size_t istart,iend;\n char* obuf;\n size_t osize;\n size_t oend;\n };\n\n socket_t connect(const char* host, unsigned short port) \n {\n initialize();\n\n \/*! create a new socket *\/\n SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot create socket\");\n \n \/*! perform DNS lookup *\/\n struct hostent* server = ::gethostbyname(host);\n if (server == nullptr) THROW_RUNTIME_ERROR(\"server \"+std::string(host)+\" not found\");\n \n \/*! perform connection *\/\n struct sockaddr_in serv_addr;\n memset((char*)&serv_addr, 0, sizeof(serv_addr));\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = (unsigned short) htons(port);\n memcpy((char*)&serv_addr.sin_addr.s_addr, (char*)server->h_addr, server->h_length);\n \n if (::connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)\n THROW_RUNTIME_ERROR(\"connection to \"+std::string(host)+\":\"+std::to_string((long long)port)+\" failed\");\n\n \/*! enable TCP_NODELAY *\/\n#ifdef TCP_NODELAY\n { int flag = 1; ::setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(int)); }\n#endif\n\n \/*! we do not want SIGPIPE to be thrown *\/\n#ifdef SO_NOSIGPIPE\n { int flag = 1; setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (const char*) &flag, sizeof(int)); }\n#endif\n \n return (socket_t) new buffered_socket_t(sockfd);\n }\n \n socket_t bind(unsigned short port)\n {\n initialize();\n\n \/*! create a new socket *\/\n SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot create socket\");\n\n \/* When the server completes, the server socket enters a time-wait state during which the local\n address and port used by the socket are believed to be in use by the OS. The wait state may\n last several minutes. This socket option allows bind() to reuse the port immediately. *\/\n#ifdef SO_REUSEADDR\n { int flag = true; ::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(int)); }\n#endif\n \n \/*! bind socket to port *\/\n struct sockaddr_in serv_addr;\n memset((char *) &serv_addr, 0, sizeof(serv_addr));\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = (unsigned short) htons(port);\n serv_addr.sin_addr.s_addr = INADDR_ANY;\n\n if (::bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)\n THROW_RUNTIME_ERROR(\"binding to port \"+std::to_string((long long)port)+\" failed\");\n \n \/*! listen to port, up to 5 pending connections *\/\n if (::listen(sockfd,5) < 0)\n THROW_RUNTIME_ERROR(\"listening on socket failed\");\n\n return (socket_t) new buffered_socket_t(sockfd);\n }\n \n socket_t listen(socket_t hsock)\n {\n SOCKET sockfd = ((buffered_socket_t*) hsock)->fd;\n \n \/*! accept incoming connection *\/\n struct sockaddr_in addr;\n socklen_t len = sizeof(addr);\n SOCKET fd = ::accept(sockfd, (struct sockaddr *) &addr, &len);\n if (fd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot accept connection\");\n\n \/*! enable TCP_NODELAY *\/\n#ifdef TCP_NODELAY\n { int flag = 1; ::setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char*)&flag,sizeof(int)); }\n#endif\n\n \/*! we do not want SIGPIPE to be thrown *\/\n#ifdef SO_NOSIGPIPE\n { int flag = 1; setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&flag, sizeof(int)); }\n#endif\n\n return (socket_t) new buffered_socket_t(fd); \n }\n \n void read(socket_t hsock_i, void* data_i, size_t bytes)\n {\n#if BUFFERING\n char* data = (char*)data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n if (hsock->istart == hsock->iend) {\n ssize_t n = ::recv(hsock->fd,hsock->ibuf,hsock->isize,MSG_NOSIGNAL);\n if (n == 0) throw Disconnect();\n else if (n < 0) THROW_RUNTIME_ERROR(\"error reading from socket\");\n hsock->istart = 0;\n hsock->iend = n;\n }\n size_t bsize = hsock->iend-hsock->istart;\n if (bytes < bsize) bsize = bytes;\n memcpy(data,hsock->ibuf+hsock->istart,bsize);\n data += bsize;\n hsock->istart += bsize;\n bytes -= bsize;\n }\n#else\n char* data = (char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n ssize_t n = ::read(hsock->fd,data,bytes);\n if (n == 0) throw Disconnect();\n else if (n < 0) THROW_RUNTIME_ERROR(\"error reading from socket\");\n data+=n;\n bytes-=n;\n }\n#endif\n }\n\n void write(socket_t hsock_i, const void* data_i, size_t bytes)\n {\n#if BUFFERING\n const char* data = (const char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n if (hsock->oend == hsock->osize) flush(hsock_i);\n size_t bsize = hsock->osize-hsock->oend;\n if (bytes < bsize) bsize = bytes;\n memcpy(hsock->obuf+hsock->oend,data,bsize);\n data += bsize;\n hsock->oend += bsize;\n bytes -= bsize;\n }\n#else\n const char* data = (const char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n ssize_t n = ::write(hsock->fd,data,bytes);\n if (n < 0) THROW_RUNTIME_ERROR(\"error writing to socket\");\n data+=n;\n bytes-=n;\n }\n#endif\n }\n\n void flush(socket_t hsock_i)\n {\n#if BUFFERING\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n char* data = hsock->obuf;\n size_t bytes = hsock->oend;\n while (bytes > 0) {\n ssize_t n = ::send(hsock->fd,data,(int)bytes,MSG_NOSIGNAL);\n if (n < 0) THROW_RUNTIME_ERROR(\"error writing to socket\");\n bytes -= n;\n data += n;\n } \n hsock->oend = 0;\n#endif\n }\n \n void close(socket_t hsock_i) {\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n ::shutdown(hsock->fd,SHUT_RDWR);\n delete hsock;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ All Platforms\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace embree\n{\n namespace network \n {\n bool read_bool(socket_t socket) \n {\n bool value = 0;\n read(socket,&value,sizeof(bool));\n return value;\n }\n\n char read_char(socket_t socket) \n {\n char value = 0;\n read(socket,&value,sizeof(char));\n return value;\n }\n \n int read_int(socket_t socket) \n {\n int value = 0;\n read(socket,&value,sizeof(int));\n return value;\n }\n \n float read_float(socket_t socket) \n {\n float value = 0.0f;\n read(socket,&value,sizeof(float));\n return value;\n }\n \n std::string read_string(socket_t socket) \n {\n int bytes = read_int(socket);\n char* str = new char[bytes+1];\n read(socket,str,bytes);\n str[bytes] = 0x00;\n std::string s(str);\n delete[] str;\n return s;\n }\n\n void write(socket_t socket, bool value) {\n write(socket,&value,sizeof(bool));\n }\n\n void write(socket_t socket, char value) {\n write(socket,&value,sizeof(char));\n }\n \n void write(socket_t socket, int value) {\n write(socket,&value,sizeof(int));\n }\n \n void write(socket_t socket, float value) {\n write(socket,&value,sizeof(float));\n }\n \n void write(socket_t socket, const std::string& str) {\n write(socket,(int)str.size());\n write(socket,str.c_str(),str.size());\n }\n }\n}\ncompile fixed for linux\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"network.h\"\n#include \"string.h\"\n#include \"mutex.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Platforms supporting Socket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(__WIN32__)\n#define _WINSOCK_DEPRECATED_NO_WARNINGS\n\/\/#include \n\/\/#include \ntypedef int socklen_t;\n#define SHUT_RDWR 0x2\n#else \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define SOCKET int\n#define INVALID_SOCKET -1\n#define closesocket close\n#endif\n\n\/*! ignore if not supported *\/\n#ifndef MSG_NOSIGNAL\n#define MSG_NOSIGNAL 0 \n#endif\n\n#define BUFFERING 1\n\nnamespace embree\n{\n namespace network \n {\n __forceinline void initialize() {\n#ifdef __WIN32__\n static bool initialized = false;\n static MutexSys initMutex;\n Lock lock(initMutex);\n WSADATA wsaData;\n short version = MAKEWORD(1,1);\n if (WSAStartup(version,&wsaData) != 0)\n THROW_RUNTIME_ERROR(\"Winsock initialization failed\");\n initialized = true;\n#endif\n }\n\n struct buffered_socket_t \n {\n buffered_socket_t (SOCKET fd, size_t isize = 64*1024, size_t osize = 64*1024)\n : fd(fd), \n ibuf(new char[isize]), isize(isize), istart(0), iend(0),\n obuf(new char[osize]), osize(osize), oend(0) {\n }\n\n ~buffered_socket_t () {\n delete[] ibuf; ibuf = nullptr;\n delete[] obuf; obuf = nullptr;\n }\n \n SOCKET fd; \/\/!< file descriptor of the socket\n char* ibuf;\n size_t isize;\n size_t istart,iend;\n char* obuf;\n size_t osize;\n size_t oend;\n };\n\n socket_t connect(const char* host, unsigned short port) \n {\n initialize();\n\n \/*! create a new socket *\/\n SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot create socket\");\n \n \/*! perform DNS lookup *\/\n struct hostent* server = ::gethostbyname(host);\n if (server == nullptr) THROW_RUNTIME_ERROR(\"server \"+std::string(host)+\" not found\");\n \n \/*! perform connection *\/\n struct sockaddr_in serv_addr;\n memset((char*)&serv_addr, 0, sizeof(serv_addr));\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = (unsigned short) htons(port);\n memcpy((char*)&serv_addr.sin_addr.s_addr, (char*)server->h_addr, server->h_length);\n \n if (::connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)\n THROW_RUNTIME_ERROR(\"connection to \"+std::string(host)+\":\"+std::to_string((long long)port)+\" failed\");\n\n \/*! enable TCP_NODELAY *\/\n#ifdef TCP_NODELAY\n { int flag = 1; ::setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(int)); }\n#endif\n\n \/*! we do not want SIGPIPE to be thrown *\/\n#ifdef SO_NOSIGPIPE\n { int flag = 1; setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (const char*) &flag, sizeof(int)); }\n#endif\n \n return (socket_t) new buffered_socket_t(sockfd);\n }\n \n socket_t bind(unsigned short port)\n {\n initialize();\n\n \/*! create a new socket *\/\n SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot create socket\");\n\n \/* When the server completes, the server socket enters a time-wait state during which the local\n address and port used by the socket are believed to be in use by the OS. The wait state may\n last several minutes. This socket option allows bind() to reuse the port immediately. *\/\n#ifdef SO_REUSEADDR\n { int flag = true; ::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(int)); }\n#endif\n \n \/*! bind socket to port *\/\n struct sockaddr_in serv_addr;\n memset((char *) &serv_addr, 0, sizeof(serv_addr));\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = (unsigned short) htons(port);\n serv_addr.sin_addr.s_addr = INADDR_ANY;\n\n if (::bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)\n THROW_RUNTIME_ERROR(\"binding to port \"+std::to_string((long long)port)+\" failed\");\n \n \/*! listen to port, up to 5 pending connections *\/\n if (::listen(sockfd,5) < 0)\n THROW_RUNTIME_ERROR(\"listening on socket failed\");\n\n return (socket_t) new buffered_socket_t(sockfd);\n }\n \n socket_t listen(socket_t hsock)\n {\n SOCKET sockfd = ((buffered_socket_t*) hsock)->fd;\n \n \/*! accept incoming connection *\/\n struct sockaddr_in addr;\n socklen_t len = sizeof(addr);\n SOCKET fd = ::accept(sockfd, (struct sockaddr *) &addr, &len);\n if (fd == INVALID_SOCKET) THROW_RUNTIME_ERROR(\"cannot accept connection\");\n\n \/*! enable TCP_NODELAY *\/\n#ifdef TCP_NODELAY\n { int flag = 1; ::setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char*)&flag,sizeof(int)); }\n#endif\n\n \/*! we do not want SIGPIPE to be thrown *\/\n#ifdef SO_NOSIGPIPE\n { int flag = 1; setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&flag, sizeof(int)); }\n#endif\n\n return (socket_t) new buffered_socket_t(fd); \n }\n \n void read(socket_t hsock_i, void* data_i, size_t bytes)\n {\n#if BUFFERING\n char* data = (char*)data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n if (hsock->istart == hsock->iend) {\n ssize_t n = ::recv(hsock->fd,hsock->ibuf,hsock->isize,MSG_NOSIGNAL);\n if (n == 0) throw Disconnect();\n else if (n < 0) THROW_RUNTIME_ERROR(\"error reading from socket\");\n hsock->istart = 0;\n hsock->iend = n;\n }\n size_t bsize = hsock->iend-hsock->istart;\n if (bytes < bsize) bsize = bytes;\n memcpy(data,hsock->ibuf+hsock->istart,bsize);\n data += bsize;\n hsock->istart += bsize;\n bytes -= bsize;\n }\n#else\n char* data = (char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n ssize_t n = ::read(hsock->fd,data,bytes);\n if (n == 0) throw Disconnect();\n else if (n < 0) THROW_RUNTIME_ERROR(\"error reading from socket\");\n data+=n;\n bytes-=n;\n }\n#endif\n }\n\n void write(socket_t hsock_i, const void* data_i, size_t bytes)\n {\n#if BUFFERING\n const char* data = (const char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n if (hsock->oend == hsock->osize) flush(hsock_i);\n size_t bsize = hsock->osize-hsock->oend;\n if (bytes < bsize) bsize = bytes;\n memcpy(hsock->obuf+hsock->oend,data,bsize);\n data += bsize;\n hsock->oend += bsize;\n bytes -= bsize;\n }\n#else\n const char* data = (const char*) data_i;\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n while (bytes) {\n ssize_t n = ::write(hsock->fd,data,bytes);\n if (n < 0) THROW_RUNTIME_ERROR(\"error writing to socket\");\n data+=n;\n bytes-=n;\n }\n#endif\n }\n\n void flush(socket_t hsock_i)\n {\n#if BUFFERING\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n char* data = hsock->obuf;\n size_t bytes = hsock->oend;\n while (bytes > 0) {\n ssize_t n = ::send(hsock->fd,data,(int)bytes,MSG_NOSIGNAL);\n if (n < 0) THROW_RUNTIME_ERROR(\"error writing to socket\");\n bytes -= n;\n data += n;\n } \n hsock->oend = 0;\n#endif\n }\n \n void close(socket_t hsock_i) {\n buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;\n ::shutdown(hsock->fd,SHUT_RDWR);\n delete hsock;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ All Platforms\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace embree\n{\n namespace network \n {\n bool read_bool(socket_t socket) \n {\n bool value = 0;\n read(socket,&value,sizeof(bool));\n return value;\n }\n\n char read_char(socket_t socket) \n {\n char value = 0;\n read(socket,&value,sizeof(char));\n return value;\n }\n \n int read_int(socket_t socket) \n {\n int value = 0;\n read(socket,&value,sizeof(int));\n return value;\n }\n \n float read_float(socket_t socket) \n {\n float value = 0.0f;\n read(socket,&value,sizeof(float));\n return value;\n }\n \n std::string read_string(socket_t socket) \n {\n int bytes = read_int(socket);\n char* str = new char[bytes+1];\n read(socket,str,bytes);\n str[bytes] = 0x00;\n std::string s(str);\n delete[] str;\n return s;\n }\n\n void write(socket_t socket, bool value) {\n write(socket,&value,sizeof(bool));\n }\n\n void write(socket_t socket, char value) {\n write(socket,&value,sizeof(char));\n }\n \n void write(socket_t socket, int value) {\n write(socket,&value,sizeof(int));\n }\n \n void write(socket_t socket, float value) {\n write(socket,&value,sizeof(float));\n }\n \n void write(socket_t socket, const std::string& str) {\n write(socket,(int)str.size());\n write(socket,str.c_str(),str.size());\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ OricTAP.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 10\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"OricTAP.hpp\"\n\n#include \n\nusing namespace Storage::Tape;\n\nOricTAP::OricTAP(const char *file_name) : _file(NULL)\n{\n\tstruct stat file_stats;\n\tstat(file_name, &file_stats);\n\t_file_length = (size_t)file_stats.st_size;\n\n\t_file = fopen(file_name, \"rb\");\n\n\tif(!_file)\n\t\tthrow ErrorNotOricTAP;\n\n\t\/\/ read and check the file signature\n\tuint8_t signature[4];\n\tif(fread(signature, 1, 4, _file) != 4)\n\t\tthrow ErrorNotOricTAP;\n\n\tif(signature[0] != 0x16 || signature[1] != 0x16 || signature[2] != 0x16 || signature[3] != 0x24)\n\t\tthrow ErrorNotOricTAP;\n\n\t\/\/ then rewind and start again\n\tvirtual_reset();\n}\n\nOricTAP::~OricTAP()\n{\n\tif(_file) fclose(_file);\n}\n\nvoid OricTAP::virtual_reset()\n{\n\/\/\tfseek(_file, 0, SEEK_SET);\n\t_bit_count = 13;\n\t_phase = _next_phase = LeadIn;\n\t_phase_counter = 0;\n\t_pulse_counter = 0;\n}\n\nTape::Pulse OricTAP::virtual_get_next_pulse()\n{\n\t\/\/ Each byte byte is written as 13 bits: 0, eight bits of data, parity, three 1s.\n\tif(_bit_count == 13)\n\t{\n\t\tif(_next_phase != _phase)\n\t\t{\n\t\t\t_phase = _next_phase;\n\t\t\t_phase_counter = 0;\n\t\t}\n\n\t\t_bit_count = 0;\n\t\tuint8_t next_byte = 0;\n\t\tswitch(_phase)\n\t\t{\n\t\t\tcase LeadIn:\n\t\t\t\tnext_byte = _phase_counter < 256 ? 0x16 : 0x24;\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == 259)\t\/\/ 256 artificial bytes plus the three in the file = 259\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Header;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Header:\n\t\t\t\t\/\/ Counts are relative to:\n\t\t\t\t\/\/ [0, 1]:\t\t\"two bytes unused\" (on the Oric 1)\n\t\t\t\t\/\/ 2:\t\t\tprogram type\n\t\t\t\t\/\/ 3:\t\t\tauto indicator\n\t\t\t\t\/\/ [4, 5]:\t\tend address of data\n\t\t\t\t\/\/ [6, 7]:\t\tstart address of data\n\t\t\t\t\/\/ 8:\t\t\t\"unused\" (on the Oric 1)\n\t\t\t\t\/\/ [9...]:\t\tfilename, up to NULL byte\n\t\t\t\tnext_byte = (uint8_t)fgetc(_file);\n\n\t\t\t\tif(_phase_counter == 4)\t_data_end_address = (uint16_t)(next_byte << 8);\n\t\t\t\tif(_phase_counter == 5)\t_data_end_address |= next_byte;\n\t\t\t\tif(_phase_counter == 6)\t_data_start_address = (uint16_t)(next_byte << 8);\n\t\t\t\tif(_phase_counter == 7)\t_data_start_address |= next_byte;\n\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter >= 9 && !next_byte)\t\/\/ advance after the filename-ending NULL byte\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Gap;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Gap:\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == 8)\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Data;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Data:\n\t\t\t\tnext_byte = (uint8_t)fgetc(_file);\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == (_data_end_address - _data_start_address))\n\t\t\t\t{\n\t\t\t\t\t_phase_counter = 0;\n\t\t\t\t\tif((size_t)ftell(_file) == _file_length)\n\t\t\t\t\t{\n\t\t\t\t\t\t_next_phase = End;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t_next_phase = LeadIn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase End:\n\t\t\tbreak;\n\t\t}\n\n\t\tuint8_t parity = next_byte;\n\t\tparity ^= (parity >> 4);\n\t\tparity ^= (parity >> 2);\n\t\tparity ^= (parity >> 1);\n\t\t_current_value = (uint16_t)(((uint16_t)next_byte << 1) | ((parity&1) << 9) | (7 << 10));\n\t}\n\n\t\/\/ In slow mode, a 0 is 4 periods of 1200 Hz, a 1 is 8 periods at 2400 Hz.\n\t\/\/ In fast mode, a 1 is a single period of 2400 Hz, a 0 is a 2400 Hz pulse followed by a 1200 Hz pulse.\n\t\/\/ This code models fast mode.\n\tTape::Pulse pulse;\n\tpulse.length.clock_rate = 4800;\n\tint next_bit;\n\n\tswitch(_phase)\n\t{\n\t\tcase End:\n\t\t\tpulse.type = Pulse::Zero;\n\t\t\tpulse.length.length = 4800;\n\t\treturn pulse;\n\n\t\tcase Gap:\n\t\t\tnext_bit = 1;\n\t\tbreak;\n\n\t\tdefault:\n\t\t\tnext_bit = _current_value & 1;\n\t\tbreak;\n\t}\n\n\tif(next_bit)\n\t{\n\t\tpulse.length.length = 1;\n\t}\n\telse\n\t{\n\t\tpulse.length.length = _pulse_counter ? 2 : 1;\n\t}\n\tpulse.type = _pulse_counter ? Pulse::High : Pulse::Low;\t\/\/ TODO\n\n\t_pulse_counter ^= 1;\n\tif(!_pulse_counter)\n\t{\n\t\t_current_value >>= 1;\n\t\t_bit_count++;\n\t}\n\treturn pulse;\n}\n\nbool OricTAP::is_at_end()\n{\n\treturn _phase == End;\n}\nFirst successful game loaded! It turns out exactly one '$' is correct. Probably.\/\/\n\/\/ OricTAP.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 10\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"OricTAP.hpp\"\n\n#include \n\nusing namespace Storage::Tape;\n\nOricTAP::OricTAP(const char *file_name) : _file(NULL)\n{\n\tstruct stat file_stats;\n\tstat(file_name, &file_stats);\n\t_file_length = (size_t)file_stats.st_size;\n\n\t_file = fopen(file_name, \"rb\");\n\n\tif(!_file)\n\t\tthrow ErrorNotOricTAP;\n\n\t\/\/ read and check the file signature\n\tuint8_t signature[4];\n\tif(fread(signature, 1, 4, _file) != 4)\n\t\tthrow ErrorNotOricTAP;\n\n\tif(signature[0] != 0x16 || signature[1] != 0x16 || signature[2] != 0x16 || signature[3] != 0x24)\n\t\tthrow ErrorNotOricTAP;\n\n\t\/\/ then rewind and start again\n\tvirtual_reset();\n}\n\nOricTAP::~OricTAP()\n{\n\tif(_file) fclose(_file);\n}\n\nvoid OricTAP::virtual_reset()\n{\n\/\/\tfseek(_file, 0, SEEK_SET);\n\t_bit_count = 13;\n\t_phase = _next_phase = LeadIn;\n\t_phase_counter = 0;\n\t_pulse_counter = 0;\n}\n\nTape::Pulse OricTAP::virtual_get_next_pulse()\n{\n\t\/\/ Each byte byte is written as 13 bits: 0, eight bits of data, parity, three 1s.\n\tif(_bit_count == 13)\n\t{\n\t\tif(_next_phase != _phase)\n\t\t{\n\t\t\t_phase = _next_phase;\n\t\t\t_phase_counter = 0;\n\t\t}\n\n\t\t_bit_count = 0;\n\t\tuint8_t next_byte = 0;\n\t\tswitch(_phase)\n\t\t{\n\t\t\tcase LeadIn:\n\t\t\t\tnext_byte = _phase_counter < 258 ? 0x16 : 0x24;\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == 259)\t\/\/ 256 artificial bytes plus the three in the file = 259\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Header;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Header:\n\t\t\t\t\/\/ Counts are relative to:\n\t\t\t\t\/\/ [0, 1]:\t\t\"two bytes unused\" (on the Oric 1)\n\t\t\t\t\/\/ 2:\t\t\tprogram type\n\t\t\t\t\/\/ 3:\t\t\tauto indicator\n\t\t\t\t\/\/ [4, 5]:\t\tend address of data\n\t\t\t\t\/\/ [6, 7]:\t\tstart address of data\n\t\t\t\t\/\/ 8:\t\t\t\"unused\" (on the Oric 1)\n\t\t\t\t\/\/ [9...]:\t\tfilename, up to NULL byte\n\t\t\t\tnext_byte = (uint8_t)fgetc(_file);\n\n\t\t\t\tif(_phase_counter == 4)\t_data_end_address = (uint16_t)(next_byte << 8);\n\t\t\t\tif(_phase_counter == 5)\t_data_end_address |= next_byte;\n\t\t\t\tif(_phase_counter == 6)\t_data_start_address = (uint16_t)(next_byte << 8);\n\t\t\t\tif(_phase_counter == 7)\t_data_start_address |= next_byte;\n\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter >= 9 && !next_byte)\t\/\/ advance after the filename-ending NULL byte\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Gap;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Gap:\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == 8)\n\t\t\t\t{\n\t\t\t\t\t_next_phase = Data;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase Data:\n\t\t\t\tnext_byte = (uint8_t)fgetc(_file);\n\t\t\t\t_phase_counter++;\n\t\t\t\tif(_phase_counter == (_data_end_address - _data_start_address))\n\t\t\t\t{\n\t\t\t\t\t_phase_counter = 0;\n\t\t\t\t\tif((size_t)ftell(_file) == _file_length)\n\t\t\t\t\t{\n\t\t\t\t\t\t_next_phase = End;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t_next_phase = LeadIn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase End:\n\t\t\tbreak;\n\t\t}\n\n\t\tuint8_t parity = next_byte;\n\t\tparity ^= (parity >> 4);\n\t\tparity ^= (parity >> 2);\n\t\tparity ^= (parity >> 1);\n\t\t_current_value = (uint16_t)(((uint16_t)next_byte << 1) | ((parity&1) << 9) | (7 << 10));\n\t}\n\n\t\/\/ In slow mode, a 0 is 4 periods of 1200 Hz, a 1 is 8 periods at 2400 Hz.\n\t\/\/ In fast mode, a 1 is a single period of 2400 Hz, a 0 is a 2400 Hz pulse followed by a 1200 Hz pulse.\n\t\/\/ This code models fast mode.\n\tTape::Pulse pulse;\n\tpulse.length.clock_rate = 4800;\n\tint next_bit;\n\n\tswitch(_phase)\n\t{\n\t\tcase End:\n\t\t\tpulse.type = Pulse::Zero;\n\t\t\tpulse.length.length = 4800;\n\t\treturn pulse;\n\n\t\tcase Gap:\n\t\t\tnext_bit = 1;\n\t\tbreak;\n\n\t\tdefault:\n\t\t\tnext_bit = _current_value & 1;\n\t\tbreak;\n\t}\n\n\tif(next_bit)\n\t{\n\t\tpulse.length.length = 1;\n\t}\n\telse\n\t{\n\t\tpulse.length.length = _pulse_counter ? 2 : 1;\n\t}\n\tpulse.type = _pulse_counter ? Pulse::High : Pulse::Low;\t\/\/ TODO\n\n\t_pulse_counter ^= 1;\n\tif(!_pulse_counter)\n\t{\n\t\t_current_value >>= 1;\n\t\t_bit_count++;\n\t}\n\treturn pulse;\n}\n\nbool OricTAP::is_at_end()\n{\n\treturn _phase == End;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009-2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#ifndef LIBPORT_SERIALIZE_BINARY_I_SERIALIZER_HXX\n# define LIBPORT_SERIALIZE_BINARY_I_SERIALIZER_HXX\n\n# include \n\n# include \n\n# include \n# include \n# include \n# include \n# include \n# include \n\n\nnamespace libport\n{\n namespace serialize\n {\n \/*----------------.\n | Generic class. |\n `----------------*\/\n template \n struct ICImpl\n {\n static T\n get(const std::string&, std::istream&, BinaryISerializer& ser)\n {\n return T(ser);\n }\n };\n\n \/*------------.\n | Hierarchy. |\n `------------*\/\n template \n struct ISerialize\n {\n static void\n res(const std::pair& c)\n {\n *c.first = reinterpret_cast(new T(*c.second));\n }\n };\n\n template \n struct IHImpl\n {\n static T*\n get(const std::string&,\n std::istream&, BinaryISerializer& ser)\n {\n unsigned id = ser.unserialize(\"id\");\n typename T::root* res = 0;\n typedef std::pair Cookie;\n Cookie c(&res, &ser);\n T::template dispatch(id, c);\n return reinterpret_cast(res);\n }\n };\n\n \/*-----------.\n | Fallback. |\n `-----------*\/\n template \n struct BinaryISerializer::Impl\n {\n static typename meta::If::res,\n T*, T>::res\n get(const std::string& name,\n std::istream& output, BinaryISerializer& ser)\n {\n return meta::If::res,\n IHImpl, ICImpl >::res::get(name, output, ser);\n }\n };\n\n \/*-------.\n | char. |\n `-------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static char get(const std::string&, std::istream& input,\n BinaryISerializer&)\n {\n char res;\n input.read(&res, sizeof(char));\n return res;\n }\n };\n\n \/*---------------------.\n | unsigned int\/short. |\n `---------------------*\/\n# define SERIALIZE_NET_INTEGRAL(Type, Function) \\\n template <> \\\n struct BinaryISerializer::Impl \\\n { \\\n static Type \\\n get(const std::string&, std::istream& input, \\\n BinaryISerializer&) \\\n { \\\n Type normalized; \\\n input.read(reinterpret_cast(&normalized), sizeof(Type)); \\\n return Function(normalized); \\\n } \\\n };\n\n SERIALIZE_NET_INTEGRAL(unsigned int, ntohl);\n SERIALIZE_NET_INTEGRAL(unsigned short, ntohs);\n#undef SERIALIZE_NET_INTEGRAL\n\n \/*---------.\n | double. |\n `---------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static double get(const std::string&, std::istream& input,\n BinaryISerializer&)\n {\n \/\/ FIXME: non-portable\n double res;\n input.read(reinterpret_cast(&res), sizeof(double));\n return res;\n }\n };\n\n\/\/\/ Define the handling of To using the implementation for From.\n#define BOUNCE(From, To) \\\n template <> \\\n struct BinaryISerializer::Impl \\\n { \\\n static From get(const std::string& name, \\\n std::istream& input, BinaryISerializer& ser) \\\n { \\\n return static_cast(Impl::get(name, input, ser)); \\\n } \\\n }\n\n BOUNCE(bool, char);\n BOUNCE(unsigned char, char);\n BOUNCE(int, unsigned);\n BOUNCE(short, unsigned short);\n#undef BOUNCE\n\n \/*-----------.\n | Pointers. |\n `-----------*\/\n template \n struct BinaryISerializer::PCImpl\n {\n static T*\n res(BinaryISerializer& ser, std::istream& input)\n {\n T* res = reinterpret_cast(new char[sizeof(T)]);\n ser.ptr_map_.push_back(res);\n \/\/ FIXME: copy ctor\n new (res) T(BinaryISerializer::Impl::get(\"value\", input, ser));\n return res;\n }\n };\n\n template \n struct BinaryISerializer::PHImpl\n {\n static T*\n res(BinaryISerializer& ser, std::istream& input)\n {\n unsigned id = ser.ptr_map_.size();\n ser.ptr_map_.push_back(0);\n \/\/ FIXME: loops\n T* res = BinaryISerializer::Impl::get(\"value\", input, ser);\n ser.ptr_map_[id] = res;\n return res;\n }\n };\n\n template \n struct BinaryISerializer::Impl\n {\n static T* get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n pointer_status status =\n static_cast(Impl::get(\"opt\", input, ser));\n switch (status)\n {\n case null:\n return 0;\n case cached:\n {\n unsigned id = Impl::get(\"id\", input, ser);\n assert_lt(id, ser.ptr_map_.size());\n return reinterpret_cast(ser.ptr_map_[id]);\n }\n case serialized:\n {\n return meta::If::res,\n PHImpl, PCImpl >::res\n ::res(ser, input);\n }\n }\n \/\/ GCC bug prevents this: unreachable();\n \/\/ http:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=44580\n abort();\n }\n };\n\n \/*-----------------.\n | Boost optional. |\n `-----------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef boost::optional type;\n static type get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n pointer_status status =\n static_cast(Impl::get(\"opt\", input, ser));\n switch (status)\n {\n case null:\n return 0;\n case cached:\n assert(!\"Impossible 'cached' value \"\n \"for a serialized boost::optional.\");\n case serialized:\n return BinaryISerializer::Impl::get(\"value\", input, ser);\n }\n abort();\n }\n };\n\n \/*------------.\n | std::pair. |\n `------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef std::pair type;\n static type get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n A first = BinaryISerializer::Impl::get(\"first\", input, ser);\n B second = BinaryISerializer::Impl::get(\"second\", input, ser);\n return type(first, second);\n }\n };\n\n \/*--------------.\n | std::string. |\n `--------------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static std::string get(const std::string& name, std::istream& input,\n BinaryISerializer& ser)\n {\n size_t l = Impl::get(name, input, ser);\n \/\/ FIXME: alloca\n char* buf = new char[l];\n input.read(buf, std::streamsize(l));\n std::string res(buf, l);\n delete [] buf;\n return res;\n }\n };\n\n \/*--------------.\n | std::vector. |\n `--------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n static std::vector\n get(const std::string& name,\n std::istream& input, BinaryISerializer& ser)\n {\n unsigned short size = Impl::get(name, input, ser);\n std::vector res;\n for (unsigned i = 0; i < size; ++i)\n res.push_back(Impl::get(name, input, ser));\n return res;\n }\n };\n\n\n \/\/ Hash and Symbol serialization is defined here because of\n \/\/ serialization\/hash\/symbol dependency loop.\n\n \/*------------------.\n | libport::Symbol. |\n `------------------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static libport::Symbol\n get(const std::string& name, std::istream& input,\n BinaryISerializer& ser)\n {\n bool cached = Impl::get(\"opt\", input, ser);\n if (cached)\n {\n unsigned id = Impl::get(\"id\", input, ser);\n return ser.sym_map_[id];\n }\n Symbol res(Impl::get(name, input, ser));\n ser.sym_map_.push_back(res);\n return res;\n }\n };\n\n \/*----------------.\n | libport::hash. |\n `----------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef boost::unordered_map result_type;\n static result_type\n get(const std::string&, std::istream&, BinaryISerializer& ser)\n {\n typedef typename result_type::value_type Value;\n size_t size = ser.unserialize(\"size\");\n result_type res;\n for (unsigned i = 0; i < size; ++i)\n {\n K k = ser.template unserialize(\"key\");\n V v = ser.template unserialize(\"value\");\n res[k] = v;\n }\n return res;\n }\n };\n }\n}\n\n#endif\nserializer: fix typo.\/*\n * Copyright (C) 2009-2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#ifndef LIBPORT_SERIALIZE_BINARY_I_SERIALIZER_HXX\n# define LIBPORT_SERIALIZE_BINARY_I_SERIALIZER_HXX\n\n# include \n\n# include \n\n# include \n# include \n# include \n# include \n# include \n# include \n\n\nnamespace libport\n{\n namespace serialize\n {\n \/*----------------.\n | Generic class. |\n `----------------*\/\n template \n struct ICImpl\n {\n static T\n get(const std::string&, std::istream&, BinaryISerializer& ser)\n {\n return T(ser);\n }\n };\n\n \/*------------.\n | Hierarchy. |\n `------------*\/\n template \n struct ISerialize\n {\n static void\n res(const std::pair& c)\n {\n *c.first = reinterpret_cast(new T(*c.second));\n }\n };\n\n template \n struct IHImpl\n {\n static T*\n get(const std::string&,\n std::istream&, BinaryISerializer& ser)\n {\n unsigned id = ser.unserialize(\"id\");\n typename T::root* res = 0;\n typedef std::pair Cookie;\n Cookie c(&res, &ser);\n T::template dispatch(id, c);\n return reinterpret_cast(res);\n }\n };\n\n \/*-----------.\n | Fallback. |\n `-----------*\/\n template \n struct BinaryISerializer::Impl\n {\n static typename meta::If::res,\n T*, T>::res\n get(const std::string& name,\n std::istream& output, BinaryISerializer& ser)\n {\n return meta::If::res,\n IHImpl, ICImpl >::res::get(name, output, ser);\n }\n };\n\n \/*-------.\n | char. |\n `-------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static char get(const std::string&, std::istream& input,\n BinaryISerializer&)\n {\n char res;\n input.read(&res, sizeof(char));\n return res;\n }\n };\n\n \/*---------------------.\n | unsigned int\/short. |\n `---------------------*\/\n# define SERIALIZE_NET_INTEGRAL(Type, Function) \\\n template <> \\\n struct BinaryISerializer::Impl \\\n { \\\n static Type \\\n get(const std::string&, std::istream& input, \\\n BinaryISerializer&) \\\n { \\\n Type normalized; \\\n input.read(reinterpret_cast(&normalized), sizeof(Type)); \\\n return Function(normalized); \\\n } \\\n };\n\n SERIALIZE_NET_INTEGRAL(unsigned int, ntohl);\n SERIALIZE_NET_INTEGRAL(unsigned short, ntohs);\n#undef SERIALIZE_NET_INTEGRAL\n\n \/*---------.\n | double. |\n `---------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static double get(const std::string&, std::istream& input,\n BinaryISerializer&)\n {\n \/\/ FIXME: non-portable\n double res;\n input.read(reinterpret_cast(&res), sizeof(double));\n return res;\n }\n };\n\n\/\/\/ Define the handling of To using the implementation for From.\n#define BOUNCE(From, To) \\\n template <> \\\n struct BinaryISerializer::Impl \\\n { \\\n static From get(const std::string& name, \\\n std::istream& input, BinaryISerializer& ser) \\\n { \\\n return static_cast(Impl::get(name, input, ser)); \\\n } \\\n }\n\n BOUNCE(bool, char);\n BOUNCE(unsigned char, char);\n BOUNCE(int, unsigned);\n BOUNCE(short, unsigned short);\n#undef BOUNCE\n\n \/*-----------.\n | Pointers. |\n `-----------*\/\n template \n struct BinaryISerializer::PCImpl\n {\n static T*\n res(BinaryISerializer& ser, std::istream& input)\n {\n T* res = reinterpret_cast(new char[sizeof(T)]);\n ser.ptr_map_.push_back(res);\n \/\/ FIXME: copy ctor\n new (res) T(BinaryISerializer::Impl::get(\"value\", input, ser));\n return res;\n }\n };\n\n template \n struct BinaryISerializer::PHImpl\n {\n static T*\n res(BinaryISerializer& ser, std::istream& input)\n {\n unsigned id = ser.ptr_map_.size();\n ser.ptr_map_.push_back(0);\n \/\/ FIXME: loops\n T* res = BinaryISerializer::Impl::get(\"value\", input, ser);\n ser.ptr_map_[id] = res;\n return res;\n }\n };\n\n template \n struct BinaryISerializer::Impl\n {\n static T* get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n pointer_status status =\n static_cast(Impl::get(\"opt\", input, ser));\n switch (status)\n {\n case null:\n return 0;\n case cached:\n {\n unsigned id = Impl::get(\"id\", input, ser);\n assert_lt(id, ser.ptr_map_.size());\n return reinterpret_cast(ser.ptr_map_[id]);\n }\n case serialized:\n {\n return meta::If::res,\n PHImpl, PCImpl >::res\n ::res(ser, input);\n }\n }\n \/\/ GCC bug prevents this: unreachable();\n \/\/ http:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=44580\n abort();\n }\n };\n\n \/*-----------------.\n | Boost optional. |\n `-----------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef boost::optional type;\n static type get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n pointer_status status =\n static_cast(Impl::get(\"opt\", input, ser));\n switch (status)\n {\n case null:\n return 0;\n case cached:\n assert(!\"Impossible 'cached' value \"\n \"for a serialized boost::optional.\");\n case serialized:\n return BinaryISerializer::Impl::get(\"value\", input, ser);\n }\n abort();\n }\n };\n\n \/*------------.\n | std::pair. |\n `------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef std::pair type;\n static type get(const std::string&, std::istream& input,\n BinaryISerializer& ser)\n {\n A first = BinaryISerializer::Impl::get(\"first\", input, ser);\n B second = BinaryISerializer::Impl::get(\"second\", input, ser);\n return type(first, second);\n }\n };\n\n \/*--------------.\n | std::string. |\n `--------------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static std::string get(const std::string& name, std::istream& input,\n BinaryISerializer& ser)\n {\n size_t l = Impl::get(name, input, ser);\n \/\/ FIXME: alloca\n char* buf = new char[l];\n input.read(buf, std::streamsize(l));\n std::string res(buf, l);\n delete [] buf;\n return res;\n }\n };\n\n \/*--------------.\n | std::vector. |\n `--------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n static std::vector\n get(const std::string& name,\n std::istream& input, BinaryISerializer& ser)\n {\n unsigned short size = Impl::get(name, input, ser);\n std::vector res;\n for (unsigned i = 0; i < size; ++i)\n res.push_back(Impl::get(name, input, ser));\n return res;\n }\n };\n\n\n \/\/ Hash and Symbol serialization is defined here because of\n \/\/ serialization\/hash\/symbol dependency loop.\n\n \/*------------------.\n | libport::Symbol. |\n `------------------*\/\n template <>\n struct BinaryISerializer::Impl\n {\n static libport::Symbol\n get(const std::string& name, std::istream& input,\n BinaryISerializer& ser)\n {\n bool cached = Impl::get(\"opt\", input, ser);\n if (cached)\n {\n unsigned id = Impl::get(\"id\", input, ser);\n return ser.sym_map_[id];\n }\n Symbol res(Impl::get(name, input, ser));\n ser.sym_map_.push_back(res);\n return res;\n }\n };\n\n \/*----------------.\n | libport::hash. |\n `----------------*\/\n template \n struct BinaryISerializer::Impl >\n {\n typedef boost::unordered_map result_type;\n static result_type\n get(const std::string&, std::istream&, BinaryISerializer& ser)\n {\n typedef typename result_type::value_type Value;\n size_t size = ser.unserialize(\"size\");\n result_type res;\n for (unsigned i = 0; i < size; ++i)\n {\n K k = ser.template unserialize(\"key\");\n V v = ser.template unserialize(\"value\");\n res[k] = v;\n }\n return res;\n }\n };\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#ifndef __CERBERUS_COMMON_HPP__\n#define __CERBERUS_COMMON_HPP__\n\n#include \n\n#define VERSION \"0.7.11-2017-03-29\"\n\nnamespace cerb {\n\n using byte = unsigned char;\n using rint = int64_t;\n using slot = unsigned int;\n using msize_t = uint64_t;\n\n typedef std::chrono::high_resolution_clock Clock;\n typedef Clock::time_point Time;\n typedef std::chrono::duration Interval;\n\n constexpr msize_t CLUSTER_SLOT_COUNT = 16384;\n\n}\n\n#endif \/* __CERBERUS_COMMON_HPP__ *\/\nVersion: 0.0.8#ifndef __CERBERUS_COMMON_HPP__\n#define __CERBERUS_COMMON_HPP__\n\n#include \n\n#define VERSION \"0.8.0-2018-05-02\"\n\nnamespace cerb {\n\n using byte = unsigned char;\n using rint = int64_t;\n using slot = unsigned int;\n using msize_t = uint64_t;\n\n typedef std::chrono::high_resolution_clock Clock;\n typedef Clock::time_point Time;\n typedef std::chrono::duration Interval;\n\n constexpr msize_t CLUSTER_SLOT_COUNT = 16384;\n\n}\n\n#endif \/* __CERBERUS_COMMON_HPP__ *\/\n<|endoftext|>"} {"text":"\/*\n * Author:\n * Guido Tack \n *\n * Copyright:\n * NICTA 2013\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"project.h\"\n#include \"moocsubmission.h\"\n#include \"solverdialog.h\"\n#include \"process.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nProject::Project(const QList& configs, QObject* parent) : QObject(parent), solverConfigs(configs)\n{\n itemModel = new QStandardItemModel(this);\n itemModel->setColumnCount(1);\n\n connect(itemModel, &QStandardItemModel::itemChanged, this, &Project::on_itemChanged);\n\n rootItem = new QStandardItem(QIcon(\":\/images\/mznicon.png\"), \"Untitled Project\");\n rootItem->setData(NodeType::ProjectFile, Role::Type);\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n rootItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n\n auto font = rootItem->font();\n font.setBold(true);\n\n modelsItem = new QStandardItem(\"Models\");\n modelsItem->setData(NodeType::Group, Role::Type);\n modelsItem->setFlags(Qt::NoItemFlags);\n modelsItem->setFont(font);\n\n dataItem = new QStandardItem(\"Data (right click to run)\");\n dataItem->setData(NodeType::Group, Role::Type);\n dataItem->setFlags(Qt::NoItemFlags);\n dataItem->setFont(font);\n\n checkersItem = new QStandardItem(\"Checkers (right click to run)\");\n checkersItem->setData(NodeType::Group, Role::Type);\n checkersItem->setFlags(Qt::NoItemFlags);\n checkersItem->setFont(font);\n\n configsItem = new QStandardItem(\"Solver configurations\");\n configsItem->setData(NodeType::Group, Role::Type);\n configsItem->setFlags(Qt::NoItemFlags);\n configsItem->setFont(font);\n\n otherItem = new QStandardItem(\"Other files\");\n otherItem->setData(NodeType::Group, Role::Type);\n otherItem->setFlags(Qt::NoItemFlags);\n otherItem->setFont(font);\n\n rootItem->appendRow(modelsItem);\n rootItem->appendRow(dataItem);\n rootItem->appendRow(checkersItem);\n rootItem->appendRow(configsItem);\n rootItem->appendRow(otherItem);\n itemModel->appendRow(rootItem);\n}\n\nQStringList Project::loadProject(const QString& file, ConfigWindow* configWindow)\n{\n clear();\n\n projectFile(file);\n\n QStringList warnings;\n\n QFile f(file);\n QFileInfo fi(f);\n if (!f.open(QFile::ReadOnly)) {\n throw FileError(\"Failed to open project file\");\n }\n\n auto doc = QJsonDocument::fromJson(f.readAll());\n\n if (doc.isObject()) {\n loadJSON(doc.object(), fi, configWindow, warnings);\n } else {\n f.reset();\n QDataStream in(&f);\n loadLegacy(in, fi, configWindow, warnings);\n }\n\n f.close();\n\n for (auto& sc : solverConfigurationFiles()) {\n configWindow->addConfig(sc);\n }\n\n if (!selectedBuiltinConfigId.isEmpty()) {\n int index = configWindow->findBuiltinConfig(selectedBuiltinConfigId, selectedBuiltinConfigVersion);\n if (index == -1) {\n warnings << \"Could not find solver \" + selectedBuiltinConfigId + \"@\" + selectedBuiltinConfigVersion;\n } else {\n configWindow->setCurrentIndex(index);\n }\n } else if (!selectedSolverConfigFile.isEmpty()) {\n int index = configWindow->findConfigFile(rootDir().absolutePath() + \"\/\" + selectedSolverConfigFile);\n configWindow->setCurrentIndex(index);\n }\n\n setModified(false);\n\n return warnings;\n}\n\nvoid Project::loadJSON(const QJsonObject& obj, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n int version = obj[\"version\"].toInt();\n\n QString basePath = fi.absolutePath() + \"\/\";\n\n auto of = obj[\"openFiles\"].toArray();\n for (auto file : of) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n openTabs << path;\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n\n openTabIndex = obj[\"openTab\"].toInt();\n\n QList configs;\n if (obj[\"builtinSolverConfigs\"].isArray()) {\n for (auto config : obj[\"builtinSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver builtin solver config\";\n continue;\n }\n SolverConfiguration* loaded;\n if (version >= 106) {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadJSON(QJsonDocument(config.toObject())));\n } else {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n }\n loaded->isBuiltin = true;\n configs << loaded;\n }\n }\n\n if (obj[\"projectSolverConfigs\"].isArray()) {\n for (auto config : obj[\"projectSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver project solver config\";\n continue;\n }\n auto loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n loaded->modified = true;\n configs << loaded;\n }\n }\n\n configWindow->mergeConfigs(configs);\n\n if (obj[\"selectedBuiltinConfigId\"].isString()) {\n selectedBuiltinConfigId = obj[\"selectedBuiltinConfigId\"].toString();\n selectedBuiltinConfigVersion = obj[\"selectedBuiltinConfigVersion\"].toString();\n selectedSolverConfigFile = \"\";\n\n } else if (obj[\"selectedSolverConfigFile\"].isString()) {\n selectedSolverConfigFile = obj[\"selectedSolverConfigFile\"].toString();\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n } \/*else {\n warnings << \"No selected solver config in project\";\n }*\/\n\n for (auto file : obj[\"projectFiles\"].toArray()) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n add(path);\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n}\n\nvoid Project::loadLegacy(QDataStream& in, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n \/\/ Load old binary format of project\n throw InternalError(\"This project format is no longer supported. Please use MiniZinc IDE version 2.4 to upgrade it.\");\n}\n\nvoid Project::saveProject()\n{\n QJsonObject confObject;\n confObject[\"version\"] = 106;\n\n \/\/ Save the currently open tabs\n QStringList of;\n for (auto& f: openTabs) {\n of << relativeToProject(f);\n }\n confObject[\"openFiles\"] = QJsonArray::fromStringList(of);\n confObject[\"openTab\"] = openTabIndex;\n\n \/\/ Save paths of all project files\n QStringList relativeFilePaths;\n for (auto& file : files()) {\n relativeFilePaths << relativeToProject(file);\n }\n confObject[\"projectFiles\"] = QJsonArray::fromStringList(relativeFilePaths);\n\n \/\/ Save which config is currently selected\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n confObject[\"selectedBuiltinConfigId\"] = selectedBuiltinConfigId;\n confObject[\"selectedBuiltinConfigVersion\"] = selectedBuiltinConfigVersion;\n } else if (!selectedSolverConfigFile.isEmpty()){\n confObject[\"selectedSolverConfigFile\"] = selectedSolverConfigFile;\n }\n\n \/\/ Write project file\n QJsonDocument doc(confObject);\n QFile file(projectFile());\n if (!file.open(QFile::WriteOnly)) {\n throw FileError(\"Failed to write file\");\n }\n file.write(doc.toJson());\n file.close();\n\n setModified(false);\n}\n\nvoid Project::add(const QString& fileName)\n{\n auto abs = QFileInfo(fileName).absoluteFilePath();\n auto path = relativeToProject(fileName);\n if (contains(abs)) {\n return;\n }\n\n auto parts = path.split(\"\/\", QString::SkipEmptyParts); \/\/ Qt always uses \/ as the path separator\n auto file = parts.takeLast();\n\n QStandardItem* node = otherItem;\n QString icon;\n NodeType type = NodeType::Other;\n if (file.endsWith(\".mzc.mzn\") || file.endsWith(\".mzc\")) {\n node = checkersItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Checker;\n } else if (file.endsWith(\".mzn\")) {\n node = modelsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Model;\n } else if (file.endsWith(\".dzn\") || file.endsWith(\".json\")) {\n node = dataItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Data;\n } else if (file.endsWith(\".mpc\")) {\n node = configsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::SolverConfig;\n } else if (file == \"_mooc\" || file == \"_coursera\") {\n if (mooc) {\n delete mooc;\n }\n mooc = new MOOCAssignment(fileName);\n emit moocChanged(mooc);\n }\n\n node->setFlags(Qt::ItemIsEnabled);\n\n \/\/ Traverse existing path items\n int i = 0;\n while (!parts.empty() && i < node->rowCount()) {\n if (getType(node->child(i)->index()) == NodeType::Dir &&\n node->child(i)->text() == parts.first()) {\n parts.pop_front();\n node = node->child(i);\n i = 0;\n } else {\n i++;\n }\n }\n \/\/ Create new path items\n for (auto& part : parts) {\n auto dir = new QStandardItem(QIcon(\":\/icons\/images\/folder.png\"), part);\n dir->setData(NodeType::Dir, Role::Type);\n dir->setFlags(Qt::ItemIsEnabled);\n node->appendRow(dir);\n node->sortChildren(0);\n node = dir;\n }\n \/\/ Add file item\n auto item = new QStandardItem(QIcon(icon), file);\n item->setData(type, Role::Type);\n item->setData(abs, Role::Path);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n node->appendRow(item);\n node->sortChildren(0);\n\n entries.insert(abs, item);\n\n if (!projectFile().isEmpty()) {\n setModified(true);\n }\n}\n\nvoid Project::add(const QStringList& fileNames)\n{\n for (auto& fileName : fileNames) {\n add(fileName);\n }\n}\n\nvoid Project::remove(const QString &fileName)\n{\n auto path = QFileInfo(fileName).absoluteFilePath();\n if (!contains(path)) {\n return;\n }\n\n \/\/ Make sure we also remove any unused dirs\n auto node = entries[path];\n if (node->text() == \"_mooc\" || node->text() == \"_coursera\") {\n delete mooc;\n mooc = nullptr;\n emit moocChanged(mooc);\n }\n while (getType(node->parent()->index()) == NodeType::Dir && node->parent()->rowCount() <= 1) {\n node = node->parent();\n }\n auto parent = node->parent();\n parent->removeRow(node->row());\n if (parent->data(Role::Type) == \"group\" && !parent->hasChildren()) {\n parent->setFlags(Qt::NoItemFlags);\n }\n entries.remove(path);\n\n if (!projectFile().isEmpty()) {\n setModified(true);\n }\n}\n\nvoid Project::remove(const QStringList &fileNames)\n{\n for (auto& fileName : fileNames) {\n remove(fileName);\n }\n}\n\nvoid Project::remove(const QModelIndex& index)\n{\n remove(getFileName(index));\n}\n\nvoid Project::remove(const QModelIndexList& indexes)\n{\n for (auto& index : indexes) {\n remove(index);\n }\n}\n\nvoid Project::clear()\n{\n modelsItem->removeRows(0, modelsItem->rowCount());\n dataItem->removeRows(0, dataItem->rowCount());\n checkersItem->removeRows(0, checkersItem->rowCount());\n otherItem->removeRows(0, otherItem->rowCount());\n entries.clear();\n setModified(true);\n}\n\nQStringList Project::files(void) const {\n return entries.keys();\n}\n\nQStringList Project::modelFiles(void) const {\n return getFiles(NodeType::Model);\n}\n\nQStringList Project::solverConfigurationFiles(void) const {\n return getFiles(NodeType::SolverConfig);\n}\n\nQStringList Project::dataFiles(void) const {\n return getFiles(NodeType::Data);\n}\n\nbool Project::contains(const QString &fileName)\n{\n QFileInfo fi(fileName);\n return entries.contains(fi.absoluteFilePath());\n}\n\nvoid Project::setModified(bool m)\n{\n modified = m;\n auto label = rootItem->data(Role::OriginalLabel).toString();\n if (modified) {\n rootItem->setText(label + \" *\");\n } else {\n rootItem->setText(label);\n }\n}\n\nvoid Project::projectFile(const QString& fileName)\n{\n QStringList files = entries.keys();\n clear();\n if (fileName.isEmpty()) {\n rootItem->setText(\"Untitled Project\");\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n projFile = \"\";\n } else {\n QFileInfo fi(fileName);\n projFile = fi.absoluteFilePath();\n rootItem->setText(fi.fileName());\n rootItem->setData(fi.fileName(), Role::OriginalLabel);\n }\n add(files);\n}\n\nQDir Project::rootDir()\n{\n QFileInfo fi(projectFile());\n return QDir(fi.absolutePath());\n}\n\nbool Project::hasProjectFile()\n{\n return !projectFile().isEmpty();\n}\n\nProject::NodeType Project::getType(const QModelIndex& index)\n{\n return static_cast(model()->data(index, Role::Type).toInt());\n}\n\nQString Project::getFileName(const QModelIndex& index)\n{\n return model()->data(index, Role::Path).toString();\n}\n\nQStringList Project::getFileNames(const QModelIndexList& indices)\n{\n QStringList result;\n for (auto& index : indices) {\n result << getFileName(index);\n }\n return result;\n}\n\nQStringList Project::getFiles(NodeType type) const\n{\n QStringList ret;\n for (auto it = entries.begin(); it != entries.end(); it++) {\n auto t = static_cast(it.value()->data(Role::Type).toInt());\n if (t == type) {\n ret << it.key();\n }\n }\n return ret;\n}\n\nQString Project::relativeToProject(const QString& fileName)\n{\n QFileInfo fi(fileName);\n auto abs = fi.absoluteFilePath();\n return hasProjectFile() ? rootDir().relativeFilePath(abs) : abs;\n}\n\nvoid Project::openTabsChanged(const QStringList& files, int currentTab)\n{\n openTabs.clear();\n for (auto& file : files) {\n auto abs = QFileInfo(file).absoluteFilePath();\n if (contains(abs)) {\n openTabs << abs;\n }\n }\n\n if (currentTab >= 0) {\n openTabIndex = openTabs.indexOf(QFileInfo(files[currentTab]).absoluteFilePath());\n } else {\n openTabIndex = -1;\n }\n\n\/\/ setModified(true);\n}\n\nvoid Project::activeSolverConfigChanged(const SolverConfiguration* sc)\n{\n if (!sc) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n }\n if (sc->isBuiltin) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = sc->solverDefinition.id;\n selectedBuiltinConfigVersion = sc->solverDefinition.version;\n } else {\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n selectedSolverConfigFile = relativeToProject(sc->paramFile);\n }\n\/\/ setModified(true);\n}\n\nvoid Project::on_itemChanged(QStandardItem* item)\n{\n auto oldPath = item->data(Qt::UserRole + 1).toString();\n auto newName = item->text();\n if (oldPath.isEmpty() || oldPath.endsWith(newName)) {\n return;\n }\n QFileInfo fi(oldPath);\n auto target = fi.path() + \"\/\" + item->text();\n if (QFile::rename(oldPath, target)) {\n remove(oldPath);\n add(target);\n emit fileRenamed(oldPath, target);\n } else {\n item->setText(fi.fileName());\n }\n}\nFix reading of currently selected solver config\/*\n * Author:\n * Guido Tack \n *\n * Copyright:\n * NICTA 2013\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"project.h\"\n#include \"moocsubmission.h\"\n#include \"solverdialog.h\"\n#include \"process.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nProject::Project(const QList& configs, QObject* parent) : QObject(parent), solverConfigs(configs)\n{\n itemModel = new QStandardItemModel(this);\n itemModel->setColumnCount(1);\n\n connect(itemModel, &QStandardItemModel::itemChanged, this, &Project::on_itemChanged);\n\n rootItem = new QStandardItem(QIcon(\":\/images\/mznicon.png\"), \"Untitled Project\");\n rootItem->setData(NodeType::ProjectFile, Role::Type);\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n rootItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n\n auto font = rootItem->font();\n font.setBold(true);\n\n modelsItem = new QStandardItem(\"Models\");\n modelsItem->setData(NodeType::Group, Role::Type);\n modelsItem->setFlags(Qt::NoItemFlags);\n modelsItem->setFont(font);\n\n dataItem = new QStandardItem(\"Data (right click to run)\");\n dataItem->setData(NodeType::Group, Role::Type);\n dataItem->setFlags(Qt::NoItemFlags);\n dataItem->setFont(font);\n\n checkersItem = new QStandardItem(\"Checkers (right click to run)\");\n checkersItem->setData(NodeType::Group, Role::Type);\n checkersItem->setFlags(Qt::NoItemFlags);\n checkersItem->setFont(font);\n\n configsItem = new QStandardItem(\"Solver configurations\");\n configsItem->setData(NodeType::Group, Role::Type);\n configsItem->setFlags(Qt::NoItemFlags);\n configsItem->setFont(font);\n\n otherItem = new QStandardItem(\"Other files\");\n otherItem->setData(NodeType::Group, Role::Type);\n otherItem->setFlags(Qt::NoItemFlags);\n otherItem->setFont(font);\n\n rootItem->appendRow(modelsItem);\n rootItem->appendRow(dataItem);\n rootItem->appendRow(checkersItem);\n rootItem->appendRow(configsItem);\n rootItem->appendRow(otherItem);\n itemModel->appendRow(rootItem);\n}\n\nQStringList Project::loadProject(const QString& file, ConfigWindow* configWindow)\n{\n clear();\n\n projectFile(file);\n\n QStringList warnings;\n\n QFile f(file);\n QFileInfo fi(f);\n if (!f.open(QFile::ReadOnly)) {\n throw FileError(\"Failed to open project file\");\n }\n\n auto doc = QJsonDocument::fromJson(f.readAll());\n\n if (doc.isObject()) {\n loadJSON(doc.object(), fi, configWindow, warnings);\n } else {\n f.reset();\n QDataStream in(&f);\n loadLegacy(in, fi, configWindow, warnings);\n }\n\n f.close();\n\n \/\/ Save these because adding the configs can change them\n auto projectBuiltinConfigId = selectedBuiltinConfigId;\n auto projectBuiltinConfigVersion = selectedBuiltinConfigVersion;\n auto projectselectedSolverConfigFile = selectedSolverConfigFile;\n\n for (auto& sc : solverConfigurationFiles()) {\n configWindow->addConfig(sc);\n }\n\n if (!projectBuiltinConfigId.isEmpty()) {\n int index = configWindow->findBuiltinConfig(projectBuiltinConfigId, projectBuiltinConfigVersion);\n if (index == -1) {\n warnings << \"Could not find solver \" + projectBuiltinConfigId + \"@\" + projectBuiltinConfigVersion;\n } else {\n configWindow->setCurrentIndex(index);\n }\n } else if (!projectselectedSolverConfigFile.isEmpty()) {\n int index = configWindow->findConfigFile(rootDir().absolutePath() + \"\/\" + projectselectedSolverConfigFile);\n configWindow->setCurrentIndex(index);\n }\n\n setModified(false);\n\n return warnings;\n}\n\nvoid Project::loadJSON(const QJsonObject& obj, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n int version = obj[\"version\"].toInt();\n\n QString basePath = fi.absolutePath() + \"\/\";\n\n auto of = obj[\"openFiles\"].toArray();\n for (auto file : of) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n openTabs << path;\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n\n openTabIndex = obj[\"openTab\"].toInt();\n\n QList configs;\n if (obj[\"builtinSolverConfigs\"].isArray()) {\n for (auto config : obj[\"builtinSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver builtin solver config\";\n continue;\n }\n SolverConfiguration* loaded;\n if (version >= 106) {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadJSON(QJsonDocument(config.toObject())));\n } else {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n }\n loaded->isBuiltin = true;\n configs << loaded;\n }\n }\n\n if (obj[\"projectSolverConfigs\"].isArray()) {\n for (auto config : obj[\"projectSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver project solver config\";\n continue;\n }\n auto loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n loaded->modified = true;\n configs << loaded;\n }\n }\n\n configWindow->mergeConfigs(configs);\n\n if (obj[\"selectedBuiltinConfigId\"].isString()) {\n selectedBuiltinConfigId = obj[\"selectedBuiltinConfigId\"].toString();\n selectedBuiltinConfigVersion = obj[\"selectedBuiltinConfigVersion\"].toString();\n selectedSolverConfigFile = \"\";\n\n } else if (obj[\"selectedSolverConfigFile\"].isString()) {\n selectedSolverConfigFile = obj[\"selectedSolverConfigFile\"].toString();\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n } \/*else {\n warnings << \"No selected solver config in project\";\n }*\/\n\n for (auto file : obj[\"projectFiles\"].toArray()) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n add(path);\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n}\n\nvoid Project::loadLegacy(QDataStream& in, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n \/\/ Load old binary format of project\n throw InternalError(\"This project format is no longer supported. Please use MiniZinc IDE version 2.4 to upgrade it.\");\n}\n\nvoid Project::saveProject()\n{\n QJsonObject confObject;\n confObject[\"version\"] = 106;\n\n \/\/ Save the currently open tabs\n QStringList of;\n for (auto& f: openTabs) {\n of << relativeToProject(f);\n }\n confObject[\"openFiles\"] = QJsonArray::fromStringList(of);\n confObject[\"openTab\"] = openTabIndex;\n\n \/\/ Save paths of all project files\n QStringList relativeFilePaths;\n for (auto& file : files()) {\n relativeFilePaths << relativeToProject(file);\n }\n confObject[\"projectFiles\"] = QJsonArray::fromStringList(relativeFilePaths);\n\n \/\/ Save which config is currently selected\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n confObject[\"selectedBuiltinConfigId\"] = selectedBuiltinConfigId;\n confObject[\"selectedBuiltinConfigVersion\"] = selectedBuiltinConfigVersion;\n } else if (!selectedSolverConfigFile.isEmpty()){\n confObject[\"selectedSolverConfigFile\"] = selectedSolverConfigFile;\n }\n\n \/\/ Write project file\n QJsonDocument doc(confObject);\n QFile file(projectFile());\n if (!file.open(QFile::WriteOnly)) {\n throw FileError(\"Failed to write file\");\n }\n file.write(doc.toJson());\n file.close();\n\n setModified(false);\n}\n\nvoid Project::add(const QString& fileName)\n{\n auto abs = QFileInfo(fileName).absoluteFilePath();\n auto path = relativeToProject(fileName);\n if (contains(abs)) {\n return;\n }\n\n auto parts = path.split(\"\/\", QString::SkipEmptyParts); \/\/ Qt always uses \/ as the path separator\n auto file = parts.takeLast();\n\n QStandardItem* node = otherItem;\n QString icon;\n NodeType type = NodeType::Other;\n if (file.endsWith(\".mzc.mzn\") || file.endsWith(\".mzc\")) {\n node = checkersItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Checker;\n } else if (file.endsWith(\".mzn\")) {\n node = modelsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Model;\n } else if (file.endsWith(\".dzn\") || file.endsWith(\".json\")) {\n node = dataItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Data;\n } else if (file.endsWith(\".mpc\")) {\n node = configsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::SolverConfig;\n } else if (file == \"_mooc\" || file == \"_coursera\") {\n if (mooc) {\n delete mooc;\n }\n mooc = new MOOCAssignment(fileName);\n emit moocChanged(mooc);\n }\n\n node->setFlags(Qt::ItemIsEnabled);\n\n \/\/ Traverse existing path items\n int i = 0;\n while (!parts.empty() && i < node->rowCount()) {\n if (getType(node->child(i)->index()) == NodeType::Dir &&\n node->child(i)->text() == parts.first()) {\n parts.pop_front();\n node = node->child(i);\n i = 0;\n } else {\n i++;\n }\n }\n \/\/ Create new path items\n for (auto& part : parts) {\n auto dir = new QStandardItem(QIcon(\":\/icons\/images\/folder.png\"), part);\n dir->setData(NodeType::Dir, Role::Type);\n dir->setFlags(Qt::ItemIsEnabled);\n node->appendRow(dir);\n node->sortChildren(0);\n node = dir;\n }\n \/\/ Add file item\n auto item = new QStandardItem(QIcon(icon), file);\n item->setData(type, Role::Type);\n item->setData(abs, Role::Path);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n node->appendRow(item);\n node->sortChildren(0);\n\n entries.insert(abs, item);\n\n if (!projectFile().isEmpty()) {\n setModified(true);\n }\n}\n\nvoid Project::add(const QStringList& fileNames)\n{\n for (auto& fileName : fileNames) {\n add(fileName);\n }\n}\n\nvoid Project::remove(const QString &fileName)\n{\n auto path = QFileInfo(fileName).absoluteFilePath();\n if (!contains(path)) {\n return;\n }\n\n \/\/ Make sure we also remove any unused dirs\n auto node = entries[path];\n if (node->text() == \"_mooc\" || node->text() == \"_coursera\") {\n delete mooc;\n mooc = nullptr;\n emit moocChanged(mooc);\n }\n while (getType(node->parent()->index()) == NodeType::Dir && node->parent()->rowCount() <= 1) {\n node = node->parent();\n }\n auto parent = node->parent();\n parent->removeRow(node->row());\n if (parent->data(Role::Type) == \"group\" && !parent->hasChildren()) {\n parent->setFlags(Qt::NoItemFlags);\n }\n entries.remove(path);\n\n if (!projectFile().isEmpty()) {\n setModified(true);\n }\n}\n\nvoid Project::remove(const QStringList &fileNames)\n{\n for (auto& fileName : fileNames) {\n remove(fileName);\n }\n}\n\nvoid Project::remove(const QModelIndex& index)\n{\n remove(getFileName(index));\n}\n\nvoid Project::remove(const QModelIndexList& indexes)\n{\n for (auto& index : indexes) {\n remove(index);\n }\n}\n\nvoid Project::clear()\n{\n modelsItem->removeRows(0, modelsItem->rowCount());\n dataItem->removeRows(0, dataItem->rowCount());\n checkersItem->removeRows(0, checkersItem->rowCount());\n otherItem->removeRows(0, otherItem->rowCount());\n entries.clear();\n setModified(true);\n}\n\nQStringList Project::files(void) const {\n return entries.keys();\n}\n\nQStringList Project::modelFiles(void) const {\n return getFiles(NodeType::Model);\n}\n\nQStringList Project::solverConfigurationFiles(void) const {\n return getFiles(NodeType::SolverConfig);\n}\n\nQStringList Project::dataFiles(void) const {\n return getFiles(NodeType::Data);\n}\n\nbool Project::contains(const QString &fileName)\n{\n QFileInfo fi(fileName);\n return entries.contains(fi.absoluteFilePath());\n}\n\nvoid Project::setModified(bool m)\n{\n modified = m;\n auto label = rootItem->data(Role::OriginalLabel).toString();\n if (modified) {\n rootItem->setText(label + \" *\");\n } else {\n rootItem->setText(label);\n }\n}\n\nvoid Project::projectFile(const QString& fileName)\n{\n QStringList files = entries.keys();\n clear();\n if (fileName.isEmpty()) {\n rootItem->setText(\"Untitled Project\");\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n projFile = \"\";\n } else {\n QFileInfo fi(fileName);\n projFile = fi.absoluteFilePath();\n rootItem->setText(fi.fileName());\n rootItem->setData(fi.fileName(), Role::OriginalLabel);\n }\n add(files);\n}\n\nQDir Project::rootDir()\n{\n QFileInfo fi(projectFile());\n return QDir(fi.absolutePath());\n}\n\nbool Project::hasProjectFile()\n{\n return !projectFile().isEmpty();\n}\n\nProject::NodeType Project::getType(const QModelIndex& index)\n{\n return static_cast(model()->data(index, Role::Type).toInt());\n}\n\nQString Project::getFileName(const QModelIndex& index)\n{\n return model()->data(index, Role::Path).toString();\n}\n\nQStringList Project::getFileNames(const QModelIndexList& indices)\n{\n QStringList result;\n for (auto& index : indices) {\n result << getFileName(index);\n }\n return result;\n}\n\nQStringList Project::getFiles(NodeType type) const\n{\n QStringList ret;\n for (auto it = entries.begin(); it != entries.end(); it++) {\n auto t = static_cast(it.value()->data(Role::Type).toInt());\n if (t == type) {\n ret << it.key();\n }\n }\n return ret;\n}\n\nQString Project::relativeToProject(const QString& fileName)\n{\n QFileInfo fi(fileName);\n auto abs = fi.absoluteFilePath();\n return hasProjectFile() ? rootDir().relativeFilePath(abs) : abs;\n}\n\nvoid Project::openTabsChanged(const QStringList& files, int currentTab)\n{\n openTabs.clear();\n for (auto& file : files) {\n auto abs = QFileInfo(file).absoluteFilePath();\n if (contains(abs)) {\n openTabs << abs;\n }\n }\n\n if (currentTab >= 0) {\n openTabIndex = openTabs.indexOf(QFileInfo(files[currentTab]).absoluteFilePath());\n } else {\n openTabIndex = -1;\n }\n\n\/\/ setModified(true);\n}\n\nvoid Project::activeSolverConfigChanged(const SolverConfiguration* sc)\n{\n if (!sc) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n }\n if (sc->isBuiltin) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = sc->solverDefinition.id;\n selectedBuiltinConfigVersion = sc->solverDefinition.version;\n } else {\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n selectedSolverConfigFile = relativeToProject(sc->paramFile);\n }\n\/\/ setModified(true);\n}\n\nvoid Project::on_itemChanged(QStandardItem* item)\n{\n auto oldPath = item->data(Qt::UserRole + 1).toString();\n auto newName = item->text();\n if (oldPath.isEmpty() || oldPath.endsWith(newName)) {\n return;\n }\n QFileInfo fi(oldPath);\n auto target = fi.path() + \"\/\" + item->text();\n if (QFile::rename(oldPath, target)) {\n remove(oldPath);\n add(target);\n emit fileRenamed(oldPath, target);\n } else {\n item->setText(fi.fileName());\n }\n}\n<|endoftext|>"} {"text":"\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n\/\/\/\/@begin includes\n#include \"wx\/bookctrl.h\"\n\/\/\/\/@end includes\n\n#include \"rowsselectiondialog.h\"\n#include \"labelconstructor.h\"\n#include \"gtimeline.h\"\n#include \"window.h\"\n\n\/\/\/\/@begin XPM images\n\/\/\/\/@end XPM images\n\n\/*!\n * RowsSelectionDialog type definition\n *\/\n\nIMPLEMENT_DYNAMIC_CLASS( RowsSelectionDialog, wxPropertySheetDialog )\n\n\n\/*!\n * RowsSelectionDialog event table definition\n *\/\n\nBEGIN_EVENT_TABLE( RowsSelectionDialog, wxPropertySheetDialog )\nEVT_BUTTON( wxID_OK, RowsSelectionDialog::OnOkClick )\nEND_EVENT_TABLE()\n\n\n\/*!\n * RowsSelectionDialog constructors\n *\/\n\nRowsSelectionDialog::RowsSelectionDialog()\n{\n Init();\n}\n\nvoid RowsSelectionDialog::OnSelectAllButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i );\n}\n\n\nvoid RowsSelectionDialog::OnUnselectAllButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i, false );\n}\n\n\nvoid RowsSelectionDialog::OnInvertButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i, !myLevelCheckList->IsChecked( i ) );\n}\n\n\nvoid RowsSelectionDialog::buildPanel( const wxString& title,\n TWindowLevel whichLevel )\n{\n wxPanel *myPanel;\n\n myPanel = new wxPanel( GetBookCtrl(),\n wxID_ANY,\n wxDefaultPosition,\n wxDefaultSize,\n wxSUNKEN_BORDER | wxTAB_TRAVERSAL );\n\n GetBookCtrl()->AddPage( myPanel, title, whichLevel == myTimeline->getLevel() );\n\n wxBoxSizer *panelSizer = new wxBoxSizer( wxVERTICAL );\n wxBoxSizer *buttonsSizer = new wxBoxSizer( wxHORIZONTAL );\n\n myPanel->SetSizer( panelSizer );\n\n \/\/ Add Checklist lines\n wxArrayString choices;\n Trace *myTrace = myTimeline->getTrace();\n for ( size_t row = (size_t)0; row < myTrace->getLevelObjects( whichLevel ); ++row )\n {\n if( myTimeline->getLevel() == CPU )\n choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row + 1,\n whichLevel,\n myTrace ).c_str() ) );\n else\n choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row,\n whichLevel,\n myTrace ).c_str() ) );\n }\n \n vector< TObjectOrder > selectedIndex;\n mySelectedRows->getSelected( selectedIndex, whichLevel );\n wxCheckListBox * auxCheckList = new wxCheckListBox( myPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices );\n levelCheckList.push_back( auxCheckList );\n\n for ( unsigned int i = 0; i < (unsigned int)selectedIndex.size(); ++i )\n auxCheckList->Check( selectedIndex[ i ] );\n\n panelSizer->Add( auxCheckList, 3, wxALL | wxALIGN_CENTER | wxGROW, 5 );\n\n \/\/ Add Buttons\n wxButton *auxButton = new wxButton( myPanel, wxID_ANY, _(\"Select All\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog:: OnSelectAllButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n auxButton = new wxButton( myPanel, wxID_ANY, _(\"Unselect All\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n auxButton = new wxButton( myPanel, wxID_ANY, _(\"Invert\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n \/\/ Build Panel\n panelSizer->Add( buttonsSizer, 0, wxALL | wxALIGN_BOTTOM, 5 );\n}\n\n\nRowsSelectionDialog::RowsSelectionDialog( wxWindow* parent,\n Window *whichTimeline,\n SelectionManagement< TObjectOrder, TWindowLevel > *whichSelectedRows,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size,\n long style )\n{\n myTimeline = whichTimeline;\n mySelectedRows = whichSelectedRows;\n \n Init();\n Create( parent, id, caption, pos, size, style );\n\n TWindowLevel level = myTimeline->getLevel();\n\n if (( level >= SYSTEM ) && ( level <= CPU ))\n {\n minLevel = NODE;\n buildPanel( _(\"Node\"), NODE );\n buildPanel( _(\"CPU\"), CPU );\n }\n else if (( level >= WORKLOAD ) && ( level <= THREAD ))\n {\n minLevel = APPLICATION;\n buildPanel( _(\"Application\"), APPLICATION );\n buildPanel( _(\"Task\"), TASK );\n buildPanel( _(\"Thread\"), THREAD );\n }\n\n LayoutDialog();\n Centre();\n}\n\n\n\/*!\n * RowsSelectionDialog creator\n *\/\n\nbool RowsSelectionDialog::Create( wxWindow* parent,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size,\n long style )\n{\n SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY | wxWS_EX_BLOCK_EVENTS );\n SetSheetStyle( wxPROPSHEET_DEFAULT );\n wxPropertySheetDialog::Create( parent, id, caption, pos, size, style );\n\n CreateButtons( wxOK | wxCANCEL );\n CreateControls();\n LayoutDialog();\n Centre();\n\n return true;\n}\n\n\n\/*!\n * RowsSelectionDialog destructor\n *\/\n\nRowsSelectionDialog::~RowsSelectionDialog()\n{\n for ( vector< wxButton * >::iterator it = selectionButtons.begin(); it != selectionButtons.end(); ++it )\n {\n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, \n wxCommandEventHandler( RowsSelectionDialog::OnSelectAllButtonClicked )); \n ++it; \n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked )); \n ++it; \n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked )); \n }\n}\n\n\n\/*!\n * Member initialisation\n *\/\n\nvoid RowsSelectionDialog::Init()\n{\n}\n\n\n\/*!\n * Control creation for RowsSelectionDialog\n *\/\n\nvoid RowsSelectionDialog::CreateControls()\n{\n}\n\n\n\/*!\n * Should we show tooltips?\n *\/\n\nbool RowsSelectionDialog::ShowToolTips()\n{\n return true;\n}\n\n\/*!\n * Get bitmap resources\n *\/\n\nwxBitmap RowsSelectionDialog::GetBitmapResource( const wxString& name )\n{\n \/\/ Bitmap retrieval\n wxUnusedVar(name);\n return wxNullBitmap;\n}\n\n\/*!\n * Get icon resources\n *\/\n\nwxIcon RowsSelectionDialog::GetIconResource( const wxString& name )\n{\n \/\/ Icon retrieval\n wxUnusedVar(name);\n return wxNullIcon;\n}\n\n\nint RowsSelectionDialog::GetSelections( TWindowLevel whichLevel, wxArrayInt &selections )\n{\n int selected = 0;\n\n for ( unsigned int i = 0; i < levelCheckList[ whichLevel - minLevel ]->GetCount(); ++i )\n {\n if ( levelCheckList[ whichLevel - minLevel ]->IsChecked( i ) )\n {\n ++selected;\n selections.Add( i );\n }\n }\n\n return selected;\n}\n\nvoid RowsSelectionDialog::OnOkClick( wxCommandEvent& event )\n{\n TWindowLevel beginLevel;\n TWindowLevel endLevel;\n\n \/\/ Set range of levels for update loop\n if (( myTimeline->getLevel() >= WORKLOAD ) && ( myTimeline->getLevel() <= THREAD ))\n {\n beginLevel = APPLICATION;\n endLevel = THREAD;\n }\n else\n {\n beginLevel = NODE;\n endLevel = CPU;\n }\n\n \/\/ Loop through levels to update gTimeline\n for ( TWindowLevel whichLevel = beginLevel; whichLevel <= endLevel; whichLevel = TWindowLevel(whichLevel + 1) )\n {\n wxArrayInt selections;\n int numberSelected = GetSelections( whichLevel, selections );\n if ( numberSelected > 0 )\n {\n \/\/ Get new selections for that level\n vector< TObjectOrder > newSelection;\n for ( size_t row = (size_t)0; row < (size_t)numberSelected; row++ )\n {\n newSelection.push_back( (TObjectOrder)selections[ row ] );\n }\n mySelectedRows->setSelected( newSelection,\n myTimeline->getTrace()->getLevelObjects( whichLevel ),\n whichLevel );\n }\n }\n\n if ( TransferDataFromWindow() )\n EndModal( wxID_OK );\n}\n*** empty log message ***\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n\/\/\/\/@begin includes\n#include \"wx\/bookctrl.h\"\n\/\/\/\/@end includes\n\n#include \"rowsselectiondialog.h\"\n#include \"labelconstructor.h\"\n#include \"gtimeline.h\"\n#include \"window.h\"\n\n\/\/\/\/@begin XPM images\n\/\/\/\/@end XPM images\n\n\/*!\n * RowsSelectionDialog type definition\n *\/\n\nIMPLEMENT_DYNAMIC_CLASS( RowsSelectionDialog, wxPropertySheetDialog )\n\n\n\/*!\n * RowsSelectionDialog event table definition\n *\/\n\nBEGIN_EVENT_TABLE( RowsSelectionDialog, wxPropertySheetDialog )\nEVT_BUTTON( wxID_OK, RowsSelectionDialog::OnOkClick )\nEND_EVENT_TABLE()\n\n\n\/*!\n * RowsSelectionDialog constructors\n *\/\n\nRowsSelectionDialog::RowsSelectionDialog()\n{\n Init();\n}\n\nvoid RowsSelectionDialog::OnSelectAllButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i );\n}\n\n\nvoid RowsSelectionDialog::OnUnselectAllButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i, false );\n}\n\n\nvoid RowsSelectionDialog::OnInvertButtonClicked( wxCommandEvent& event )\n{\n wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];\n\n for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )\n myLevelCheckList->Check( i, !myLevelCheckList->IsChecked( i ) );\n}\n\n\nvoid RowsSelectionDialog::buildPanel( const wxString& title,\n TWindowLevel whichLevel )\n{\n wxPanel *myPanel;\n\n myPanel = new wxPanel( GetBookCtrl(),\n wxID_ANY,\n wxDefaultPosition,\n wxDefaultSize,\n wxSUNKEN_BORDER | wxTAB_TRAVERSAL );\n\n GetBookCtrl()->AddPage( myPanel, title, whichLevel == myTimeline->getLevel() );\n\n wxBoxSizer *panelSizer = new wxBoxSizer( wxVERTICAL );\n wxBoxSizer *buttonsSizer = new wxBoxSizer( wxHORIZONTAL );\n\n myPanel->SetSizer( panelSizer );\n\n \/\/ Add Checklist lines\n wxArrayString choices;\n Trace *myTrace = myTimeline->getTrace();\n for ( size_t row = (size_t)0; row < myTrace->getLevelObjects( whichLevel ); ++row )\n {\n if( whichLevel == CPU )\n choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row + 1,\n whichLevel,\n myTrace ).c_str() ) );\n else\n choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row,\n whichLevel,\n myTrace ).c_str() ) );\n }\n \n vector< TObjectOrder > selectedIndex;\n mySelectedRows->getSelected( selectedIndex, whichLevel );\n wxCheckListBox * auxCheckList = new wxCheckListBox( myPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices );\n levelCheckList.push_back( auxCheckList );\n\n for ( unsigned int i = 0; i < (unsigned int)selectedIndex.size(); ++i )\n auxCheckList->Check( selectedIndex[ i ] );\n\n panelSizer->Add( auxCheckList, 3, wxALL | wxALIGN_CENTER | wxGROW, 5 );\n\n \/\/ Add Buttons\n wxButton *auxButton = new wxButton( myPanel, wxID_ANY, _(\"Select All\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog:: OnSelectAllButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n auxButton = new wxButton( myPanel, wxID_ANY, _(\"Unselect All\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n auxButton = new wxButton( myPanel, wxID_ANY, _(\"Invert\") );\n selectionButtons.push_back( auxButton );\n auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ),\n NULL,\n this ); \n buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );\n\n \/\/ Build Panel\n panelSizer->Add( buttonsSizer, 0, wxALL | wxALIGN_BOTTOM, 5 );\n}\n\n\nRowsSelectionDialog::RowsSelectionDialog( wxWindow* parent,\n Window *whichTimeline,\n SelectionManagement< TObjectOrder, TWindowLevel > *whichSelectedRows,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size,\n long style )\n{\n myTimeline = whichTimeline;\n mySelectedRows = whichSelectedRows;\n \n Init();\n Create( parent, id, caption, pos, size, style );\n\n TWindowLevel level = myTimeline->getLevel();\n\n if (( level >= SYSTEM ) && ( level <= CPU ))\n {\n minLevel = NODE;\n buildPanel( _(\"Node\"), NODE );\n buildPanel( _(\"CPU\"), CPU );\n }\n else if (( level >= WORKLOAD ) && ( level <= THREAD ))\n {\n minLevel = APPLICATION;\n buildPanel( _(\"Application\"), APPLICATION );\n buildPanel( _(\"Task\"), TASK );\n buildPanel( _(\"Thread\"), THREAD );\n }\n\n LayoutDialog();\n Centre();\n}\n\n\n\/*!\n * RowsSelectionDialog creator\n *\/\n\nbool RowsSelectionDialog::Create( wxWindow* parent,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size,\n long style )\n{\n SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY | wxWS_EX_BLOCK_EVENTS );\n SetSheetStyle( wxPROPSHEET_DEFAULT );\n wxPropertySheetDialog::Create( parent, id, caption, pos, size, style );\n\n CreateButtons( wxOK | wxCANCEL );\n CreateControls();\n LayoutDialog();\n Centre();\n\n return true;\n}\n\n\n\/*!\n * RowsSelectionDialog destructor\n *\/\n\nRowsSelectionDialog::~RowsSelectionDialog()\n{\n for ( vector< wxButton * >::iterator it = selectionButtons.begin(); it != selectionButtons.end(); ++it )\n {\n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, \n wxCommandEventHandler( RowsSelectionDialog::OnSelectAllButtonClicked )); \n ++it; \n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked )); \n ++it; \n (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,\n wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked )); \n }\n}\n\n\n\/*!\n * Member initialisation\n *\/\n\nvoid RowsSelectionDialog::Init()\n{\n}\n\n\n\/*!\n * Control creation for RowsSelectionDialog\n *\/\n\nvoid RowsSelectionDialog::CreateControls()\n{\n}\n\n\n\/*!\n * Should we show tooltips?\n *\/\n\nbool RowsSelectionDialog::ShowToolTips()\n{\n return true;\n}\n\n\/*!\n * Get bitmap resources\n *\/\n\nwxBitmap RowsSelectionDialog::GetBitmapResource( const wxString& name )\n{\n \/\/ Bitmap retrieval\n wxUnusedVar(name);\n return wxNullBitmap;\n}\n\n\/*!\n * Get icon resources\n *\/\n\nwxIcon RowsSelectionDialog::GetIconResource( const wxString& name )\n{\n \/\/ Icon retrieval\n wxUnusedVar(name);\n return wxNullIcon;\n}\n\n\nint RowsSelectionDialog::GetSelections( TWindowLevel whichLevel, wxArrayInt &selections )\n{\n int selected = 0;\n\n for ( unsigned int i = 0; i < levelCheckList[ whichLevel - minLevel ]->GetCount(); ++i )\n {\n if ( levelCheckList[ whichLevel - minLevel ]->IsChecked( i ) )\n {\n ++selected;\n selections.Add( i );\n }\n }\n\n return selected;\n}\n\nvoid RowsSelectionDialog::OnOkClick( wxCommandEvent& event )\n{\n TWindowLevel beginLevel;\n TWindowLevel endLevel;\n\n \/\/ Set range of levels for update loop\n if (( myTimeline->getLevel() >= WORKLOAD ) && ( myTimeline->getLevel() <= THREAD ))\n {\n beginLevel = APPLICATION;\n endLevel = THREAD;\n }\n else\n {\n beginLevel = NODE;\n endLevel = CPU;\n }\n\n \/\/ Loop through levels to update gTimeline\n for ( TWindowLevel whichLevel = beginLevel; whichLevel <= endLevel; whichLevel = TWindowLevel(whichLevel + 1) )\n {\n wxArrayInt selections;\n int numberSelected = GetSelections( whichLevel, selections );\n if ( numberSelected > 0 )\n {\n \/\/ Get new selections for that level\n vector< TObjectOrder > newSelection;\n for ( size_t row = (size_t)0; row < (size_t)numberSelected; row++ )\n {\n newSelection.push_back( (TObjectOrder)selections[ row ] );\n }\n mySelectedRows->setSelected( newSelection,\n myTimeline->getTrace()->getLevelObjects( whichLevel ),\n whichLevel );\n }\n }\n\n if ( TransferDataFromWindow() )\n EndModal( wxID_OK );\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"application_manager\/commands\/hmi\/activate_app_request.h\"\n#include \"utils\/shared_ptr.h\"\n#include \"smart_objects\/smart_object.h\"\n#include \"application_manager\/commands\/command_impl.h\"\n#include \"commands\/commands_test.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace hmi_commands_test {\nnamespace activate_app_request {\n\nusing ::testing::_;\nnamespace am = ::application_manager;\nnamespace strings = ::application_manager::strings;\nusing am::commands::MessageSharedPtr;\nusing am::commands::ActivateAppRequest;\nusing am::commands::CommandImpl;\n\ntypedef ::utils::SharedPtr ActivateAppRequestPtr;\n\nMATCHER_P(CheckMessage, level, \"\") {\n return level ==\n static_cast(\n (*arg)[strings::msg_params][strings::activate_app_hmi_level]\n .asInt());\n}\n\nnamespace {\nconst uint32_t kAppId = 1u;\nconst uint32_t kCorrelationId = 2u;\n} \/\/ namespace\n\nclass ActivateAppRequestTest : public CommandsTest {\n public:\n MessageSharedPtr CreateMsgParams() {\n MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);\n smart_objects::SmartObject msg_params =\n smart_objects::SmartObject(smart_objects::SmartType_Map);\n msg_params[strings::app_id] = kAppId;\n msg_params[strings::correlation_id] = kCorrelationId;\n (*msg)[strings::msg_params] = msg_params;\n (*msg)[strings::params][strings::app_id] = kAppId;\n (*msg)[strings::params][strings::correlation_id] = kCorrelationId;\n (*msg)[strings::app_id] = kAppId;\n return msg;\n }\n};\n\nTEST_F(ActivateAppRequestTest, Run_SUCCESS) {\n MessageSharedPtr msg = CreateMsgParams();\n\n\/\/ TODO(OKozlov) Invastigate and fix issue with using log\n#ifdef ENABLE_LOG\n (*msg)[strings::msg_params][strings::activate_app_hmi_level] =\n mobile_apis::HMILevel::HMI_FULL;\n#endif\n ActivateAppRequestPtr command(CreateCommand(msg));\n\n EXPECT_CALL(app_mngr_, set_application_id(kCorrelationId, kAppId));\n#ifdef ENABLE_LOG\n EXPECT_CALL(app_mngr_,\n SendMessageToHMI(CheckMessage(mobile_apis::HMILevel::HMI_FULL)));\n#else\n EXPECT_CALL(app_mngr_,\n SendMessageToHMI(msg)));\n#endif\n command->Run();\n\n#ifndef ENABLE_LOG\n EXPECT_EQ(CommandImpl::hmi_protocol_type_,\n (*msg)[strings::params][strings::protocol_type].asInt());\n EXPECT_EQ(CommandImpl::protocol_version_,\n (*msg)[strings::params][strings::protocol_version].asInt());\n#endif\n}\n\n} \/\/ namespace activate_app_request\n} \/\/ namespace hmi_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\nFix UT for activate_app_request\/*\n * Copyright (c) 2016, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"application_manager\/commands\/hmi\/activate_app_request.h\"\n#include \"utils\/shared_ptr.h\"\n#include \"smart_objects\/smart_object.h\"\n#include \"application_manager\/commands\/command_impl.h\"\n#include \"commands\/commands_test.h\"\n#include \"application_manager\/mock_application.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace hmi_commands_test {\nnamespace activate_app_request {\n\nusing ::testing::_;\nusing ::utils::SharedPtr;\nnamespace am = ::application_manager;\nnamespace strings = ::application_manager::strings;\nusing am::commands::MessageSharedPtr;\nusing am::commands::ActivateAppRequest;\nusing am::commands::CommandImpl;\n\nusing ::test::components::application_manager_test::MockApplication;\n\ntypedef SharedPtr MockAppPtr;\ntypedef ::utils::SharedPtr ActivateAppRequestPtr;\n\nMATCHER_P(CheckMessage, level, \"\") {\n return level ==\n static_cast(\n (*arg)[strings::msg_params][strings::activate_app_hmi_level]\n .asInt());\n}\n\nnamespace {\nconst uint32_t kAppId = 1u;\nconst uint32_t kCorrelationId = 2u;\n} \/\/ namespace\n\nclass ActivateAppRequestTest : public CommandsTest {\n public:\n MessageSharedPtr CreateMsgParams() {\n MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);\n smart_objects::SmartObject msg_params =\n smart_objects::SmartObject(smart_objects::SmartType_Map);\n msg_params[strings::app_id] = kAppId;\n msg_params[strings::correlation_id] = kCorrelationId;\n (*msg)[strings::msg_params] = msg_params;\n (*msg)[strings::params][strings::app_id] = kAppId;\n (*msg)[strings::params][strings::correlation_id] = kCorrelationId;\n (*msg)[strings::app_id] = kAppId;\n return msg;\n }\n};\n\nTEST_F(ActivateAppRequestTest, Run_SUCCESS) {\n MessageSharedPtr msg = CreateMsgParams();\n MockAppPtr app = CreateMockApp();\n\n EXPECT_CALL(app_mngr_, application(_)).WillRepeatedly(Return(app));\n\n ON_CALL(*app, hmi_app_id()).WillByDefault(Return(kAppId));\n\n\/\/ TODO(OKozlov) Investigate and fix issue with using log\n#ifdef ENABLE_LOG\n (*msg)[strings::msg_params][strings::activate_app_hmi_level] =\n mobile_apis::HMILevel::HMI_FULL;\n#endif\n ActivateAppRequestPtr command(CreateCommand(msg));\n\n EXPECT_CALL(app_mngr_, set_application_id(kCorrelationId, kAppId));\n#ifdef ENABLE_LOG\n EXPECT_CALL(app_mngr_,\n SendMessageToHMI(CheckMessage(mobile_apis::HMILevel::HMI_FULL)));\n#else\n EXPECT_CALL(app_mngr_,\n SendMessageToHMI(msg)));\n#endif\n command->Run();\n\n#ifndef ENABLE_LOG\n EXPECT_EQ(CommandImpl::hmi_protocol_type_,\n (*msg)[strings::params][strings::protocol_type].asInt());\n EXPECT_EQ(CommandImpl::protocol_version_,\n (*msg)[strings::params][strings::protocol_version].asInt());\n#endif\n}\n\n} \/\/ namespace activate_app_request\n} \/\/ namespace hmi_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\n<|endoftext|>"} {"text":"\/*!\n \\class QGraphicsSceneLinearIndex\n \\brief The QGraphicsSceneLinearIndex class provides an implementation of\n a linear indexing algorithm for discovering items in QGraphicsScene.\n \\since 4.6\n \\ingroup multimedia\n \\ingroup graphicsview-api\n \\mainclass\n \\internal\n\n QGraphicsSceneLinearIndex index is default linear implementation to discover items.\n It basically store all items in a list and return them to the scene.\n\n \\sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex, QGraphicsSceneBspTreeIndex\n*\/\n\n#include \n\n\/*!\n \\fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):\n\n Construct a linear index for the given \\a scene.\n*\/\n\n\/*!\n \\fn QList QGraphicsSceneLinearIndex::items(Qt::SortOrder order = Qt::AscendingOrder) const;\n\n Return all items in the index and sort them using \\a order.\n*\/\n\n\n\/*!\n \\fn virtual QList QGraphicsSceneLinearIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const;\n\n Returns an estimation visible items that are either inside or\n intersect with the specified \\a rect and return a list sorted using \\a order.\n*\/\n\n\/*!\n \\fn QRectF QGraphicsSceneLinearIndex::indexedRect() const;\n \\reimp\n Return the rect indexed by the the index.\n*\/\n\n\/*!\n \\fn void QGraphicsSceneLinearIndex::clear();\n \\reimp\n Clear the all the BSP index.\n*\/\n\n\/*!\n \\fn virtual void QGraphicsSceneLinearIndex::addItem(QGraphicsItem *item);\n\n Add the \\a item into the index.\n*\/\n\n\/*!\n \\fn virtual void QGraphicsSceneLinearIndex::removeItem(QGraphicsItem *item);\n\n Add the \\a item from the index.\n*\/\n\nWith license it's better.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/*!\n \\class QGraphicsSceneLinearIndex\n \\brief The QGraphicsSceneLinearIndex class provides an implementation of\n a linear indexing algorithm for discovering items in QGraphicsScene.\n \\since 4.6\n \\ingroup multimedia\n \\ingroup graphicsview-api\n \\mainclass\n \\internal\n\n QGraphicsSceneLinearIndex index is default linear implementation to discover items.\n It basically store all items in a list and return them to the scene.\n\n \\sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex, QGraphicsSceneBspTreeIndex\n*\/\n\n#include \n\n\/*!\n \\fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):\n\n Construct a linear index for the given \\a scene.\n*\/\n\n\/*!\n \\fn QList QGraphicsSceneLinearIndex::items(Qt::SortOrder order = Qt::AscendingOrder) const;\n\n Return all items in the index and sort them using \\a order.\n*\/\n\n\n\/*!\n \\fn virtual QList QGraphicsSceneLinearIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const;\n\n Returns an estimation visible items that are either inside or\n intersect with the specified \\a rect and return a list sorted using \\a order.\n*\/\n\n\/*!\n \\fn QRectF QGraphicsSceneLinearIndex::indexedRect() const;\n \\reimp\n Return the rect indexed by the the index.\n*\/\n\n\/*!\n \\fn void QGraphicsSceneLinearIndex::clear();\n \\reimp\n Clear the all the BSP index.\n*\/\n\n\/*!\n \\fn virtual void QGraphicsSceneLinearIndex::addItem(QGraphicsItem *item);\n\n Add the \\a item into the index.\n*\/\n\n\/*!\n \\fn virtual void QGraphicsSceneLinearIndex::removeItem(QGraphicsItem *item);\n\n Add the \\a item from the index.\n*\/\n\n<|endoftext|>"} {"text":"#include \"master.hpp\"\n\nnamespace factor\n{\n\nTHREADHANDLE start_thread(void *(*start_routine)(void *),void *args)\n{\n\tpthread_attr_t attr;\n\tpthread_t thread;\n\tif (pthread_attr_init (&attr) != 0)\n\t\tfatal_error(\"pthread_attr_init() failed\",0);\n\tif (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)\n\t\tfatal_error(\"pthread_attr_setdetachstate() failed\",0);\n\tif (pthread_create (&thread, &attr, start_routine, args) != 0)\n\t\tfatal_error(\"pthread_create() failed\",0);\n\tpthread_attr_destroy(&attr);\n\treturn thread;\n}\n\nstatic void *null_dll;\n\nvoid sleep_nanos(u64 nsec)\n{\n\ttimespec ts;\n\ttimespec ts_rem;\n\tint ret;\n\tts.tv_sec = nsec \/ 1000000000;\n\tts.tv_nsec = nsec % 1000000000;\n\tret = nanosleep(&ts,&ts_rem);\n\twhile(ret == -1 && errno == EINTR)\n\t{\n\t\tmemcpy(&ts, &ts_rem, sizeof(ts));\n\t\tret = nanosleep(&ts, &ts_rem);\n\t}\n\n\tif(ret == -1)\n\t\tfatal_error(\"nanosleep failed\", 0);\n}\n\nvoid factor_vm::init_ffi()\n{\n\tnull_dll = dlopen(NULL,RTLD_LAZY);\n}\n\nvoid factor_vm::ffi_dlopen(dll *dll)\n{\n\tdll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);\n}\n\nvoid *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)\n{\n\tvoid *handle = (dll == NULL ? null_dll : dll->handle);\n\treturn dlsym(handle,symbol);\n}\n\nvoid factor_vm::ffi_dlclose(dll *dll)\n{\n\tif(dlclose(dll->handle))\n\t\tgeneral_error(ERROR_FFI,false_object,false_object);\n\tdll->handle = NULL;\n}\n\nvoid factor_vm::primitive_existsp()\n{\n\tstruct stat sb;\n\tchar *path = (char *)(untag_check(ctx->pop()) + 1);\n\tctx->push(tag_boolean(stat(path,&sb) >= 0));\n}\n\nvoid factor_vm::move_file(const vm_char *path1, const vm_char *path2)\n{\n\tint ret = 0;\n\tdo\n\t{\n\t\tret = rename((path1),(path2));\n\t}\n\twhile(ret < 0 && errno == EINTR);\n\n\tif(ret < 0)\n\t\tgeneral_error(ERROR_IO,tag_fixnum(errno),false_object);\n}\n\nsegment::segment(cell size_, bool executable_p)\n{\n\tsize = size_;\n\n\tint pagesize = getpagesize();\n\n\tint prot;\n\tif(executable_p)\n\t\tprot = (PROT_READ | PROT_WRITE | PROT_EXEC);\n\telse\n\t\tprot = (PROT_READ | PROT_WRITE);\n\n\tchar *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);\n\tif(array == (char*)-1) out_of_memory();\n\n\tif(mprotect(array,pagesize,PROT_NONE) == -1)\n\t\tfatal_error(\"Cannot protect low guard page\",(cell)array);\n\n\tif(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)\n\t\tfatal_error(\"Cannot protect high guard page\",(cell)array);\n\n\tstart = (cell)(array + pagesize);\n\tend = start + size;\n}\n\nsegment::~segment()\n{\n\tint pagesize = getpagesize();\n\tint retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);\n\tif(retval)\n\t\tfatal_error(\"Segment deallocation failed\",0);\n}\n\nvoid factor_vm::dispatch_signal(void *uap, void (handler)())\n{\n\tUAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));\n\tUAP_PROGRAM_COUNTER(uap) = (cell)handler;\n\n\tctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);\n}\n\nvoid memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_fault_addr = (cell)siginfo->si_addr;\n\tvm->dispatch_signal(uap,factor::memory_signal_handler_impl);\n}\n\nvoid misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_number = signal;\n\tvm->dispatch_signal(uap,factor::misc_signal_handler_impl);\n}\n\nvoid ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n}\n\nvoid fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_number = signal;\n\tvm->signal_fpu_status = fpu_status(uap_fpu_status(uap));\n\tuap_clear_fpu_status(uap);\n\n\tvm->dispatch_signal(uap,\n\t\t(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)\n\t\t? factor::misc_signal_handler_impl\n\t\t: factor::fp_signal_handler_impl);\n}\n\nstatic void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)\n{\n\tint ret;\n\tdo\n\t{\n\t\tret = sigaction(signum, act, oldact);\n\t}\n\twhile(ret == -1 && errno == EINTR);\n\n\tif(ret == -1)\n\t\tfatal_error(\"sigaction failed\", 0);\n}\n\nvoid factor_vm::unix_init_signals()\n{\n\t\/* OpenBSD doesn't support sigaltstack() if we link against\n\tlibpthread. See http:\/\/redmine.ruby-lang.org\/issues\/show\/1239 *\/\n\n#ifndef __OpenBSD__\n\tsignal_callstack_seg = new segment(callstack_size,false);\n\n\tstack_t signal_callstack;\n\tsignal_callstack.ss_sp = (char *)signal_callstack_seg->start;\n\tsignal_callstack.ss_size = signal_callstack_seg->size;\n\tsignal_callstack.ss_flags = 0;\n\n\tif(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)\n\t\tfatal_error(\"sigaltstack() failed\",0);\n#endif\n\n\tstruct sigaction memory_sigaction;\n\tstruct sigaction misc_sigaction;\n\tstruct sigaction fpe_sigaction;\n\tstruct sigaction ignore_sigaction;\n\n\tmemset(&memory_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&memory_sigaction.sa_mask);\n\tmemory_sigaction.sa_sigaction = memory_signal_handler;\n\tmemory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGBUS,&memory_sigaction,NULL);\n\tsigaction_safe(SIGSEGV,&memory_sigaction,NULL);\n\n\tmemset(&fpe_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&fpe_sigaction.sa_mask);\n\tfpe_sigaction.sa_sigaction = fpe_signal_handler;\n\tfpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGFPE,&fpe_sigaction,NULL);\n\n\tmemset(&misc_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&misc_sigaction.sa_mask);\n\tmisc_sigaction.sa_sigaction = misc_signal_handler;\n\tmisc_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGQUIT,&misc_sigaction,NULL);\n\tsigaction_safe(SIGILL,&misc_sigaction,NULL);\n\n\t\/* We don't use SA_IGN here because then the ignore action is inherited\n\tby subprocesses, which we don't want. There is a unit test in\n\tio.launcher.unix for this. *\/\n\tmemset(&ignore_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&ignore_sigaction.sa_mask);\n\tignore_sigaction.sa_sigaction = ignore_signal_handler;\n\tignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\tsigaction_safe(SIGPIPE,&ignore_sigaction,NULL);\n}\n\n\/* On Unix, shared fds such as stdin cannot be set to non-blocking mode\n(http:\/\/homepages.tesco.net\/J.deBoynePollard\/FGA\/dont-set-shared-file-descriptors-to-non-blocking-mode.html)\nso we kludge around this by spawning a thread, which waits on a control pipe\nfor a signal, upon receiving this signal it reads one block of data from stdin\nand writes it to a data pipe. Upon completion, it writes a 4-byte integer to\nthe size pipe, indicating how much data was written to the data pipe.\n\nThe read end of the size pipe can be set to non-blocking. *\/\nextern \"C\" {\n\tint stdin_read;\n\tint stdin_write;\n\n\tint control_read;\n\tint control_write;\n\n\tint size_read;\n\tint size_write;\n}\n\nvoid safe_close(int fd)\n{\n\tif(close(fd) < 0)\n\t\tfatal_error(\"error closing fd\",errno);\n}\n\nbool check_write(int fd, void *data, ssize_t size)\n{\n\tif(write(fd,data,size) == size)\n\t\treturn true;\n\telse\n\t{\n\t\tif(errno == EINTR)\n\t\t\treturn check_write(fd,data,size);\n\t\telse\n\t\t\treturn false;\n\t}\n}\n\nvoid safe_write(int fd, void *data, ssize_t size)\n{\n\tif(!check_write(fd,data,size))\n\t\tfatal_error(\"error writing fd\",errno);\n}\n\nbool safe_read(int fd, void *data, ssize_t size)\n{\n\tssize_t bytes = read(fd,data,size);\n\tif(bytes < 0)\n\t{\n\t\tif(errno == EINTR)\n\t\t\treturn safe_read(fd,data,size);\n\t\telse\n\t\t{\n\t\t\tfatal_error(\"error reading fd\",errno);\n\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t\treturn (bytes == size);\n}\n\nvoid *stdin_loop(void *arg)\n{\n\tunsigned char buf[4096];\n\tbool loop_running = true;\n\n\twhile(loop_running)\n\t{\n\t\tif(!safe_read(control_read,buf,1))\n\t\t\tbreak;\n\n\t\tif(buf[0] != 'X')\n\t\t\tfatal_error(\"stdin_loop: bad data on control fd\",buf[0]);\n\n\t\tfor(;;)\n\t\t{\n\t\t\tssize_t bytes = read(0,buf,sizeof(buf));\n\t\t\tif(bytes < 0)\n\t\t\t{\n\t\t\t\tif(errno == EINTR)\n\t\t\t\t\tcontinue;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tloop_running = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(bytes >= 0)\n\t\t\t{\n\t\t\t\tsafe_write(size_write,&bytes,sizeof(bytes));\n\n\t\t\t\tif(!check_write(stdin_write,buf,bytes))\n\t\t\t\t\tloop_running = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tsafe_close(stdin_write);\n\tsafe_close(control_read);\n\n\treturn NULL;\n}\n\nvoid safe_pipe(int *in, int *out)\n{\n\tint filedes[2];\n\n\tif(pipe(filedes) < 0)\n\t\tfatal_error(\"Error opening pipe\",errno);\n\n\t*in = filedes[0];\n\t*out = filedes[1];\n\n\tif(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)\n\t\tfatal_error(\"Error with fcntl\",errno);\n\n\tif(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)\n\t\tfatal_error(\"Error with fcntl\",errno);\n}\n\nvoid open_console()\n{\n\tsafe_pipe(&control_read,&control_write);\n\tsafe_pipe(&size_read,&size_write);\n\tsafe_pipe(&stdin_read,&stdin_write);\n\tstart_thread(stdin_loop,NULL);\n}\n\nVM_C_API void wait_for_stdin()\n{\n\tif(write(control_write,\"X\",1) != 1)\n\t{\n\t\tif(errno == EINTR)\n\t\t\twait_for_stdin();\n\t\telse\n\t\t\tfatal_error(\"Error writing control fd\",errno);\n\t}\n}\n\n}\nvm\/os-unix.cpp: remove dead code#include \"master.hpp\"\n\nnamespace factor\n{\n\nTHREADHANDLE start_thread(void *(*start_routine)(void *),void *args)\n{\n\tpthread_attr_t attr;\n\tpthread_t thread;\n\tif (pthread_attr_init (&attr) != 0)\n\t\tfatal_error(\"pthread_attr_init() failed\",0);\n\tif (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)\n\t\tfatal_error(\"pthread_attr_setdetachstate() failed\",0);\n\tif (pthread_create (&thread, &attr, start_routine, args) != 0)\n\t\tfatal_error(\"pthread_create() failed\",0);\n\tpthread_attr_destroy(&attr);\n\treturn thread;\n}\n\nstatic void *null_dll;\n\nvoid sleep_nanos(u64 nsec)\n{\n\ttimespec ts;\n\ttimespec ts_rem;\n\tint ret;\n\tts.tv_sec = nsec \/ 1000000000;\n\tts.tv_nsec = nsec % 1000000000;\n\tret = nanosleep(&ts,&ts_rem);\n\twhile(ret == -1 && errno == EINTR)\n\t{\n\t\tmemcpy(&ts, &ts_rem, sizeof(ts));\n\t\tret = nanosleep(&ts, &ts_rem);\n\t}\n\n\tif(ret == -1)\n\t\tfatal_error(\"nanosleep failed\", 0);\n}\n\nvoid factor_vm::init_ffi()\n{\n\tnull_dll = dlopen(NULL,RTLD_LAZY);\n}\n\nvoid factor_vm::ffi_dlopen(dll *dll)\n{\n\tdll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);\n}\n\nvoid *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)\n{\n\tvoid *handle = (dll == NULL ? null_dll : dll->handle);\n\treturn dlsym(handle,symbol);\n}\n\nvoid factor_vm::ffi_dlclose(dll *dll)\n{\n\tif(dlclose(dll->handle))\n\t\tgeneral_error(ERROR_FFI,false_object,false_object);\n\tdll->handle = NULL;\n}\n\nvoid factor_vm::primitive_existsp()\n{\n\tstruct stat sb;\n\tchar *path = (char *)(untag_check(ctx->pop()) + 1);\n\tctx->push(tag_boolean(stat(path,&sb) >= 0));\n}\n\nvoid factor_vm::move_file(const vm_char *path1, const vm_char *path2)\n{\n\tint ret = 0;\n\tdo\n\t{\n\t\tret = rename((path1),(path2));\n\t}\n\twhile(ret < 0 && errno == EINTR);\n\n\tif(ret < 0)\n\t\tgeneral_error(ERROR_IO,tag_fixnum(errno),false_object);\n}\n\nsegment::segment(cell size_, bool executable_p)\n{\n\tsize = size_;\n\n\tint pagesize = getpagesize();\n\n\tint prot;\n\tif(executable_p)\n\t\tprot = (PROT_READ | PROT_WRITE | PROT_EXEC);\n\telse\n\t\tprot = (PROT_READ | PROT_WRITE);\n\n\tchar *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);\n\tif(array == (char*)-1) out_of_memory();\n\n\tif(mprotect(array,pagesize,PROT_NONE) == -1)\n\t\tfatal_error(\"Cannot protect low guard page\",(cell)array);\n\n\tif(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)\n\t\tfatal_error(\"Cannot protect high guard page\",(cell)array);\n\n\tstart = (cell)(array + pagesize);\n\tend = start + size;\n}\n\nsegment::~segment()\n{\n\tint pagesize = getpagesize();\n\tint retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);\n\tif(retval)\n\t\tfatal_error(\"Segment deallocation failed\",0);\n}\n\nvoid factor_vm::dispatch_signal(void *uap, void (handler)())\n{\n\tUAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));\n\tUAP_PROGRAM_COUNTER(uap) = (cell)handler;\n\n\tctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);\n}\n\nvoid memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_fault_addr = (cell)siginfo->si_addr;\n\tvm->dispatch_signal(uap,factor::memory_signal_handler_impl);\n}\n\nvoid misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_number = signal;\n\tvm->dispatch_signal(uap,factor::misc_signal_handler_impl);\n}\n\nvoid ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n}\n\nvoid fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)\n{\n\tfactor_vm *vm = current_vm();\n\tvm->signal_number = signal;\n\tvm->signal_fpu_status = fpu_status(uap_fpu_status(uap));\n\tuap_clear_fpu_status(uap);\n\n\tvm->dispatch_signal(uap,\n\t\t(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)\n\t\t? factor::misc_signal_handler_impl\n\t\t: factor::fp_signal_handler_impl);\n}\n\nstatic void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)\n{\n\tint ret;\n\tdo\n\t{\n\t\tret = sigaction(signum, act, oldact);\n\t}\n\twhile(ret == -1 && errno == EINTR);\n\n\tif(ret == -1)\n\t\tfatal_error(\"sigaction failed\", 0);\n}\n\nvoid factor_vm::unix_init_signals()\n{\n\t\/* OpenBSD doesn't support sigaltstack() if we link against\n\tlibpthread. See http:\/\/redmine.ruby-lang.org\/issues\/show\/1239 *\/\n\n#ifndef __OpenBSD__\n\tsignal_callstack_seg = new segment(callstack_size,false);\n\n\tstack_t signal_callstack;\n\tsignal_callstack.ss_sp = (char *)signal_callstack_seg->start;\n\tsignal_callstack.ss_size = signal_callstack_seg->size;\n\tsignal_callstack.ss_flags = 0;\n\n\tif(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)\n\t\tfatal_error(\"sigaltstack() failed\",0);\n#endif\n\n\tstruct sigaction memory_sigaction;\n\tstruct sigaction misc_sigaction;\n\tstruct sigaction fpe_sigaction;\n\tstruct sigaction ignore_sigaction;\n\n\tmemset(&memory_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&memory_sigaction.sa_mask);\n\tmemory_sigaction.sa_sigaction = memory_signal_handler;\n\tmemory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGBUS,&memory_sigaction,NULL);\n\tsigaction_safe(SIGSEGV,&memory_sigaction,NULL);\n\n\tmemset(&fpe_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&fpe_sigaction.sa_mask);\n\tfpe_sigaction.sa_sigaction = fpe_signal_handler;\n\tfpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGFPE,&fpe_sigaction,NULL);\n\n\tmemset(&misc_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&misc_sigaction.sa_mask);\n\tmisc_sigaction.sa_sigaction = misc_signal_handler;\n\tmisc_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\n\tsigaction_safe(SIGQUIT,&misc_sigaction,NULL);\n\tsigaction_safe(SIGILL,&misc_sigaction,NULL);\n\n\t\/* We don't use SA_IGN here because then the ignore action is inherited\n\tby subprocesses, which we don't want. There is a unit test in\n\tio.launcher.unix for this. *\/\n\tmemset(&ignore_sigaction,0,sizeof(struct sigaction));\n\tsigemptyset(&ignore_sigaction.sa_mask);\n\tignore_sigaction.sa_sigaction = ignore_signal_handler;\n\tignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;\n\tsigaction_safe(SIGPIPE,&ignore_sigaction,NULL);\n}\n\n\/* On Unix, shared fds such as stdin cannot be set to non-blocking mode\n(http:\/\/homepages.tesco.net\/J.deBoynePollard\/FGA\/dont-set-shared-file-descriptors-to-non-blocking-mode.html)\nso we kludge around this by spawning a thread, which waits on a control pipe\nfor a signal, upon receiving this signal it reads one block of data from stdin\nand writes it to a data pipe. Upon completion, it writes a 4-byte integer to\nthe size pipe, indicating how much data was written to the data pipe.\n\nThe read end of the size pipe can be set to non-blocking. *\/\nextern \"C\" {\n\tint stdin_read;\n\tint stdin_write;\n\n\tint control_read;\n\tint control_write;\n\n\tint size_read;\n\tint size_write;\n}\n\nvoid safe_close(int fd)\n{\n\tif(close(fd) < 0)\n\t\tfatal_error(\"error closing fd\",errno);\n}\n\nbool check_write(int fd, void *data, ssize_t size)\n{\n\tif(write(fd,data,size) == size)\n\t\treturn true;\n\telse\n\t{\n\t\tif(errno == EINTR)\n\t\t\treturn check_write(fd,data,size);\n\t\telse\n\t\t\treturn false;\n\t}\n}\n\nvoid safe_write(int fd, void *data, ssize_t size)\n{\n\tif(!check_write(fd,data,size))\n\t\tfatal_error(\"error writing fd\",errno);\n}\n\nbool safe_read(int fd, void *data, ssize_t size)\n{\n\tssize_t bytes = read(fd,data,size);\n\tif(bytes < 0)\n\t{\n\t\tif(errno == EINTR)\n\t\t\treturn safe_read(fd,data,size);\n\t\telse\n\t\t{\n\t\t\tfatal_error(\"error reading fd\",errno);\n\t\t\treturn false;\n\t\t}\n\t}\n\telse\n\t\treturn (bytes == size);\n}\n\nvoid *stdin_loop(void *arg)\n{\n\tunsigned char buf[4096];\n\tbool loop_running = true;\n\n\twhile(loop_running)\n\t{\n\t\tif(!safe_read(control_read,buf,1))\n\t\t\tbreak;\n\n\t\tif(buf[0] != 'X')\n\t\t\tfatal_error(\"stdin_loop: bad data on control fd\",buf[0]);\n\n\t\tfor(;;)\n\t\t{\n\t\t\tssize_t bytes = read(0,buf,sizeof(buf));\n\t\t\tif(bytes < 0)\n\t\t\t{\n\t\t\t\tif(errno == EINTR)\n\t\t\t\t\tcontinue;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tloop_running = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(bytes >= 0)\n\t\t\t{\n\t\t\t\tsafe_write(size_write,&bytes,sizeof(bytes));\n\n\t\t\t\tif(!check_write(stdin_write,buf,bytes))\n\t\t\t\t\tloop_running = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tsafe_close(stdin_write);\n\tsafe_close(control_read);\n\n\treturn NULL;\n}\n\nvoid safe_pipe(int *in, int *out)\n{\n\tint filedes[2];\n\n\tif(pipe(filedes) < 0)\n\t\tfatal_error(\"Error opening pipe\",errno);\n\n\t*in = filedes[0];\n\t*out = filedes[1];\n\n\tif(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)\n\t\tfatal_error(\"Error with fcntl\",errno);\n\n\tif(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)\n\t\tfatal_error(\"Error with fcntl\",errno);\n}\n\nvoid open_console()\n{\n\tsafe_pipe(&control_read,&control_write);\n\tsafe_pipe(&size_read,&size_write);\n\tsafe_pipe(&stdin_read,&stdin_write);\n\tstart_thread(stdin_loop,NULL);\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#include \"ElemMessage.hpp\"\n\n\n\n#include \n\n\n\n#include \n\n\n\n#include \"Constants.hpp\"\n#include \"StylesheetConstructionContext.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n\n\n\nElemMessage::ElemMessage(\n\t\t\tStylesheetConstructionContext&\tconstructionContext,\n\t\t\tStylesheet&\t\t\t\t\t\tstylesheetTree,\n\t\t\tconst AttributeList&\t\t\tatts,\n\t\t\tint\t\t\t\t\t\t\t\tlineNumber,\n\t\t\tint\t\t\t\t\t\t\t\tcolumnNumber) :\n\tElemTemplateElement(constructionContext,\n\t\t\t\t\t\tstylesheetTree,\n\t\t\t\t\t\tlineNumber,\n\t\t\t\t\t\tcolumnNumber,\n\t\t\t\t\t\tConstants::ELEMNAME_MESSAGE),\n\tm_terminate(false)\n{\n\tconst unsigned int\tnAttrs = atts.getLength();\n\n\tfor(unsigned int i = 0; i < nAttrs; i++)\n\t{\n\t\tconst XalanDOMChar*\tconst\taname = atts.getName(i);\n\n\t\tif (equals(aname, Constants::ATTRNAME_TERMINATE) == true)\n\t\t{\n\t\t\tconst XalanDOMChar*\tconst\tavalue = atts.getValue(i);\n\n\t\t\tif (equals(avalue, Constants::ATTRVAL_YES) == true)\n\t\t\t{\n\t\t\t\tm_terminate = true;\n\t\t\t}\n\t\t\telse if (equals(avalue, Constants::ATTRVAL_NO) == false)\n\t\t\t{\n\t\t\t\tconstructionContext.error(\n\t\t\t\t\t\"The attribute 'terminate' has an illegal value\",\n\t\t\t\t\t0,\n\t\t\t\t\tthis);\n\t\t\t}\n\t\t}\n\t\telse if(isAttrOK(aname, atts, i, constructionContext) == false ||\n\t\t\t\tprocessSpaceAttr(aname, atts, i, constructionContext))\n\t\t{\n\t\t\tconstructionContext.error(\n\t\t\t\t\"xsl:message has an illegal attribute\",\n\t\t\t\t0,\n\t\t\t\tthis);\n\t\t}\n\t}\n}\n\n\n\nconst XalanDOMString&\nElemMessage::getElementName() const\n{\n\treturn Constants::ELEMNAME_MESSAGE_WITH_PREFIX_STRING;\n}\n\n\n\nvoid\nElemMessage::execute(StylesheetExecutionContext&\t\texecutionContext) const\n{\n\tElemTemplateElement::execute(executionContext);\n\n\tStylesheetExecutionContext::GetAndReleaseCachedString\ttheResult(executionContext);\n\n executionContext.message(\n\t\tchildrenToString(executionContext,theResult.get()),\n\t\texecutionContext.getCurrentNode(),\n\t\tthis);\n\n\tif (m_terminate == true)\n\t{\n\t\tthrow ElemMessageTerminateException(theResult.get());\n\t}\n}\n\n\n\nElemMessage::ElemMessageTerminateException::ElemMessageTerminateException(const XalanDOMString&\t\ttheMessage) :\n\tXSLTProcessorException(theMessage,\n\t\t\t\t\t\t TranscodeFromLocalCodePage(\"ElemMessageTerminateException\"))\n{\n}\n\n\n\nElemMessage::ElemMessageTerminateException::~ElemMessageTerminateException()\n{\n}\nUse Locator for messages.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#include \"ElemMessage.hpp\"\n\n\n\n#include \n\n\n\n#include \n\n\n\n#include \"Constants.hpp\"\n#include \"StylesheetConstructionContext.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n\n\n\nElemMessage::ElemMessage(\n\t\t\tStylesheetConstructionContext&\tconstructionContext,\n\t\t\tStylesheet&\t\t\t\t\t\tstylesheetTree,\n\t\t\tconst AttributeList&\t\t\tatts,\n\t\t\tint\t\t\t\t\t\t\t\tlineNumber,\n\t\t\tint\t\t\t\t\t\t\t\tcolumnNumber) :\n\tElemTemplateElement(constructionContext,\n\t\t\t\t\t\tstylesheetTree,\n\t\t\t\t\t\tlineNumber,\n\t\t\t\t\t\tcolumnNumber,\n\t\t\t\t\t\tConstants::ELEMNAME_MESSAGE),\n\tm_terminate(false)\n{\n\tconst unsigned int\tnAttrs = atts.getLength();\n\n\tfor(unsigned int i = 0; i < nAttrs; i++)\n\t{\n\t\tconst XalanDOMChar*\tconst\taname = atts.getName(i);\n\n\t\tif (equals(aname, Constants::ATTRNAME_TERMINATE) == true)\n\t\t{\n\t\t\tconst XalanDOMChar*\tconst\tavalue = atts.getValue(i);\n\n\t\t\tif (equals(avalue, Constants::ATTRVAL_YES) == true)\n\t\t\t{\n\t\t\t\tm_terminate = true;\n\t\t\t}\n\t\t\telse if (equals(avalue, Constants::ATTRVAL_NO) == false)\n\t\t\t{\n\t\t\t\tconstructionContext.error(\n\t\t\t\t\t\"The attribute 'terminate' has an illegal value\",\n\t\t\t\t\t0,\n\t\t\t\t\tthis);\n\t\t\t}\n\t\t}\n\t\telse if(isAttrOK(aname, atts, i, constructionContext) == false ||\n\t\t\t\tprocessSpaceAttr(aname, atts, i, constructionContext))\n\t\t{\n\t\t\tconstructionContext.error(\n\t\t\t\t\"xsl:message has an illegal attribute\",\n\t\t\t\t0,\n\t\t\t\tthis);\n\t\t}\n\t}\n}\n\n\n\nconst XalanDOMString&\nElemMessage::getElementName() const\n{\n\treturn Constants::ELEMNAME_MESSAGE_WITH_PREFIX_STRING;\n}\n\n\n\nvoid\nElemMessage::execute(StylesheetExecutionContext&\t\texecutionContext) const\n{\n\tElemTemplateElement::execute(executionContext);\n\n\tStylesheetExecutionContext::GetAndReleaseCachedString\ttheResult(executionContext);\n\n executionContext.message(\n\t\tchildrenToString(executionContext,theResult.get()),\n\t\texecutionContext.getCurrentNode(),\n\t\tgetLocator());\n\n\tif (m_terminate == true)\n\t{\n\t\tthrow ElemMessageTerminateException(theResult.get());\n\t}\n}\n\n\n\nElemMessage::ElemMessageTerminateException::ElemMessageTerminateException(const XalanDOMString&\t\ttheMessage) :\n\tXSLTProcessorException(theMessage,\n\t\t\t\t\t\t TranscodeFromLocalCodePage(\"ElemMessageTerminateException\"))\n{\n}\n\n\n\nElemMessage::ElemMessageTerminateException::~ElemMessageTerminateException()\n{\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"blackrock_spire.h\"\n#include \"ScriptedCreature.h\"\n#include \"ScriptMgr.h\"\n\nenum Spells\n{\n SPELL_FLAMESTRIKE = 16419,\n SPELL_CLEAVE = 15284,\n SPELL_CONFLAGRATION = 16805,\n SPELL_THUNDERCLAP = 15548, \/\/Not sure if right ID. 23931 would be a harder possibility.\n SPELL_RAGE = 16789,\n SPELL_PIERCE_ARMOR = 12097\n};\n\nenum Events\n{\n EVENT_FLAMESTRIKE = 1,\n EVENT_CLEAVE,\n EVENT_CONFLAGRATION,\n EVENT_THUNDERCLAP,\n EVENT_PIERCE_ARMOR,\n EVENT_RAGE\n};\n\nenum ChromaticEliteGuardEvents\n{\n EVENT_MORTAL_STRIKE = 1,\n EVENT_KNOCKDOWN = 2,\n EVENT_STRIKE = 3\n};\n\nenum ChromaticEliteGuardSpells\n{\n SPELL_MORTAL_STRIKE = 15708,\n SPELL_KNOCKDOWN = 16790,\n SPELL_STRIKE = 15580\n};\n\nconstexpr uint32 ChromaticEliteGuardEntry = 10814;\nconstexpr uint32 GeneralDrakkisathEntry = 10814;\n\nclass boss_drakkisath : public CreatureScript\n{\npublic:\n boss_drakkisath() : CreatureScript(\"boss_drakkisath\") { }\n\n struct boss_drakkisathAI : public BossAI\n {\n boss_drakkisathAI(Creature* creature) : BossAI(creature, DATA_GENERAL_DRAKKISATH) { }\n\n void Reset() override\n {\n _Reset();\n }\n\n void EnterCombat(Unit* \/*who*\/) override\n {\n _EnterCombat();\n CallForHelp();\n events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);\n events.ScheduleEvent(EVENT_CLEAVE, 8000);\n events.ScheduleEvent(EVENT_CONFLAGRATION, 15000);\n events.ScheduleEvent(EVENT_THUNDERCLAP, 17000);\n events.ScheduleEvent(EVENT_PIERCE_ARMOR, 5000);\n events.ScheduleEvent(EVENT_RAGE, 1000);\n }\n\n \/\/ Will make his two adds engage combat\n void CallForHelp()\n {\n std::list ChromaticEliteGuards;\n me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);\n for (std::list::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(me->GetVictim());\n }\n }\n\n void JustDied(Unit* \/*killer*\/) override\n {\n _JustDied();\n }\n\n void UpdateAI(uint32 diff) override\n {\n if (!UpdateVictim())\n return;\n\n events.Update(diff);\n\n if (me->HasUnitState(UNIT_STATE_CASTING))\n return;\n\n while (uint32 eventId = events.ExecuteEvent())\n {\n switch (eventId)\n {\n case EVENT_FLAMESTRIKE:\n DoCastAOE(SPELL_FLAMESTRIKE);\n events.ScheduleEvent(EVENT_FLAMESTRIKE, 10000);\n break;\n case EVENT_CLEAVE:\n DoCastVictim(SPELL_CLEAVE);\n events.ScheduleEvent(EVENT_CLEAVE, 8000);\n break;\n case EVENT_CONFLAGRATION:\n if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))\n {\n DoCast(target, SPELL_CONFLAGRATION);\n }\n events.ScheduleEvent(EVENT_CONFLAGRATION, 18000);\n break;\n case EVENT_THUNDERCLAP:\n DoCastVictim(SPELL_THUNDERCLAP);\n events.ScheduleEvent(EVENT_THUNDERCLAP, 20000);\n break;\n case EVENT_PIERCE_ARMOR:\n DoCastVictim(SPELL_PIERCE_ARMOR);\n events.ScheduleEvent(EVENT_PIERCE_ARMOR, 40000);\n break;\n case EVENT_RAGE:\n DoCastSelf(SPELL_RAGE);\n events.ScheduleEvent(EVENT_RAGE, 35000);\n break;\n }\n }\n DoMeleeAttackIfReady();\n }\n };\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return GetBlackrockSpireAI(creature);\n }\n};\n\nclass chromatic_elite_guard : public CreatureScript\n{\npublic:\n chromatic_elite_guard() : CreatureScript(\"chromatic_elite_guard\") { }\n\n struct chromatic_elite_guardAI : public ScriptedAI\n {\n chromatic_elite_guardAI(Creature* creature) : ScriptedAI(creature) { }\n\n EventMap _events;\n\n void EnterCombat(Unit* who) override\n {\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(5000, 12800));\n _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(5600, 15400));\n _events.ScheduleEvent(EVENT_STRIKE, urand(12000, 20800));\n\n std::list GeneralDrakkisath;\n me->GetCreaturesWithEntryInRange(GeneralDrakkisath, 15.0f, GeneralDrakkisathEntry);\n for (std::list::const_iterator itr = GeneralDrakkisath.begin(); itr != GeneralDrakkisath.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(who);\n }\n\n std::list ChromaticEliteGuards;\n me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);\n for (std::list::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(who);\n }\n }\n\n void UpdateAI(uint32 diff) override\n {\n if (!UpdateVictim())\n return;\n\n _events.Update(diff);\n\n switch (_events.ExecuteEvent())\n {\n case EVENT_MORTAL_STRIKE:\n DoCastVictim(SPELL_MORTAL_STRIKE);\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 13000);\n break;\n case EVENT_KNOCKDOWN:\n DoCastVictim(SPELL_KNOCKDOWN);\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(11200, 25700));\n break;\n case EVENT_STRIKE:\n DoCastVictim(SPELL_STRIKE);\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 9000);\n break;\n }\n\n DoMeleeAttackIfReady();\n }\n };\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return new chromatic_elite_guardAI(creature);\n }\n};\n\nvoid AddSC_boss_drakkisath()\n{\n new boss_drakkisath();\n new chromatic_elite_guard();\n}\nfix(Scripts\/UBRS): Correct Drakkisath's guard abilities not being cast (#8957)\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n#include \"blackrock_spire.h\"\n#include \"ScriptedCreature.h\"\n#include \"ScriptMgr.h\"\n\nenum Spells\n{\n SPELL_FLAMESTRIKE = 16419,\n SPELL_CLEAVE = 15284,\n SPELL_CONFLAGRATION = 16805,\n SPELL_THUNDERCLAP = 15548, \/\/Not sure if right ID. 23931 would be a harder possibility.\n SPELL_RAGE = 16789,\n SPELL_PIERCE_ARMOR = 12097\n};\n\nenum Events\n{\n EVENT_FLAMESTRIKE = 1,\n EVENT_CLEAVE,\n EVENT_CONFLAGRATION,\n EVENT_THUNDERCLAP,\n EVENT_PIERCE_ARMOR,\n EVENT_RAGE\n};\n\nenum ChromaticEliteGuardEvents\n{\n EVENT_MORTAL_STRIKE = 1,\n EVENT_KNOCKDOWN = 2,\n EVENT_STRIKE = 3\n};\n\nenum ChromaticEliteGuardSpells\n{\n SPELL_MORTAL_STRIKE = 15708,\n SPELL_KNOCKDOWN = 16790,\n SPELL_STRIKE = 15580\n};\n\nconstexpr uint32 ChromaticEliteGuardEntry = 10814;\nconstexpr uint32 GeneralDrakkisathEntry = 10814;\n\nclass boss_drakkisath : public CreatureScript\n{\npublic:\n boss_drakkisath() : CreatureScript(\"boss_drakkisath\") { }\n\n struct boss_drakkisathAI : public BossAI\n {\n boss_drakkisathAI(Creature* creature) : BossAI(creature, DATA_GENERAL_DRAKKISATH) { }\n\n void Reset() override\n {\n _Reset();\n }\n\n void EnterCombat(Unit* \/*who*\/) override\n {\n _EnterCombat();\n CallForHelp();\n events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);\n events.ScheduleEvent(EVENT_CLEAVE, 8000);\n events.ScheduleEvent(EVENT_CONFLAGRATION, 15000);\n events.ScheduleEvent(EVENT_THUNDERCLAP, 17000);\n events.ScheduleEvent(EVENT_PIERCE_ARMOR, 5000);\n events.ScheduleEvent(EVENT_RAGE, 1000);\n }\n\n \/\/ Will make his two adds engage combat\n void CallForHelp()\n {\n std::list ChromaticEliteGuards;\n me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);\n for (std::list::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(me->GetVictim());\n }\n }\n\n void JustDied(Unit* \/*killer*\/) override\n {\n _JustDied();\n }\n\n void UpdateAI(uint32 diff) override\n {\n if (!UpdateVictim())\n return;\n\n events.Update(diff);\n\n if (me->HasUnitState(UNIT_STATE_CASTING))\n return;\n\n while (uint32 eventId = events.ExecuteEvent())\n {\n switch (eventId)\n {\n case EVENT_FLAMESTRIKE:\n DoCastAOE(SPELL_FLAMESTRIKE);\n events.ScheduleEvent(EVENT_FLAMESTRIKE, 10000);\n break;\n case EVENT_CLEAVE:\n DoCastVictim(SPELL_CLEAVE);\n events.ScheduleEvent(EVENT_CLEAVE, 8000);\n break;\n case EVENT_CONFLAGRATION:\n if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))\n {\n DoCast(target, SPELL_CONFLAGRATION);\n }\n events.ScheduleEvent(EVENT_CONFLAGRATION, 18000);\n break;\n case EVENT_THUNDERCLAP:\n DoCastVictim(SPELL_THUNDERCLAP);\n events.ScheduleEvent(EVENT_THUNDERCLAP, 20000);\n break;\n case EVENT_PIERCE_ARMOR:\n DoCastVictim(SPELL_PIERCE_ARMOR);\n events.ScheduleEvent(EVENT_PIERCE_ARMOR, 40000);\n break;\n case EVENT_RAGE:\n DoCastSelf(SPELL_RAGE);\n events.ScheduleEvent(EVENT_RAGE, 35000);\n break;\n }\n }\n DoMeleeAttackIfReady();\n }\n };\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return GetBlackrockSpireAI(creature);\n }\n};\n\nclass chromatic_elite_guard : public CreatureScript\n{\npublic:\n chromatic_elite_guard() : CreatureScript(\"chromatic_elite_guard\") { }\n\n struct chromatic_elite_guardAI : public ScriptedAI\n {\n chromatic_elite_guardAI(Creature* creature) : ScriptedAI(creature) { }\n\n EventMap _events;\n\n void EnterCombat(Unit* who) override\n {\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(5000, 12800));\n _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(5600, 15400));\n _events.ScheduleEvent(EVENT_STRIKE, urand(12000, 20800));\n\n std::list GeneralDrakkisath;\n me->GetCreaturesWithEntryInRange(GeneralDrakkisath, 15.0f, GeneralDrakkisathEntry);\n for (std::list::const_iterator itr = GeneralDrakkisath.begin(); itr != GeneralDrakkisath.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(who);\n }\n\n std::list ChromaticEliteGuards;\n me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);\n for (std::list::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)\n {\n (*itr)->ToCreature()->AI()->AttackStart(who);\n }\n }\n\n void UpdateAI(uint32 diff) override\n {\n if (!UpdateVictim())\n return;\n\n _events.Update(diff);\n\n switch (_events.ExecuteEvent())\n {\n case EVENT_MORTAL_STRIKE:\n DoCastVictim(SPELL_MORTAL_STRIKE);\n _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 13000);\n break;\n case EVENT_KNOCKDOWN:\n DoCastVictim(SPELL_KNOCKDOWN);\n _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(11200, 25700));\n break;\n case EVENT_STRIKE:\n DoCastVictim(SPELL_STRIKE);\n _events.ScheduleEvent(EVENT_STRIKE, 9000);\n break;\n }\n\n DoMeleeAttackIfReady();\n }\n };\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return new chromatic_elite_guardAI(creature);\n }\n};\n\nvoid AddSC_boss_drakkisath()\n{\n new boss_drakkisath();\n new chromatic_elite_guard();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2005 Stefan Seefeld\n\/\/ All rights reserved.\n\/\/ Licensed to the public under the terms of the GNU LGPL (>= 2),\n\/\/ see the file COPYING for details.\n\/\/\n\n#include \"ASGTranslator.hh\"\n#include \"SXRGenerator.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Synopsis;\nnamespace fs = boost::filesystem;\n\nnamespace\n{\nbpl::object error_type;\n\n\/\/. Override unexpected() to print a message before we abort\nvoid unexpected()\n{\n std::cout << \"Warning: Aborting due to unexpected exception.\" << std::endl;\n throw std::bad_exception();\n}\n\nbpl::dict annotations(bpl::object o) \n{ return bpl::extract(o.attr(\"annotations\"));}\n\n\/\/. Merge new files to files already present in the IR.\n\/\/. If a file doesn't exist yet, add it. If it does, \n\/\/. upgrade the 'primary' flag if it is set now.\nvoid merge_files(bpl::dict ir_files, bpl::dict new_files)\n{\n bpl::list keys = new_files.keys();\n for (unsigned i = 0; i != bpl::len(keys); ++i)\n {\n bpl::object filename = keys[i];\n bpl::object file = new_files[filename];\n if (ir_files.has_key(filename))\n {\n if (bpl::extract(annotations(file)[\"primary\"]))\n \tannotations(ir_files[filename])[\"primary\"] = true;\n }\n else\n ir_files[filename] = file;\n }\n}\n\n\nbpl::object parse(bpl::object ir,\n char const *cpp_file, char const *input_file, char const *base_path,\n bool primary_file_only, char const *sxr_prefix,\n\t\t bpl::list cpp_flags,\n bool verbose, bool debug, bool profile)\n{\n std::set_unexpected(unexpected);\n\n \/\/ if (debug) Synopsis::Trace::enable(Trace::TRANSLATION);\n\n if (!input_file || *input_file == '\\0') throw std::runtime_error(\"no input file\");\n\n char const **args = new char const*[bpl::len(cpp_flags) + 2];\n args[0] = \"-x\";\n args[1] = \"c\";\n for (size_t i = 0; i != bpl::len(cpp_flags); ++i)\n args[i + 2] = bpl::extract(cpp_flags[i]);\n\n Timer timer;\n \/\/ first arg: exclude declarations from PCH\n \/\/ second arg: display diagnostics\n CXIndex idx = clang_createIndex(0, 1);\n CXTranslationUnit_Flags flags = CXTranslationUnit_DetailedPreprocessingRecord;\n CXTranslationUnit tu = \n clang_parseTranslationUnit(idx, input_file,\n\t\t\t args,\n\t\t\t bpl::len(cpp_flags) + 2,\n\t\t\t 0, \/\/ unsaved_files\n\t\t\t 0, \/\/ num_unsaved_files\n\t\t\t flags);\n delete [] args;\n if (!tu) \n {\n std::cerr << \"unable to parse input\\n\";\n return ir;\n }\n\n if (profile)\n std::cout << \"C++ parser took \" << timer.elapsed() \n << \" seconds\" << std::endl;\n unsigned diagnostics = clang_getNumDiagnostics(tu);\n if (diagnostics)\n {\n for (unsigned i = 0; i != diagnostics; ++i)\n {\n CXDiagnostic d = clang_getDiagnostic(tu, i);\n CXString diagnostic = clang_formatDiagnostic(d, flags);\n std::cerr << clang_getCString(diagnostic) << std::endl;\n clang_disposeString(diagnostic);\n clang_disposeDiagnostic(d);\n }\n throw std::runtime_error(\"The input contains errors.\");\n }\n bpl::object asg = ir.attr(\"asg\");\n bpl::dict files;\n timer.reset();\n ASGTranslator translator(input_file, base_path, primary_file_only, asg, files, verbose, debug);\n translator.translate(tu);\n\n if (profile)\n std::cout << \"ASG translation took \" << timer.elapsed() \n\t << \" seconds\" << std::endl;\n if (sxr_prefix)\n {\n timer.reset();\n SXRGenerator generator(translator, verbose, debug);\n for (size_t i = 0; i != bpl::len(files); ++i)\n {\n bpl::object sf = files.attr(\"values\")()[i];\n if (!bpl::extract(sf.attr(\"annotations\"))().get(\"primary\", false)) continue;\n std::string abs_name = bpl::extract(sf.attr(\"abs_name\"))();\n std::string name = bpl::extract(sf.attr(\"name\"))();\n std::string sxr = std::string(sxr_prefix) + \"\/\" + name + \".sxr\";\n create_directories(fs::path(sxr).branch_path());\n generator.generate(tu, sxr, abs_name, name);\n }\n if (profile)\n std::cout << \"SXR generation took \" << timer.elapsed() \n \t\t<< \" seconds\" << std::endl;\n }\n merge_files(bpl::extract(ir.attr(\"files\")), files);\n\n clang_disposeTranslationUnit(tu);\n clang_disposeIndex(idx);\n return ir;\n}\n\n}\n\nBOOST_PYTHON_MODULE(ParserImpl)\n{\n bpl::scope scope;\n scope.attr(\"version\") = \"0.2\";\n bpl::def(\"parse\", parse);\n bpl::object module = bpl::import(\"Synopsis.Processor\");\n bpl::object error_base = module.attr(\"Error\");\n error_type = bpl::object(bpl::handle<>(PyErr_NewException(\"ParserImpl.ParseError\",\n error_base.ptr(), 0)));\n scope.attr(\"ParseError\") = error_type;\n}\nWork around clang bug.\/\/\n\/\/ Copyright (C) 2005 Stefan Seefeld\n\/\/ All rights reserved.\n\/\/ Licensed to the public under the terms of the GNU LGPL (>= 2),\n\/\/ see the file COPYING for details.\n\/\/\n\n#include \"ASGTranslator.hh\"\n#include \"SXRGenerator.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Synopsis;\nnamespace fs = boost::filesystem;\n\nnamespace\n{\nbpl::object error_type;\n\n\/\/. Override unexpected() to print a message before we abort\nvoid unexpected()\n{\n std::cout << \"Warning: Aborting due to unexpected exception.\" << std::endl;\n throw std::bad_exception();\n}\n\nbpl::dict annotations(bpl::object o) \n{ return bpl::extract(o.attr(\"annotations\"));}\n\n\/\/. Merge new files to files already present in the IR.\n\/\/. If a file doesn't exist yet, add it. If it does, \n\/\/. upgrade the 'primary' flag if it is set now.\nvoid merge_files(bpl::dict ir_files, bpl::dict new_files)\n{\n bpl::list keys = new_files.keys();\n for (unsigned i = 0; i != bpl::len(keys); ++i)\n {\n bpl::object filename = keys[i];\n bpl::object file = new_files[filename];\n if (ir_files.has_key(filename))\n {\n if (bpl::extract(annotations(file)[\"primary\"]))\n \tannotations(ir_files[filename])[\"primary\"] = true;\n }\n else\n ir_files[filename] = file;\n }\n}\n\n\nbpl::object parse(bpl::object ir,\n char const *cpp_file, char const *input_file, char const *base_path,\n bool primary_file_only, char const *sxr_prefix,\n\t\t bpl::list cpp_flags,\n bool verbose, bool debug, bool profile)\n{\n std::set_unexpected(unexpected);\n\n \/\/ if (debug) Synopsis::Trace::enable(Trace::TRANSLATION);\n\n if (!input_file || *input_file == '\\0') throw std::runtime_error(\"no input file\");\n\n char const **args = new char const*[bpl::len(cpp_flags) + 3];\n args[0] = \"-x\";\n args[1] = \"c\";\n for (size_t i = 0; i != bpl::len(cpp_flags); ++i)\n args[i + 2] = bpl::extract(cpp_flags[i]);\n \/\/ Due to a bug in clang 2.9, the '-x c' option above only\n \/\/ works if the input argument is passed in args, instead of\n \/\/ the below 'input_file'. (Fixed in trunk)\n args[bpl::len(cpp_flags) + 2] = input_file;\n\n Timer timer;\n \/\/ first arg: exclude declarations from PCH\n \/\/ second arg: display diagnostics\n CXIndex idx = clang_createIndex(0, 1);\n CXTranslationUnit_Flags flags = CXTranslationUnit_DetailedPreprocessingRecord;\n CXTranslationUnit tu = \n clang_parseTranslationUnit(idx, 0,\/\/input_file,\n\t\t\t args,\n\t\t\t bpl::len(cpp_flags) + 2,\n\t\t\t 0, \/\/ unsaved_files\n\t\t\t 0, \/\/ num_unsaved_files\n\t\t\t flags);\n delete [] args;\n if (!tu) \n {\n std::cerr << \"unable to parse input\\n\";\n return ir;\n }\n\n if (profile)\n std::cout << \"C++ parser took \" << timer.elapsed() \n << \" seconds\" << std::endl;\n unsigned diagnostics = clang_getNumDiagnostics(tu);\n if (diagnostics)\n {\n for (unsigned i = 0; i != diagnostics; ++i)\n {\n CXDiagnostic d = clang_getDiagnostic(tu, i);\n CXString diagnostic = clang_formatDiagnostic(d, flags);\n std::cerr << clang_getCString(diagnostic) << std::endl;\n clang_disposeString(diagnostic);\n clang_disposeDiagnostic(d);\n }\n throw std::runtime_error(\"The input contains errors.\");\n }\n bpl::object asg = ir.attr(\"asg\");\n bpl::dict files;\n timer.reset();\n ASGTranslator translator(input_file, base_path, primary_file_only, asg, files, verbose, debug);\n translator.translate(tu);\n\n if (profile)\n std::cout << \"ASG translation took \" << timer.elapsed() \n\t << \" seconds\" << std::endl;\n if (sxr_prefix)\n {\n timer.reset();\n SXRGenerator generator(translator, verbose, debug);\n for (size_t i = 0; i != bpl::len(files); ++i)\n {\n bpl::object sf = files.attr(\"values\")()[i];\n if (!bpl::extract(sf.attr(\"annotations\"))().get(\"primary\", false)) continue;\n std::string abs_name = bpl::extract(sf.attr(\"abs_name\"))();\n std::string name = bpl::extract(sf.attr(\"name\"))();\n std::string sxr = std::string(sxr_prefix) + \"\/\" + name + \".sxr\";\n create_directories(fs::path(sxr).branch_path());\n generator.generate(tu, sxr, abs_name, name);\n }\n if (profile)\n std::cout << \"SXR generation took \" << timer.elapsed() \n \t\t<< \" seconds\" << std::endl;\n }\n merge_files(bpl::extract(ir.attr(\"files\")), files);\n\n clang_disposeTranslationUnit(tu);\n clang_disposeIndex(idx);\n return ir;\n}\n\n}\n\nBOOST_PYTHON_MODULE(ParserImpl)\n{\n bpl::scope scope;\n scope.attr(\"version\") = \"0.2\";\n bpl::def(\"parse\", parse);\n bpl::object module = bpl::import(\"Synopsis.Processor\");\n bpl::object error_base = module.attr(\"Error\");\n error_type = bpl::object(bpl::handle<>(PyErr_NewException(\"ParserImpl.ParseError\",\n error_base.ptr(), 0)));\n scope.attr(\"ParseError\") = error_type;\n}\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"sceneitem.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/project\/assemblycollectionitem.h\"\n#include \"mainwindow\/project\/multimodelcollectionitem.h\"\n#include \"mainwindow\/project\/singlemodelcollectionitem.h\"\n#include \"mainwindow\/project\/texturecollectionitem.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/entity.h\"\n#include \"renderer\/api\/environmentedf.h\"\n#include \"renderer\/api\/environmentshader.h\"\n#include \"renderer\/api\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/uid.h\"\n\n\/\/ Qt headers.\n#include \n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nSceneItem::SceneItem(\n Scene& scene,\n ProjectBuilder& project_builder,\n ParamArray& settings)\n : BaseGroupItem(g_class_uid, \"Scene\", scene, project_builder, settings)\n{\n set_allow_deletion(false);\n set_allow_edition(false);\n\n insertChild(\n 0,\n m_camera_item =\n new CameraItem(\n scene.get_camera(),\n scene,\n this,\n project_builder));\n m_camera_item->set_allow_deletion(false);\n m_camera_item->set_fixed_position(true);\n\n insertChild(\n 1,\n m_environment_item =\n new EnvironmentItem(\n scene.get_environment(),\n scene,\n this,\n project_builder));\n m_environment_item->set_allow_deletion(false);\n m_environment_item->set_fixed_position(true);\n\n insertChild(\n 2,\n m_environment_edf_collection_item =\n new MultiModelCollectionItem(\n new_guid(),\n EntityTraits::get_human_readable_collection_type_name(),\n scene,\n this,\n project_builder));\n m_environment_edf_collection_item->add_items(scene.environment_edfs());\n\n insertChild(\n 3,\n m_environment_shader_collection_item =\n new MultiModelCollectionItem(\n new_guid(),\n EntityTraits::get_human_readable_collection_type_name(),\n scene,\n this,\n project_builder));\n m_environment_shader_collection_item->add_items(scene.environment_shaders());\n}\n\nQMenu* SceneItem::get_single_item_context_menu() const\n{\n QMenu* menu = ItemBase::get_single_item_context_menu();\n\n menu->addSeparator();\n menu->addAction(\"Import Textures...\", &get_texture_collection_item(), SLOT(slot_import_textures()));\n\n menu->addSeparator();\n menu->addAction(\"Create Assembly...\", &get_assembly_collection_item(), SLOT(slot_create()));\n menu->addAction(\"Create Color...\", &get_color_collection_item(), SLOT(slot_create()));\n menu->addAction(\"Create Environment EDF...\", m_environment_edf_collection_item, SLOT(slot_create()));\n menu->addAction(\"Create Environment Shader...\", m_environment_shader_collection_item, SLOT(slot_create()));\n\n return menu;\n}\n\nvoid SceneItem::add_item(EnvironmentEDF* environment_edf)\n{\n m_environment_edf_collection_item->add_item(environment_edf);\n}\n\nvoid SceneItem::add_item(EnvironmentShader* environment_shader)\n{\n m_environment_shader_collection_item->add_item(environment_shader);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\nthe Scene item is a kind of collection item, display it in bold.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"sceneitem.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/project\/assemblycollectionitem.h\"\n#include \"mainwindow\/project\/multimodelcollectionitem.h\"\n#include \"mainwindow\/project\/singlemodelcollectionitem.h\"\n#include \"mainwindow\/project\/texturecollectionitem.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/entity.h\"\n#include \"renderer\/api\/environmentedf.h\"\n#include \"renderer\/api\/environmentshader.h\"\n#include \"renderer\/api\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/uid.h\"\n\n\/\/ Qt headers.\n#include \n#include \n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nSceneItem::SceneItem(\n Scene& scene,\n ProjectBuilder& project_builder,\n ParamArray& settings)\n : BaseGroupItem(g_class_uid, \"Scene\", scene, project_builder, settings)\n{\n set_allow_deletion(false);\n set_allow_edition(false);\n\n QFont font;\n font.setBold(true);\n setFont(0, font);\n\n insertChild(\n 0,\n m_camera_item =\n new CameraItem(\n scene.get_camera(),\n scene,\n this,\n project_builder));\n m_camera_item->set_allow_deletion(false);\n m_camera_item->set_fixed_position(true);\n\n insertChild(\n 1,\n m_environment_item =\n new EnvironmentItem(\n scene.get_environment(),\n scene,\n this,\n project_builder));\n m_environment_item->set_allow_deletion(false);\n m_environment_item->set_fixed_position(true);\n\n insertChild(\n 2,\n m_environment_edf_collection_item =\n new MultiModelCollectionItem(\n new_guid(),\n EntityTraits::get_human_readable_collection_type_name(),\n scene,\n this,\n project_builder));\n m_environment_edf_collection_item->add_items(scene.environment_edfs());\n\n insertChild(\n 3,\n m_environment_shader_collection_item =\n new MultiModelCollectionItem(\n new_guid(),\n EntityTraits::get_human_readable_collection_type_name(),\n scene,\n this,\n project_builder));\n m_environment_shader_collection_item->add_items(scene.environment_shaders());\n}\n\nQMenu* SceneItem::get_single_item_context_menu() const\n{\n QMenu* menu = ItemBase::get_single_item_context_menu();\n\n menu->addSeparator();\n menu->addAction(\"Import Textures...\", &get_texture_collection_item(), SLOT(slot_import_textures()));\n\n menu->addSeparator();\n menu->addAction(\"Create Assembly...\", &get_assembly_collection_item(), SLOT(slot_create()));\n menu->addAction(\"Create Color...\", &get_color_collection_item(), SLOT(slot_create()));\n menu->addAction(\"Create Environment EDF...\", m_environment_edf_collection_item, SLOT(slot_create()));\n menu->addAction(\"Create Environment Shader...\", m_environment_shader_collection_item, SLOT(slot_create()));\n\n return menu;\n}\n\nvoid SceneItem::add_item(EnvironmentEDF* environment_edf)\n{\n m_environment_edf_collection_item->add_item(environment_edf);\n}\n\nvoid SceneItem::add_item(EnvironmentShader* environment_shader)\n{\n m_environment_shader_collection_item->add_item(environment_shader);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#include \"libbirch\/SharedPointer.hpp\"\n\n#include \"libbirch\/World.hpp\"\n#include \"libbirch\/WeakPointer.hpp\"\n#include \"libbirch\/Any.hpp\"\n\nbi::SharedPointer::SharedPointer() :\n SharedPointer(std::make_shared()) {\n \/\/\n}\n\nbi::SharedPointer::SharedPointer(const std::nullptr_t& o) {\n \/\/\n}\n\nbi::SharedPointer::SharedPointer(const std::shared_ptr& ptr) :\n ptr(ptr) {\n \/\/\n}\n\nbi::SharedPointer& bi::SharedPointer::operator=(\n const std::nullptr_t& o) {\n ptr = o;\n return *this;\n}\n\nbool bi::SharedPointer::query() const {\n return static_cast(ptr);\n}\n\nbi::Any* bi::SharedPointer::get() {\n return fiberWorld->get(ptr).get();\n}\n\nbi::Any* bi::SharedPointer::get() const {\n return fiberWorld->get(ptr).get();\n}\nPointers now updated after mapping, ~15% performance gain (anecdotal).\/**\n * @file\n *\/\n#include \"libbirch\/SharedPointer.hpp\"\n\n#include \"libbirch\/World.hpp\"\n#include \"libbirch\/WeakPointer.hpp\"\n#include \"libbirch\/Any.hpp\"\n\nbi::SharedPointer::SharedPointer() :\n SharedPointer(std::make_shared()) {\n \/\/\n}\n\nbi::SharedPointer::SharedPointer(const std::nullptr_t& o) {\n \/\/\n}\n\nbi::SharedPointer::SharedPointer(const std::shared_ptr& ptr) :\n ptr(ptr) {\n \/\/\n}\n\nbi::SharedPointer& bi::SharedPointer::operator=(\n const std::nullptr_t& o) {\n ptr = o;\n return *this;\n}\n\nbool bi::SharedPointer::query() const {\n return static_cast(ptr);\n}\n\nbi::Any* bi::SharedPointer::get() {\n ptr = fiberWorld->get(ptr);\n return ptr.get();\n}\n\nbi::Any* bi::SharedPointer::get() const {\n const_cast&>(ptr) = fiberWorld->get(ptr);\n return ptr.get();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: addonstoolbarmanager.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 11:04:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\n#define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_\n#include \n#endif\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_\n#include \n#endif\n\n#include \n\n\nnamespace framework\n{\n\nclass ToolBar;\nclass AddonsToolBarManager : public ToolBarManager\n{\n public:\n AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,\n const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,\n const rtl::OUString& rResourceName,\n ToolBar* pToolBar );\n virtual ~AddonsToolBarManager();\n\n \/\/ XComponent\n void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );\n\n virtual void RefreshImages();\n using ToolBarManager::FillToolbar;\n void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar );\n\n protected:\n DECL_LINK( Click, ToolBox * );\n DECL_LINK( DoubleClick, ToolBox * );\n DECL_LINK( Command, CommandEvent * );\n DECL_LINK( Select, ToolBox * );\n DECL_LINK( Highlight, ToolBox * );\n DECL_LINK( Activate, ToolBox * );\n DECL_LINK( Deactivate, ToolBox * );\n DECL_LINK( StateChanged, StateChangedType* );\n DECL_LINK( DataChanged, DataChangedEvent* );\n\n private:\n struct AddonsParams\n {\n rtl::OUString aImageId;\n rtl::OUString aTarget;\n };\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\nINTEGRATION: CWS fwk58 (1.6.116); FILE MERGED 2007\/01\/09 10:20:14 cd 1.6.116.1: #138017# Remove 'Visible Buttons' and 'Customize' from add-on toolbar menu\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: addonstoolbarmanager.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2007-01-23 07:10:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\n#define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_\n#include \n#endif\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_\n#include \n#endif\n\n#include \n\n\nnamespace framework\n{\n\nclass ToolBar;\nclass AddonsToolBarManager : public ToolBarManager\n{\n public:\n AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,\n const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,\n const rtl::OUString& rResourceName,\n ToolBar* pToolBar );\n virtual ~AddonsToolBarManager();\n\n \/\/ XComponent\n void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );\n\n virtual void RefreshImages();\n using ToolBarManager::FillToolbar;\n void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar );\n\n protected:\n DECL_LINK( Click, ToolBox * );\n DECL_LINK( DoubleClick, ToolBox * );\n DECL_LINK( Command, CommandEvent * );\n DECL_LINK( Select, ToolBox * );\n DECL_LINK( Highlight, ToolBox * );\n DECL_LINK( Activate, ToolBox * );\n DECL_LINK( Deactivate, ToolBox * );\n DECL_LINK( StateChanged, StateChangedType* );\n DECL_LINK( DataChanged, DataChangedEvent* );\n\n virtual bool MenuItemAllowed( sal_uInt16 ) const;\n\n private:\n struct AddonsParams\n {\n rtl::OUString aImageId;\n rtl::OUString aTarget;\n };\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_\n<|endoftext|>"} {"text":"\/\/ This implements:\n\/\/ E. Ukkonen, \"On-line construction of suffix trees,\" Algorithmica, vol. 14,\n\/\/ pp. 249-260, 1995.\n\/\/\n\/\/ Implementation is as close to the pseudocode in the paper as possible\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing state = int;\n\n\/\/ (s, (k, _)) reference pair (without right pointer)\nusing RP = pair;\n\n\/\/ (k, p, s') from g(s, (k, p)) = s'\nusing GT = tuple;\n\n\/\/ AlphabetSize (default is small letters); SC = Start char\ntemplate \nclass SuffixTree {\n static constexpr int BOTTOM = 0;\n static constexpr int ROOT = 1;\n\n public:\n void print() const;\n \/\/ ----------------------------------------\n\n \/\/ A suffix tree has at most n - 1 branching states; at most 2 * n - 2\n \/\/ transitions; at most 2 * n states\n \/\/\n \/\/ This implementation uses 2 * n + 1 for the bounds,\n \/\/ + 1 just to guard the empty string case\n SuffixTree(string_view sv)\n : n(sv.length()), g(2 * n + 1), f(2 * n + 1), t(sv), q_count(2) {\n algorithm2();\n }\n\n private:\n void algorithm2() {\n \/\/ XXX: CAUTION! string is now 0 indexed, i and k should start from 0\n \/\/ and max string index = n - 1\n int s = ROOT, k = 0;\n for (int j = 0; j < Alph; ++j) g[BOTTOM][j] = {-j, -j, ROOT};\n f[ROOT] = BOTTOM;\n for (int i = 0; i < n; ++i) {\n tie(s, k) = update(s, k, i);\n tie(s, k) = canonize(s, k, i);\n }\n }\n\n RP update(int s, int k, int i) {\n int oldr = ROOT;\n auto [is_end_point, r] = test_and_split(s, k, i - 1, t[i]);\n while (!is_end_point) {\n g[r][t[i] - SC] = {i, n - 1, q_count++};\n if (oldr != ROOT) f[oldr] = r;\n oldr = r;\n tie(s, k) = canonize(f[s], k, i - 1);\n tie(is_end_point, r) = test_and_split(s, k, i - 1, t[i]);\n }\n if (oldr != ROOT) f[oldr] = s;\n return {s, k};\n }\n\n pair test_and_split(int s, int k, int p, char t_) {\n if (k <= p) {\n auto [kp, pp, sp] = g[s][t[k] - SC];\n if (t_ == t[kp + p - k + 1]) return {true, s};\n\n int r = q_count++;\n g[s][t[k] - SC] = {kp, kp + p - k, r};\n g[r][t[kp + p - k + 1] - SC] = {kp + p - k + 1, pp, sp};\n return {false, r};\n }\n auto [kpp, ppp, spp] = g[s][t_ - SC];\n return {g[s][t_ - SC] != GT{}, s};\n }\n\n RP canonize(int s, int k, int p) const {\n if (p < k) return {s, k};\n\n auto [kp, pp, sp] = g[s][t[k] - SC];\n while (pp - kp <= p - k) {\n k = k + pp - kp + 1;\n s = sp;\n if (k <= p) tie(kp, pp, sp) = g[s][t[k] - SC];\n }\n return {s, k};\n }\n\n string_view t;\n int n; \/\/ length of string\n int q_count; \/\/ state indices\n vector f; \/\/ suffix links\n\n \/\/ transitions; g[s][i] = {k, p, r}\n \/\/ -> state#s 't[i]'-transition is\n \/\/ g(s, (k, p)) = r\n \/\/ where t[k] = t[i]\n \/\/\n \/\/ to save space, using a map\/hash is also possible\n vector > g;\n};\n\ntemplate \nvoid SuffixTree::print() const {\n cout << \"f: \";\n for (int q = 0; q < 2 * n; ++q) {\n if (f[q]) printf(\"f[%d] = %d | \", q, f[q]);\n }\n cout << '\\n';\n cout << \"g: \";\n for (int q = 1; q < 2 * n; ++q) {\n for (int w = 0; w < Alph; ++w) {\n auto tup = g[q][w];\n if (tup != GT{}) {\n auto [kp, pp, sp] = tup;\n printf(\"g(%d, [%c](%d, %d)) = %d | \", q, t[kp], kp, pp, sp);\n }\n }\n }\n cout << '\\n';\n}\n\nremove unnecessary code\/\/ This implements:\n\/\/ E. Ukkonen, \"On-line construction of suffix trees,\" Algorithmica, vol. 14,\n\/\/ pp. 249-260, 1995.\n\/\/\n\/\/ Implementation is as close to the pseudocode in the paper as possible\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing state = int;\n\n\/\/ (s, (k, _)) reference pair (without right pointer)\nusing RP = pair;\n\n\/\/ (k, p, s') from g(s, (k, p)) = s'\nusing GT = tuple;\n\n\/\/ AlphabetSize (default is small letters); SC = Start char\ntemplate \nclass SuffixTree {\n static constexpr int BOTTOM = 0;\n static constexpr int ROOT = 1;\n\n public:\n void print() const;\n \/\/ ----------------------------------------\n\n \/\/ A suffix tree has at most n - 1 branching states; at most 2 * n - 2\n \/\/ transitions; at most 2 * n states\n \/\/\n \/\/ This implementation uses 2 * n + 1 for the bounds,\n \/\/ + 1 just to guard the empty string case\n SuffixTree(string_view sv)\n : n(sv.length()), g(2 * n + 1), f(2 * n + 1), t(sv), q_count(2) {\n algorithm2();\n }\n\n private:\n void algorithm2() {\n \/\/ XXX: CAUTION! string is now 0 indexed, i and k should start from 0\n \/\/ and max string index = n - 1\n int s = ROOT, k = 0;\n for (int j = 0; j < Alph; ++j) g[BOTTOM][j] = {-j, -j, ROOT};\n f[ROOT] = BOTTOM;\n for (int i = 0; i < n; ++i) {\n tie(s, k) = update(s, k, i);\n tie(s, k) = canonize(s, k, i);\n }\n }\n\n RP update(int s, int k, int i) {\n int oldr = ROOT;\n auto [is_end_point, r] = test_and_split(s, k, i - 1, t[i]);\n while (!is_end_point) {\n g[r][t[i] - SC] = {i, n - 1, q_count++};\n if (oldr != ROOT) f[oldr] = r;\n oldr = r;\n tie(s, k) = canonize(f[s], k, i - 1);\n tie(is_end_point, r) = test_and_split(s, k, i - 1, t[i]);\n }\n if (oldr != ROOT) f[oldr] = s;\n return {s, k};\n }\n\n pair test_and_split(int s, int k, int p, char t_) {\n if (k <= p) {\n auto [kp, pp, sp] = g[s][t[k] - SC];\n if (t_ == t[kp + p - k + 1]) return {true, s};\n\n int r = q_count++;\n g[s][t[k] - SC] = {kp, kp + p - k, r};\n g[r][t[kp + p - k + 1] - SC] = {kp + p - k + 1, pp, sp};\n return {false, r};\n }\n return {g[s][t_ - SC] != GT{}, s};\n }\n\n RP canonize(int s, int k, int p) const {\n if (p < k) return {s, k};\n\n auto [kp, pp, sp] = g[s][t[k] - SC];\n while (pp - kp <= p - k) {\n k = k + pp - kp + 1;\n s = sp;\n if (k <= p) tie(kp, pp, sp) = g[s][t[k] - SC];\n }\n return {s, k};\n }\n\n string_view t;\n int n; \/\/ length of string\n int q_count; \/\/ state indices\n vector f; \/\/ suffix links\n\n \/\/ transitions; g[s][i] = {k, p, r}\n \/\/ -> state#s 't[i]'-transition is\n \/\/ g(s, (k, p)) = r\n \/\/ where t[k] = t[i]\n \/\/\n \/\/ to save space, using a map\/hash is also possible\n vector > g;\n};\n\ntemplate \nvoid SuffixTree::print() const {\n cout << \"f: \";\n for (int q = 0; q < 2 * n; ++q) {\n if (f[q]) printf(\"f[%d] = %d | \", q, f[q]);\n }\n cout << '\\n';\n cout << \"g: \";\n for (int q = 1; q < 2 * n; ++q) {\n for (int w = 0; w < Alph; ++w) {\n auto tup = g[q][w];\n if (tup != GT{}) {\n auto [kp, pp, sp] = tup;\n printf(\"g(%d, [%c](%d, %d)) = %d | \", q, t[kp], kp, pp, sp);\n }\n }\n }\n cout << '\\n';\n}\n\n<|endoftext|>"} {"text":"#include \"hascolGenerator.h\"\n\n#include \n#include \n\n#include \n\n#include \"..\/..\/..\/qrkernel\/roles.h\"\n#include \"..\/..\/..\/qrutils\/outFile.h\"\n\nusing namespace qReal;\nusing namespace hascol;\nusing utils::OutFile;\n\nHascolGenerator::HascolGenerator(qrRepo::LogicalRepoApi const &api, qReal::ErrorReporterInterface &errorReporter)\n\t\t: mApi(api)\n\t\t, mErrorReporter(errorReporter)\n{\n}\n\nvoid HascolGenerator::generate()\n{\n\tId repoId = Id::rootId();\n\tIdList rootDiagrams = mApi.children(repoId);\n\n\tforeach (Id const diagram, rootDiagrams) {\n\t\tif (diagram.element() == \"HascolPortMapping_HascolPortMappingDiagram\")\n\t\t\tmPortMappingDiagrams.append(diagram);\n\t\telse if (diagram.element() == \"HascolActivity_HascolActivityDiagram\")\n\t\t\tmActivityDiagrams.append(diagram);\n\t}\n\n\tforeach (Id const diagram, rootDiagrams) {\n\t\tqDebug() << diagram.element();\n\t\tif (diagram.element() == \"HascolStructure_HascolStructureDiagram\")\n\t\t\tgenerateDiagram(diagram);\n\t}\n}\n\nvoid HascolGenerator::generateDiagram(Id const &id)\n{\n\tQString outputDirectory = mApi.stringProperty(id, \"output directory\");\n\tif (outputDirectory == \"\")\n\t\toutputDirectory = \".\";\n\tOutFile out(outputDirectory + \"\/\" + mApi.name(id) + \".md\");\n\n\tout() << \"using bincompl;\\n\"; \/\/ Сигнатура по умолчанию, определяет основные используемые типы и операции.\n\tout() << \"\\n\";\n\n\tforeach (Id const element, mApi.children(id)) {\n\t\tif (element.element() == \"HascolStructure_Process\"\n\t\t\t&& !mApi.name(element).isEmpty())\n\t\t{\n\t\t\tgenerateProcess(element, out);\n\t\t\tout() << \"\\n\";\n\t\t} else if (element.element() == \"HascolStructure_Functor\") {\n\t\t\tgenerateFunctor(element, out);\n\t\t\tout() << \"\\n\";\n\t\t}\n\t}\n}\n\nvoid HascolGenerator::generateProcess(Id const &id, OutFile &out)\n{\n\tout() << \"process \" << mApi.name(id) << \" =\\n\";\n\tgenerateProcessTypeBody(id, out);\n}\n\nvoid HascolGenerator::generateProcessTypeBody(Id const &id, utils::OutFile &out)\n{\n\tout() << \"begin\\n\";\n\n\tout.incIndent();\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"HascolStructure_ProcessOperation\")\n\t\t\tgenerateProcessOperation(child, out);\n\n\tbool firstResource = true;\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"HascolStructure_Resource\") {\n\t\t\tif (firstResource) {\n\t\t\t\tout() << \"data\\n\";\n\t\t\t\tout.incIndent();\n\t\t\t}\n\t\t\tgenerateResource(child, firstResource, out);\n\t\t\tfirstResource = false;\n\t\t}\n\tif (!firstResource) {\n\t\tout.decIndent();\n\t\tout() << \";\\n\";\n\t}\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"HascolStructure_LetBinding\")\n\t\t\tgenerateLetBinding(child, out);\n\n\tforeach (Id const link, mApi.incomingLinks(id)) {\n\t\tif (link.element() == \"HascolStructure_UsedProcessRelation\") {\n\t\t\tId const usedProcess = mApi.otherEntityFromLink(link, id);\n\t\t\tout() << \"process \" << mApi.name(link) << \" = \" << mApi.name(usedProcess) << \";\\n\";\n\t\t}\n\t\tif (link.element() == \"HascolStructure_NestedProcessRelation\") {\n\t\t\tId const nestedProcess = mApi.otherEntityFromLink(link, id);\n\t\t\tout() << \"process \" << mApi.name(link) << \" =\\n\";\n\t\t\tgenerateProcessTypeBody(nestedProcess, out);\n\t\t}\n\t}\n\n\tforeach (Id const activity, mActivityDiagrams)\n\t\tif (mApi.name(activity) == mApi.name(id))\n\t\t\tgenerateActivity(activity, out);\n\n\tforeach (Id const portMap, mPortMappingDiagrams)\n\t\tif (mApi.name(portMap) == mApi.name(id))\n\t\t\tgeneratePortMap(portMap, out);\n\n\tout.decIndent();\n\n\tout() << \"end;\\n\";\n}\n\nvoid HascolGenerator::generatePortMap(Id const &id, utils::OutFile &out)\n{\n\tforeach (Id const child, mApi.children(id)) {\n\t\tif (child.element() == \"HascolPortMapping_ProcessInstance\"\n\t\t\t|| child.element() == \"HascolPortMapping_FunctorInstance\")\n\t\t{\n\t\t\tforeach (Id const instanceChild, mApi.children(child)) {\n\t\t\t\tif (instanceChild.element() == \"HascolPortMapping_ProcessInstance\"\n\t\t\t\t\t|| instanceChild.element() == \"HascolPortMapping_ProcessInstance\")\n\t\t\t\t{\n\t\t\t\t\tout() << \"process \" << mApi.name(instanceChild).replace(\":\", \"=\") << \" with\\n\";\n\t\t\t\t\tout.incIndent();\n\t\t\t\t\tbool first = true;\n\t\t\t\t\tforeach (Id const port, mApi.children(instanceChild)) {\n\t\t\t\t\t\tif (port.element() == \"HascolPortMapping_Port\") {\n\t\t\t\t\t\t\tif (mApi.links(port).isEmpty()) {\n\t\t\t\t\t\t\t\tmErrorReporter.addWarning(\"Port without connections\", port);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tId const link = mApi.links(port).at(0);\n\t\t\t\t\t\t\tId const mappedPort = mApi.otherEntityFromLink(link, port);\n\n\t\t\t\t\t\t\tId const mappedPortParent = mApi.parent(mappedPort);\n\t\t\t\t\t\t\tQString parentName;\n\t\t\t\t\t\t\tif (mappedPortParent == child)\n\t\t\t\t\t\t\t\tparentName = \"\";\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparentName = mApi.name(mappedPortParent);\n\t\t\t\t\t\t\t\tparentName.remove(parentName.indexOf(\":\"), parentName.length());\n\t\t\t\t\t\t\t\tparentName = parentName.trimmed();\n\t\t\t\t\t\t\t\tparentName += \".\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (mApi.outgoingLinks(port).count() == 1\n\t\t\t\t\t\t\t\t|| mappedPortParent == child)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tQString comma = !first ? \", \" : \"\";\n\t\t\t\t\t\t\t\tfirst = false;\n\n\t\t\t\t\t\t\t\tout() << comma << mApi.name(port) << \" = \" << parentName << mApi.name(mappedPort) << \"\\n\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tout.decIndent();\n\t\t\t\t\tout() << \";\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid HascolGenerator::generateFunctor(Id const &id, OutFile &out)\n{\n\tout() << \"process \" << mApi.name(id) << \" (\\n\";\n\n\tout.incIndent();\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"HascolStructure_FunctorFormalParameter\")\n\t\t\tgenerateFunctorFormalParameter(child, out);\n\n\tout.decIndent();\n\n\tout() << \"\\t) =\\n\";\n\tgenerateProcessTypeBody(id, out);\n}\n\nvoid HascolGenerator::generateFunctorFormalParameter(Id const &id, utils::OutFile &out)\n{\n\tif (mApi.links(id).count() == 1) {\n\t\tout() << mApi.name(id) << \" : \";\n\t\tId const parameterType = mApi.otherEntityFromLink(mApi.links(id).at(0), id);\n\t\tif (mApi.name(parameterType) != \"\") {\n\t\t\tout() << mApi.name(parameterType);\n\t\t} else {\n\t\t\tout() << \"\\n\";\n\t\t\tout.incIndent();\n\t\t\tgenerateProcessTypeBody(parameterType, out);\n\t\t\tout.decIndent();\n\t\t}\n\t} else {\n\t\tout() << mApi.name(id) << \"\\n\";\n\t}\n}\n\nvoid HascolGenerator::generateProcessOperation(Id const &id, OutFile &out)\n{\n\tout() << mApi.stringProperty(id, \"direction\") << \" \"\n\t\t<< mApi.name(id) << \";\\n\";\n}\n\nvoid HascolGenerator::generateLetBinding(Id const &id, utils::OutFile &out)\n{\n\tout() << \"let \" << mApi.name(id) << \";\\n\";\n}\n\nvoid HascolGenerator::generateResource(Id const &id, bool first, OutFile &out)\n{\n\tout() << (first ? \"\" : \", \") << mApi.name(id) << \"\\n\";\n}\n\nvoid HascolGenerator::generateActivity(Id const &id, utils::OutFile &out)\n{\n\tforeach (Id const element, mApi.children(id)) {\n\t\tif (element.element() == \"HascolActivity_Group\") {\n\t\t\tout() << \"group {\\n\";\n\t\t\tout.incIndent();\n\t\t\tgenerateActivity(element, out);\n\t\t\tout.decIndent();\n\t\t\tout() << \"}\\n\";\n\t\t} else if (element.element() == \"HascolActivity_HandlerStart\")\n\t\t\tgenerateHandler(element, out);\n\t}\n}\n\nvoid HascolGenerator::generateHandler(Id const &id, utils::OutFile &out)\n{\n\tout() << mApi.stringProperty(id, \"trigger\") << \"\\n\";\n\tout() << \"{\\n\";\n\n\tout.incIndent();\n\tgenerateChain(id, out);\n\tout.decIndent();\n\n\tout() << \"}\\n\";\n}\n\nId HascolGenerator::generateChain(Id const &startNode, utils::OutFile &out)\n{\n\tId currentId = startNode;\n\twhile (mApi.outgoingLinks(currentId).count() > 0) {\n\n\t\tif (mApi.incomingLinks(currentId).count() > 1)\n\t\t\treturn currentId;\n\n\t\tif (currentId.element() == \"HascolActivity_DecisionNode\") {\n\t\t\tcurrentId = generateIf(currentId, out);\n\t\t} else if (mApi.outgoingLinks(currentId).count() > 1) {\n\t\t\tgenerateActivityNode(currentId, out);\n\t\t\tId chainEndId;\n\t\t\tbool wasOutgoingLink = false;\n\t\t\tforeach (Id linkId, mApi.outgoingLinks(currentId)) {\n\t\t\t\tif (wasOutgoingLink)\n\t\t\t\t\tout() << \"|\\n\";\n\t\t\t\twasOutgoingLink = true;\n\t\t\t\tId chainBeginId = mApi.otherEntityFromLink(linkId, currentId);\n\t\t\t\tchainEndId = generateChain(chainBeginId, out);\n\t\t\t}\n\t\t\tcurrentId = chainEndId;\n\t\t}\n\n\t\tgenerateActivityNode(currentId, out);\n\n\t\tif (mApi.outgoingLinks(currentId).count() > 0) {\n\t\t\tId const link = mApi.outgoingLinks(currentId)[0]; \/\/ Последовательный участок цепочки.\n\t\t\tcurrentId = mApi.otherEntityFromLink(link, currentId);\n\t\t}\n\t}\n\treturn currentId;\n}\n\nvoid HascolGenerator::generateActivityNode(Id const &id, utils::OutFile &out)\n{\n\tif (id.element() == \"HascolActivity_SendSignalAction\") {\n\t\tout() << \"send \" << mApi.name(id) << \"\\n\";\n\t} else if (id.element() == \"HascolActivity_InformSignalAction\") {\n\t\tout() << \"inform \" << mApi.name(id) << \"\\n\";\n\t} else if (id.element() == \"HascolActivity_Action\") {\n\t\tout() << mApi.name(id) << \"\\n\";\n\t}\n}\n\nId HascolGenerator::generateIf(Id const &id, utils::OutFile &out)\n{\n\tId const thenLink = mApi.outgoingLinks(id)[0];\n\tout() << \"if \" << mApi.stringProperty(thenLink, \"guard\") << \" then {\\n\";\n\tout.incIndent();\n\tId const thenChainEnd = generateChain(mApi.otherEntityFromLink(thenLink, id), out);\n\tId const elseLink = mApi.outgoingLinks(id)[1];\n\tId const elseNode = mApi.otherEntityFromLink(elseLink, id);\n\tif (elseNode != thenChainEnd) {\n\t\tout.decIndent();\n\t\tout() << \"} else {\\n\";\n\t\tout.incIndent();\n\t\tgenerateChain(elseNode, out);\n\t}\n\tout.decIndent();\n\tout() << \"} fi\\n\";\n\treturn thenChainEnd;\n}\nupdated Hascol generator to current node naming scheme#include \"hascolGenerator.h\"\n\n#include \n#include \n\n#include \n\n#include \"..\/..\/..\/qrkernel\/roles.h\"\n#include \"..\/..\/..\/qrutils\/outFile.h\"\n\nusing namespace qReal;\nusing namespace hascol;\nusing utils::OutFile;\n\nHascolGenerator::HascolGenerator(qrRepo::LogicalRepoApi const &api, qReal::ErrorReporterInterface &errorReporter)\n\t\t: mApi(api)\n\t\t, mErrorReporter(errorReporter)\n{\n}\n\nvoid HascolGenerator::generate()\n{\n\tId repoId = Id::rootId();\n\tIdList rootDiagrams = mApi.children(repoId);\n\n\tforeach (Id const diagram, rootDiagrams) {\n\t\tif (diagram.element() == \"HascolPortMapping_HascolPortMappingDiagram\")\n\t\t\tmPortMappingDiagrams.append(diagram);\n\t\telse if (diagram.element() == \"HascolActivity_HascolActivityDiagram\")\n\t\t\tmActivityDiagrams.append(diagram);\n\t}\n\n\tforeach (Id const diagram, rootDiagrams) {\n\t\tqDebug() << diagram.element();\n\t\tif (diagram.element() == \"HascolStructureDiagram\")\n\t\t\tgenerateDiagram(diagram);\n\t}\n}\n\nvoid HascolGenerator::generateDiagram(Id const &id)\n{\n\tQString outputDirectory = mApi.stringProperty(id, \"output directory\");\n\tif (outputDirectory == \"\")\n\t\toutputDirectory = \".\";\n\tOutFile out(outputDirectory + \"\/\" + mApi.name(id) + \".md\");\n\n\tout() << \"using bincompl;\\n\"; \/\/ Сигнатура по умолчанию, определяет основные используемые типы и операции.\n\tout() << \"\\n\";\n\n\tforeach (Id const element, mApi.children(id)) {\n\t\tif (element.element() == \"Process\"\n\t\t\t&& !mApi.name(element).isEmpty())\n\t\t{\n\t\t\tgenerateProcess(element, out);\n\t\t\tout() << \"\\n\";\n\t\t} else if (element.element() == \"Functor\") {\n\t\t\tgenerateFunctor(element, out);\n\t\t\tout() << \"\\n\";\n\t\t}\n\t}\n}\n\nvoid HascolGenerator::generateProcess(Id const &id, OutFile &out)\n{\n\tout() << \"process \" << mApi.name(id) << \" =\\n\";\n\tgenerateProcessTypeBody(id, out);\n}\n\nvoid HascolGenerator::generateProcessTypeBody(Id const &id, utils::OutFile &out)\n{\n\tout() << \"begin\\n\";\n\n\tout.incIndent();\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"ProcessOperation\")\n\t\t\tgenerateProcessOperation(child, out);\n\n\tbool firstResource = true;\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"Resource\") {\n\t\t\tif (firstResource) {\n\t\t\t\tout() << \"data\\n\";\n\t\t\t\tout.incIndent();\n\t\t\t}\n\t\t\tgenerateResource(child, firstResource, out);\n\t\t\tfirstResource = false;\n\t\t}\n\tif (!firstResource) {\n\t\tout.decIndent();\n\t\tout() << \";\\n\";\n\t}\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"LetBinding\")\n\t\t\tgenerateLetBinding(child, out);\n\n\tforeach (Id const link, mApi.incomingLinks(id)) {\n\t\tif (link.element() == \"UsedProcessRelation\") {\n\t\t\tId const usedProcess = mApi.otherEntityFromLink(link, id);\n\t\t\tout() << \"process \" << mApi.name(link) << \" = \" << mApi.name(usedProcess) << \";\\n\";\n\t\t}\n\t\tif (link.element() == \"NestedProcessRelation\") {\n\t\t\tId const nestedProcess = mApi.otherEntityFromLink(link, id);\n\t\t\tout() << \"process \" << mApi.name(link) << \" =\\n\";\n\t\t\tgenerateProcessTypeBody(nestedProcess, out);\n\t\t}\n\t}\n\n\tforeach (Id const activity, mActivityDiagrams)\n\t\tif (mApi.name(activity) == mApi.name(id))\n\t\t\tgenerateActivity(activity, out);\n\n\tforeach (Id const portMap, mPortMappingDiagrams)\n\t\tif (mApi.name(portMap) == mApi.name(id))\n\t\t\tgeneratePortMap(portMap, out);\n\n\tout.decIndent();\n\n\tout() << \"end;\\n\";\n}\n\nvoid HascolGenerator::generatePortMap(Id const &id, utils::OutFile &out)\n{\n\tforeach (Id const child, mApi.children(id)) {\n\t\tif (child.element() == \"HascolPortMapping_ProcessInstance\"\n\t\t\t|| child.element() == \"HascolPortMapping_FunctorInstance\")\n\t\t{\n\t\t\tforeach (Id const instanceChild, mApi.children(child)) {\n\t\t\t\tif (instanceChild.element() == \"HascolPortMapping_ProcessInstance\"\n\t\t\t\t\t|| instanceChild.element() == \"HascolPortMapping_ProcessInstance\")\n\t\t\t\t{\n\t\t\t\t\tout() << \"process \" << mApi.name(instanceChild).replace(\":\", \"=\") << \" with\\n\";\n\t\t\t\t\tout.incIndent();\n\t\t\t\t\tbool first = true;\n\t\t\t\t\tforeach (Id const port, mApi.children(instanceChild)) {\n\t\t\t\t\t\tif (port.element() == \"HascolPortMapping_Port\") {\n\t\t\t\t\t\t\tif (mApi.links(port).isEmpty()) {\n\t\t\t\t\t\t\t\tmErrorReporter.addWarning(\"Port without connections\", port);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tId const link = mApi.links(port).at(0);\n\t\t\t\t\t\t\tId const mappedPort = mApi.otherEntityFromLink(link, port);\n\n\t\t\t\t\t\t\tId const mappedPortParent = mApi.parent(mappedPort);\n\t\t\t\t\t\t\tQString parentName;\n\t\t\t\t\t\t\tif (mappedPortParent == child)\n\t\t\t\t\t\t\t\tparentName = \"\";\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparentName = mApi.name(mappedPortParent);\n\t\t\t\t\t\t\t\tparentName.remove(parentName.indexOf(\":\"), parentName.length());\n\t\t\t\t\t\t\t\tparentName = parentName.trimmed();\n\t\t\t\t\t\t\t\tparentName += \".\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (mApi.outgoingLinks(port).count() == 1\n\t\t\t\t\t\t\t\t|| mappedPortParent == child)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tQString comma = !first ? \", \" : \"\";\n\t\t\t\t\t\t\t\tfirst = false;\n\n\t\t\t\t\t\t\t\tout() << comma << mApi.name(port) << \" = \" << parentName << mApi.name(mappedPort) << \"\\n\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tout.decIndent();\n\t\t\t\t\tout() << \";\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid HascolGenerator::generateFunctor(Id const &id, OutFile &out)\n{\n\tout() << \"process \" << mApi.name(id) << \" (\\n\";\n\n\tout.incIndent();\n\n\tforeach (Id const child, mApi.children(id))\n\t\tif (child.element() == \"FunctorFormalParameter\")\n\t\t\tgenerateFunctorFormalParameter(child, out);\n\n\tout.decIndent();\n\n\tout() << \"\\t) =\\n\";\n\tgenerateProcessTypeBody(id, out);\n}\n\nvoid HascolGenerator::generateFunctorFormalParameter(Id const &id, utils::OutFile &out)\n{\n\tif (mApi.links(id).count() == 1) {\n\t\tout() << mApi.name(id) << \" : \";\n\t\tId const parameterType = mApi.otherEntityFromLink(mApi.links(id).at(0), id);\n\t\tif (mApi.name(parameterType) != \"\") {\n\t\t\tout() << mApi.name(parameterType);\n\t\t} else {\n\t\t\tout() << \"\\n\";\n\t\t\tout.incIndent();\n\t\t\tgenerateProcessTypeBody(parameterType, out);\n\t\t\tout.decIndent();\n\t\t}\n\t} else {\n\t\tout() << mApi.name(id) << \"\\n\";\n\t}\n}\n\nvoid HascolGenerator::generateProcessOperation(Id const &id, OutFile &out)\n{\n\tout() << mApi.stringProperty(id, \"direction\") << \" \"\n\t\t<< mApi.name(id) << \";\\n\";\n}\n\nvoid HascolGenerator::generateLetBinding(Id const &id, utils::OutFile &out)\n{\n\tout() << \"let \" << mApi.name(id) << \";\\n\";\n}\n\nvoid HascolGenerator::generateResource(Id const &id, bool first, OutFile &out)\n{\n\tout() << (first ? \"\" : \", \") << mApi.name(id) << \"\\n\";\n}\n\nvoid HascolGenerator::generateActivity(Id const &id, utils::OutFile &out)\n{\n\tforeach (Id const element, mApi.children(id)) {\n\t\tif (element.element() == \"HascolActivity_Group\") {\n\t\t\tout() << \"group {\\n\";\n\t\t\tout.incIndent();\n\t\t\tgenerateActivity(element, out);\n\t\t\tout.decIndent();\n\t\t\tout() << \"}\\n\";\n\t\t} else if (element.element() == \"HascolActivity_HandlerStart\")\n\t\t\tgenerateHandler(element, out);\n\t}\n}\n\nvoid HascolGenerator::generateHandler(Id const &id, utils::OutFile &out)\n{\n\tout() << mApi.stringProperty(id, \"trigger\") << \"\\n\";\n\tout() << \"{\\n\";\n\n\tout.incIndent();\n\tgenerateChain(id, out);\n\tout.decIndent();\n\n\tout() << \"}\\n\";\n}\n\nId HascolGenerator::generateChain(Id const &startNode, utils::OutFile &out)\n{\n\tId currentId = startNode;\n\twhile (mApi.outgoingLinks(currentId).count() > 0) {\n\n\t\tif (mApi.incomingLinks(currentId).count() > 1)\n\t\t\treturn currentId;\n\n\t\tif (currentId.element() == \"HascolActivity_DecisionNode\") {\n\t\t\tcurrentId = generateIf(currentId, out);\n\t\t} else if (mApi.outgoingLinks(currentId).count() > 1) {\n\t\t\tgenerateActivityNode(currentId, out);\n\t\t\tId chainEndId;\n\t\t\tbool wasOutgoingLink = false;\n\t\t\tforeach (Id linkId, mApi.outgoingLinks(currentId)) {\n\t\t\t\tif (wasOutgoingLink)\n\t\t\t\t\tout() << \"|\\n\";\n\t\t\t\twasOutgoingLink = true;\n\t\t\t\tId chainBeginId = mApi.otherEntityFromLink(linkId, currentId);\n\t\t\t\tchainEndId = generateChain(chainBeginId, out);\n\t\t\t}\n\t\t\tcurrentId = chainEndId;\n\t\t}\n\n\t\tgenerateActivityNode(currentId, out);\n\n\t\tif (mApi.outgoingLinks(currentId).count() > 0) {\n\t\t\tId const link = mApi.outgoingLinks(currentId)[0]; \/\/ Последовательный участок цепочки.\n\t\t\tcurrentId = mApi.otherEntityFromLink(link, currentId);\n\t\t}\n\t}\n\treturn currentId;\n}\n\nvoid HascolGenerator::generateActivityNode(Id const &id, utils::OutFile &out)\n{\n\tif (id.element() == \"HascolActivity_SendSignalAction\") {\n\t\tout() << \"send \" << mApi.name(id) << \"\\n\";\n\t} else if (id.element() == \"HascolActivity_InformSignalAction\") {\n\t\tout() << \"inform \" << mApi.name(id) << \"\\n\";\n\t} else if (id.element() == \"HascolActivity_Action\") {\n\t\tout() << mApi.name(id) << \"\\n\";\n\t}\n}\n\nId HascolGenerator::generateIf(Id const &id, utils::OutFile &out)\n{\n\tId const thenLink = mApi.outgoingLinks(id)[0];\n\tout() << \"if \" << mApi.stringProperty(thenLink, \"guard\") << \" then {\\n\";\n\tout.incIndent();\n\tId const thenChainEnd = generateChain(mApi.otherEntityFromLink(thenLink, id), out);\n\tId const elseLink = mApi.outgoingLinks(id)[1];\n\tId const elseNode = mApi.otherEntityFromLink(elseLink, id);\n\tif (elseNode != thenChainEnd) {\n\t\tout.decIndent();\n\t\tout() << \"} else {\\n\";\n\t\tout.incIndent();\n\t\tgenerateChain(elseNode, out);\n\t}\n\tout.decIndent();\n\tout() << \"} fi\\n\";\n\treturn thenChainEnd;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"OptionParser.h\"\n\n#ifdef WIN32\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# include \n# include \n#else\n# include \n# include \n# include \n# include \n#endif\n\n\nbool get_executable_directory(std::string &buffer) {\n#ifdef WIN32\n char name[MAX_PATH];\n if (!GetModuleFileName(NULL, name, MAX_PATH))\n return false;\n PathRemoveFileSpec(name);\n buffer = name;\n return true;\n#else\n char path[512];\n int ch = readlink(\"\/proc\/self\/exe\", path, 512);\n if (ch != -1) {\n path[ch] = 0;\n buffer = path;\n buffer = buffer.substr(0, buffer.find_last_of(\"\/\"));\n }\n return ch != -1;\n#endif\n}\n\nvoid replace(std::string &string, const std::string &find, const std::string &replace) {\n size_t index = 0;\n while (true) {\n index = string.find(find, index);\n if (index == std::string::npos)\n break;\n\n string.replace(index, find.length(), replace);\n index += replace.length();\n }\n}\n\nstd::string get_home_directory() {\n static std::string home;\n \n if (!home.empty())\n return home;\n \n char *env = getenv(\"HOME\");\n if (env)\n return home = env;\n#ifdef WIN32\n env = getenv(\"USERPROFILE\");\n if (env)\n return home = env;\n \n home = getenv(\"HOMEDRIVE\");\n home += getenv(\"HOMEPATH\");\n return home;\n#else\n struct passwd *pw = getpwuid(getuid());\n return home = pw->pw_dir;\n#endif\n}\n\nstd::string expanduser(const std::string &path) {\n std::string copy(path);\n replace(copy, \"~\", get_home_directory());\n return copy;\n}\n\nvoid add_cow_path_if_exists(std::vector &cowpath, const std::string &path) {\n#ifdef WIN32\n if (PathIsDirectory(path.c_str()))\n cowpath.push_back(path);\n#else\n struct stat buf;\n if (stat(path.c_str(), &buf) == 0 && S_ISDIR(buf.st_mode))\n cowpath.push_back(path);\n#endif\n}\n\nvoid add_default_cowpath(std::vector &cowpath) {\n std::string path;\n if (!get_executable_directory(path))\n return;\n \n add_cow_path_if_exists(cowpath, expanduser(\"~\/.cows\"));\n add_cow_path_if_exists(cowpath, expanduser(\"~\/cows\"));\n add_cow_path_if_exists(cowpath, path + \"\/..\/share\/cows\");\n add_cow_path_if_exists(cowpath, path + \"\/..\/share\/cows\");\n add_cow_path_if_exists(cowpath, \"\/usr\/share\/cows\");\n add_cow_path_if_exists(cowpath, \"\/usr\/local\/share\/cows\");\n add_cow_path_if_exists(cowpath, path + \"\/cows\");\n}\n\nbool file_exist(const std::string &file) {\n#ifdef WIN32\n return PathFileExists(file.c_str());\n#else\n struct stat buf;\n return stat(file.c_str(), &buf) == 0 && S_ISREG(buf.st_mode);\n#endif\n}\n\nbool endswith(std::string const &string, std::string const &ending) {\n if (string.length() >= ending.length()) {\n return !string.compare(string.length() - ending.length(), ending.length(), ending);\n } else {\n return false;\n }\n}\n\nbool startswith(std::string const &string, std::string const &ending) {\n if (string.length() >= ending.length()) {\n return !string.compare(0, ending.length(), ending);\n } else {\n return false;\n }\n}\n\nstd::string findcow(const std::vector &cowpath, const std::string &cow) {\n if (file_exist(cow))\n return cow;\n for (auto i = cowpath.cbegin(); i < cowpath.cend(); ++i) {\n std::string check = *i + \"\/\" + cow;\n if (file_exist(check))\n return check;\n }\n if (endswith(cow, \".cow\"))\n throw std::string(\"Cow exists not: \") + cow;\n return findcow(cowpath, cow + \".cow\");\n}\n\nstatic inline std::string <rim(std::string &s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n return s;\n}\n\nstatic inline std::string &rtrim(std::string &s) {\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n}\n\nstatic inline std::string &trim(std::string &s) {\n return ltrim(rtrim(s));\n}\n\nint isnewline(int ch) {\n switch (ch) {\n case '\\r':\n case '\\n':\n case '\\f':\n return 1;\n }\n return 0;\n}\n\nstd::string loadcow(const std::string &file, const std::string &thoughts,\n const std::string &eyes, const std::string &tongue) {\n if (!file_exist(file))\n throw std::string(\"Can't find cow: \") + file;\n std::string cow, buf;\n \n try {\n std::ifstream cowfile(file);\n if (!cowfile)\n throw std::string(\"Can't open cow: \") + file;\n cowfile.exceptions(std::ifstream::badbit);\n while (std::getline(cowfile, buf))\n if (!startswith(ltrim(std::string(buf)), \"#\"))\n cow += buf + '\\n';\n cowfile.close();\n } catch (std::ifstream::failure e) {\n throw std::string(\"Can't open cow: \") + e.what();\n }\n \n if (cow.find(\"$the_cow\") != std::string::npos) {\n \/\/ Perl format, 'tis because of thee that I need regex\n std::regex cowstart(\"\\\\$the_cow\\\\s*=\\\\s*<<[\\\"']?(\\\\w+)[\\\"']?;?$\");\n std::smatch match;\n if (!regex_search(cow, match, cowstart))\n throw std::string(\"Can't find a perl cow declaration\");\n int start = match.position() + match.length(), end;\n std::string heredoc = match.str(1);\n const std::regex esc(\"[\\\\^\\\\.\\\\$\\\\|\\\\(\\\\)\\\\[\\\\]\\\\*\\\\+\\\\?\\\\\/\\\\\\\\]\");\n const std::string escaped(\"\\\\\\\\\\\\1\");\n std::regex cowend(\"^\" + std::regex_replace(heredoc, esc, escaped) + \"$\");\n if (regex_search(cow, match, cowend))\n end = match.position();\n else\n end = cow.length();\n cow = cow.substr(start, end - start);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?thoughts(?:\\\\}|\\\\b)\"), thoughts);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?eyes(?:\\\\}|\\\\b)\"), eyes);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?tongue(?:\\\\}|\\\\b)\"), tongue);\n replace(cow, \"\\\\\\\\\", \"\\\\\");\n replace(cow, \"\\\\@\", \"@\");\n cow.erase(cow.begin(), std::find_if(cow.begin(), cow.end(), std::not1(std::ptr_fun(isnewline))));\n } else {\n \/\/ Now, my own cow format, just basic formatting\n rtrim(cow);\n replace(cow, \"{thoughts}\", thoughts);\n replace(cow, \"{eyes}\", eyes);\n replace(cow, \"{tongue}\", tongue);\n }\n return cow;\n}\n\nvoid write_ballon(FILE *out, const std::vector &lines, int width, bool think=false) {\n std::stringstream formatter;\n formatter << \"%c %-\" << width << \"s %c\\n\";\n width += 2;\n std::string format = formatter.str();\n fprintf(out, \" %s \\n\", std::string(width, '_').c_str());\n if (think) {\n for (auto line = lines.cbegin(); line < lines.cend(); ++line)\n fprintf(out, format.c_str(), '(', line->c_str(), ')');\n } else if (lines.size() < 2) {\n fprintf(out, format.c_str(), '<', lines.size() ? lines[0].c_str() : \"\", '>');\n } else {\n auto line = lines.cbegin();\n auto end = lines.cend();\n --end;\n fprintf(out, format.c_str(), '\/', (line++)->c_str(), '\\\\');\n for (; line < end; ++line)\n fprintf(out, format.c_str(), '|', line->c_str(), '|');\n fprintf(out, format.c_str(), '\\\\', line->c_str(), '\/');\n }\n fprintf(out, \" %s \\n\", std::string(width, '-').c_str());\n}\n\nint wrap(const std::string& input, std::vector& result, size_t width) {\n std::string line;\n std::stringstream stream(input);\n int maxwidth = 0;\n while (stream) {\n std::string word;\n stream >> word;\n if (!word.length())\n continue;\n if (line.length() + word.length() > width) {\n rtrim(line);\n result.push_back(line);\n if (line.length() > maxwidth)\n maxwidth = line.length();\n line.clear();\n }\n line += word + \" \";\n }\n\n if (!line.empty()) {\n rtrim(line);\n result.push_back(line);\n if (line.length() > maxwidth)\n maxwidth = line.length();\n }\n return maxwidth;\n}\n\nvoid open_streams(std::string &data, const std::vector &files) {\n if (!files.size()) {\n std::stringstream stream;\n stream << std::cin.rdbuf();\n data = stream.str();\n return;\n }\n data = \"\";\n for (auto file = files.cbegin(); file < files.cend(); ++file) {\n if (*file == \"-\") {\n std::stringstream stream;\n stream << std::cin.rdbuf();\n data += stream.str();\n continue;\n }\n std::ifstream stream;\n stream.exceptions(std::ifstream::badbit);\n try {\n stream.open(*file);\n std::stringstream string;\n string << stream.rdbuf();\n data += string.str();\n } catch (std::ifstream::failure e) {\n std::cerr << \"Can't open file: \" << *file << \": \" << e.what() << std::endl;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n optparse::OptionParser parser = optparse::OptionParser()\n .description(\"C++ reimplementation of the classic cowsay.\");\n parser.set_defaults(\"eyes\", \"oo\");\n parser.set_defaults(\"tongue\", \"\");\n parser.set_defaults(\"thoughts\", strstr(argv[0], \"think\") ? \"o\" : \"\\\\\");\n parser.add_option(\"-b\", \"--borg\"). action(\"store_const\").dest(\"eyes\").set_const(\"==\");\n parser.add_option(\"-d\", \"--dead\"). action(\"store_const\").dest(\"eyes\").set_const(\"xx\");\n parser.add_option(\"-g\", \"--greedy\"). action(\"store_const\").dest(\"eyes\").set_const(\"$$\");\n parser.add_option(\"-p\", \"--paranoid\").action(\"store_const\").dest(\"eyes\").set_const(\"@@\");\n parser.add_option(\"-s\", \"--stoned\"). action(\"store_const\").dest(\"eyes\").set_const(\"**\");\n parser.add_option(\"-t\", \"--tired\"). action(\"store_const\").dest(\"eyes\").set_const(\"--\");\n parser.add_option(\"-w\", \"--wired\"). action(\"store_const\").dest(\"eyes\").set_const(\"OO\");\n parser.add_option(\"-y\", \"--young\"). action(\"store_const\").dest(\"eyes\").set_const(\"..\");\n parser.add_option(\"-e\", \"--eyes\"). action(\"store\").dest(\"eyes\");\n parser.add_option(\"-T\", \"--tongue\"). action(\"store\").dest(\"tongue\");\n parser.add_option(\"-l\", \"--list\").action(\"store_true\").dest(\"list\")\n .help(\"displays cow file location\");\n parser.add_option(\"-f\", \"--file\").action(\"store\").dest(\"file\")\n .set_default(\"default.cow\").help(\"cow file, searches in cowpath. \"\n \".cow is automatically appended\");\n parser.add_option(\"-W\", \"--wrap\").action(\"store\").type(\"int\").dest(\"wrap\")\n .set_default(70).help(\"wraps the cow text, default 70\");\n parser.add_option(\"--thoughts\").action(\"store\").dest(\"thoughts\")\n .help(\"the method of communication cow uses. \"\n \"Default to `o` if invoked as cowthink, otherwise `\\\\`\");\n parser.add_option(\"-c\", \"--command-line\").action(\"store_true\").dest(\"cmd\")\n .help(\"treat command line as text, not files\");\n std::string cowpath_opts[5] = {\"-a\", \"--add\", \"--add-cow\", \"--add-path\", \"--add-cow-path\"};\n parser.add_option(std::vector(&cowpath_opts[0], &cowpath_opts[5]))\n .action(\"append\").dest(\"cowpath\");\n\n optparse::Values& options = parser.parse_args(argc, argv);\n std::vector args = parser.args();\n std::vector cowpath(options.all(\"cowpath\").cbegin(), options.all(\"cowpath\").cend());\n std::reverse(cowpath.begin(), cowpath.end());\n add_default_cowpath(cowpath);\n \n std::string tongue, eyes;\n eyes = (options[\"eyes\"] + \" \").substr(0, 2);\n if (options[\"tongue\"].empty()) {\n if (eyes == \"xx\" || eyes == \"**\") \/\/ one of the predefined dead faces\n tongue = \"U \";\n else\n tongue = \" \";\n } else\n tongue = (options[\"tongue\"] + \" \").substr(0, 2);\n \n if (options.is_set(\"list\")) {\n try {\n std::string path = findcow(cowpath, options[\"file\"]);\n#ifdef WIN32\n replace(path, \"\/\", \"\\\\\");\n#endif\n std::cout << path << std::endl;\n return 0;\n } catch (std::string e) {\n std::cerr << argv[0] << \": \" << e << std::endl;\n return 1;\n }\n }\n \n \/*for (auto i = cowpath.cbegin(); i < cowpath.cend(); ++i)\n std::cout << *i << '\\n';*\/\n std::string cow;\n std::vector lines;\n std::string input;\n try {\n cow = loadcow(findcow(cowpath, options[\"file\"]), options[\"thoughts\"], eyes, tongue);\n open_streams(input, args);\n int width = wrap(input, lines, options.get(\"wrap\"));\n write_ballon(stdout, lines, width, options[\"thoughts\"] == \"o\");\n fputs(cow.c_str(), stdout);\n } catch (std::string e) {\n std::cerr << argv[0] << \": \" << e << std::endl;\n }\n}\nProper word wrapping code.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"OptionParser.h\"\n\n#ifdef WIN32\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# include \n# include \n#else\n# include \n# include \n# include \n# include \n#endif\n\n\nbool get_executable_directory(std::string &buffer) {\n#ifdef WIN32\n char name[MAX_PATH];\n if (!GetModuleFileName(NULL, name, MAX_PATH))\n return false;\n PathRemoveFileSpec(name);\n buffer = name;\n return true;\n#else\n char path[512];\n int ch = readlink(\"\/proc\/self\/exe\", path, 512);\n if (ch != -1) {\n path[ch] = 0;\n buffer = path;\n buffer = buffer.substr(0, buffer.find_last_of(\"\/\"));\n }\n return ch != -1;\n#endif\n}\n\nvoid replace(std::string &string, const std::string &find, const std::string &replace) {\n size_t index = 0;\n while (true) {\n index = string.find(find, index);\n if (index == std::string::npos)\n break;\n\n string.replace(index, find.length(), replace);\n index += replace.length();\n }\n}\n\nstd::string get_home_directory() {\n static std::string home;\n \n if (!home.empty())\n return home;\n \n char *env = getenv(\"HOME\");\n if (env)\n return home = env;\n#ifdef WIN32\n env = getenv(\"USERPROFILE\");\n if (env)\n return home = env;\n \n home = getenv(\"HOMEDRIVE\");\n home += getenv(\"HOMEPATH\");\n return home;\n#else\n struct passwd *pw = getpwuid(getuid());\n return home = pw->pw_dir;\n#endif\n}\n\nstd::string expanduser(const std::string &path) {\n std::string copy(path);\n replace(copy, \"~\", get_home_directory());\n return copy;\n}\n\nvoid add_cow_path_if_exists(std::vector &cowpath, const std::string &path) {\n#ifdef WIN32\n if (PathIsDirectory(path.c_str()))\n cowpath.push_back(path);\n#else\n struct stat buf;\n if (stat(path.c_str(), &buf) == 0 && S_ISDIR(buf.st_mode))\n cowpath.push_back(path);\n#endif\n}\n\nvoid add_default_cowpath(std::vector &cowpath) {\n std::string path;\n if (!get_executable_directory(path))\n return;\n \n add_cow_path_if_exists(cowpath, expanduser(\"~\/.cows\"));\n add_cow_path_if_exists(cowpath, expanduser(\"~\/cows\"));\n add_cow_path_if_exists(cowpath, path + \"\/..\/share\/cows\");\n add_cow_path_if_exists(cowpath, path + \"\/..\/share\/cows\");\n add_cow_path_if_exists(cowpath, \"\/usr\/share\/cows\");\n add_cow_path_if_exists(cowpath, \"\/usr\/local\/share\/cows\");\n add_cow_path_if_exists(cowpath, path + \"\/cows\");\n}\n\nbool file_exist(const std::string &file) {\n#ifdef WIN32\n return PathFileExists(file.c_str());\n#else\n struct stat buf;\n return stat(file.c_str(), &buf) == 0 && S_ISREG(buf.st_mode);\n#endif\n}\n\nbool endswith(std::string const &string, std::string const &ending) {\n if (string.length() >= ending.length()) {\n return !string.compare(string.length() - ending.length(), ending.length(), ending);\n } else {\n return false;\n }\n}\n\nbool startswith(std::string const &string, std::string const &ending) {\n if (string.length() >= ending.length()) {\n return !string.compare(0, ending.length(), ending);\n } else {\n return false;\n }\n}\n\nstd::string findcow(const std::vector &cowpath, const std::string &cow) {\n if (file_exist(cow))\n return cow;\n for (auto i = cowpath.cbegin(); i < cowpath.cend(); ++i) {\n std::string check = *i + \"\/\" + cow;\n if (file_exist(check))\n return check;\n }\n if (endswith(cow, \".cow\"))\n throw std::string(\"Cow exists not: \") + cow;\n return findcow(cowpath, cow + \".cow\");\n}\n\nstatic inline std::string <rim(std::string &s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n return s;\n}\n\nstatic inline std::string &rtrim(std::string &s) {\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n}\n\nstatic inline std::string &trim(std::string &s) {\n return ltrim(rtrim(s));\n}\n\nint isnewline(int ch) {\n switch (ch) {\n case '\\r':\n case '\\n':\n case '\\f':\n return 1;\n }\n return 0;\n}\n\nstd::string loadcow(const std::string &file, const std::string &thoughts,\n const std::string &eyes, const std::string &tongue) {\n if (!file_exist(file))\n throw std::string(\"Can't find cow: \") + file;\n std::string cow, buf;\n \n try {\n std::ifstream cowfile(file);\n if (!cowfile)\n throw std::string(\"Can't open cow: \") + file;\n cowfile.exceptions(std::ifstream::badbit);\n while (std::getline(cowfile, buf))\n if (!startswith(ltrim(std::string(buf)), \"#\"))\n cow += buf + '\\n';\n cowfile.close();\n } catch (std::ifstream::failure e) {\n throw std::string(\"Can't open cow: \") + e.what();\n }\n \n if (cow.find(\"$the_cow\") != std::string::npos) {\n \/\/ Perl format, 'tis because of thee that I need regex\n std::regex cowstart(\"\\\\$the_cow\\\\s*=\\\\s*<<[\\\"']?(\\\\w+)[\\\"']?;?$\");\n std::smatch match;\n if (!regex_search(cow, match, cowstart))\n throw std::string(\"Can't find a perl cow declaration\");\n int start = match.position() + match.length(), end;\n std::string heredoc = match.str(1);\n const std::regex esc(\"[\\\\^\\\\.\\\\$\\\\|\\\\(\\\\)\\\\[\\\\]\\\\*\\\\+\\\\?\\\\\/\\\\\\\\]\");\n const std::string escaped(\"\\\\\\\\\\\\1\");\n std::regex cowend(\"^\" + std::regex_replace(heredoc, esc, escaped) + \"$\");\n if (regex_search(cow, match, cowend))\n end = match.position();\n else\n end = cow.length();\n cow = cow.substr(start, end - start);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?thoughts(?:\\\\}|\\\\b)\"), thoughts);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?eyes(?:\\\\}|\\\\b)\"), eyes);\n cow = std::regex_replace(cow, std::regex(\"\\\\$\\\\{?tongue(?:\\\\}|\\\\b)\"), tongue);\n replace(cow, \"\\\\\\\\\", \"\\\\\");\n replace(cow, \"\\\\@\", \"@\");\n cow.erase(cow.begin(), std::find_if(cow.begin(), cow.end(), std::not1(std::ptr_fun(isnewline))));\n } else {\n \/\/ Now, my own cow format, just basic formatting\n rtrim(cow);\n replace(cow, \"{thoughts}\", thoughts);\n replace(cow, \"{eyes}\", eyes);\n replace(cow, \"{tongue}\", tongue);\n }\n return cow;\n}\n\nvoid write_ballon(FILE *out, const std::vector &lines, int width, bool think=false) {\n std::stringstream formatter;\n formatter << \"%c %-\" << width << \"s %c\\n\";\n width += 2;\n std::string format = formatter.str();\n fprintf(out, \" %s \\n\", std::string(width, '_').c_str());\n if (think) {\n for (auto line = lines.cbegin(); line < lines.cend(); ++line)\n fprintf(out, format.c_str(), '(', line->c_str(), ')');\n } else if (lines.size() < 2) {\n fprintf(out, format.c_str(), '<', lines.size() ? lines[0].c_str() : \"\", '>');\n } else {\n auto line = lines.cbegin();\n auto end = lines.cend();\n --end;\n fprintf(out, format.c_str(), '\/', (line++)->c_str(), '\\\\');\n for (; line < end; ++line)\n fprintf(out, format.c_str(), '|', line->c_str(), '|');\n fprintf(out, format.c_str(), '\\\\', line->c_str(), '\/');\n }\n fprintf(out, \" %s \\n\", std::string(width, '-').c_str());\n}\n\nint wrap(const std::string& input, std::vector& result, size_t width) {\n std::string line;\n size_t index = 0, maxwidth = 0;\n while (index < input.length()) {\n int i = input.find_first_of(\" \\t\\n\", index);\n if (i == std::string::npos)\n i = input.length() - 1;\n if (line.length() + i - index > width) {\n rtrim(line);\n result.push_back(line);\n if (line.length() > maxwidth)\n maxwidth = line.length();\n line.clear();\n }\n line += input.substr(index, i - index) + \" \";\n if (input[i] == '\\n') {\n result.push_back(line);\n line.clear();\n }\n index = i + 1;\n }\n\n if (!line.empty()) {\n rtrim(line);\n result.push_back(line);\n if (line.length() > maxwidth)\n maxwidth = line.length();\n }\n return maxwidth;\n}\n\nvoid open_streams(std::string &data, const std::vector &files) {\n if (!files.size()) {\n std::stringstream stream;\n stream << std::cin.rdbuf();\n data = stream.str();\n return;\n }\n data = \"\";\n for (auto file = files.cbegin(); file < files.cend(); ++file) {\n if (*file == \"-\") {\n std::stringstream stream;\n stream << std::cin.rdbuf();\n data += stream.str();\n continue;\n }\n std::ifstream stream;\n stream.exceptions(std::ifstream::badbit);\n try {\n stream.open(*file);\n std::stringstream string;\n string << stream.rdbuf();\n data += string.str();\n } catch (std::ifstream::failure e) {\n std::cerr << \"Can't open file: \" << *file << \": \" << e.what() << std::endl;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n optparse::OptionParser parser = optparse::OptionParser()\n .description(\"C++ reimplementation of the classic cowsay.\");\n parser.set_defaults(\"eyes\", \"oo\");\n parser.set_defaults(\"tongue\", \"\");\n parser.set_defaults(\"thoughts\", strstr(argv[0], \"think\") ? \"o\" : \"\\\\\");\n parser.add_option(\"-b\", \"--borg\"). action(\"store_const\").dest(\"eyes\").set_const(\"==\");\n parser.add_option(\"-d\", \"--dead\"). action(\"store_const\").dest(\"eyes\").set_const(\"xx\");\n parser.add_option(\"-g\", \"--greedy\"). action(\"store_const\").dest(\"eyes\").set_const(\"$$\");\n parser.add_option(\"-p\", \"--paranoid\").action(\"store_const\").dest(\"eyes\").set_const(\"@@\");\n parser.add_option(\"-s\", \"--stoned\"). action(\"store_const\").dest(\"eyes\").set_const(\"**\");\n parser.add_option(\"-t\", \"--tired\"). action(\"store_const\").dest(\"eyes\").set_const(\"--\");\n parser.add_option(\"-w\", \"--wired\"). action(\"store_const\").dest(\"eyes\").set_const(\"OO\");\n parser.add_option(\"-y\", \"--young\"). action(\"store_const\").dest(\"eyes\").set_const(\"..\");\n parser.add_option(\"-e\", \"--eyes\"). action(\"store\").dest(\"eyes\");\n parser.add_option(\"-T\", \"--tongue\"). action(\"store\").dest(\"tongue\");\n parser.add_option(\"-l\", \"--list\").action(\"store_true\").dest(\"list\")\n .help(\"displays cow file location\");\n parser.add_option(\"-f\", \"--file\").action(\"store\").dest(\"file\")\n .set_default(\"default.cow\").help(\"cow file, searches in cowpath. \"\n \".cow is automatically appended\");\n parser.add_option(\"-W\", \"--wrap\").action(\"store\").type(\"int\").dest(\"wrap\")\n .set_default(70).help(\"wraps the cow text, default 70\");\n parser.add_option(\"--thoughts\").action(\"store\").dest(\"thoughts\")\n .help(\"the method of communication cow uses. \"\n \"Default to `o` if invoked as cowthink, otherwise `\\\\`\");\n parser.add_option(\"-c\", \"--command-line\").action(\"store_true\").dest(\"cmd\")\n .help(\"treat command line as text, not files\");\n std::string cowpath_opts[5] = {\"-a\", \"--add\", \"--add-cow\", \"--add-path\", \"--add-cow-path\"};\n parser.add_option(std::vector(&cowpath_opts[0], &cowpath_opts[5]))\n .action(\"append\").dest(\"cowpath\");\n\n optparse::Values& options = parser.parse_args(argc, argv);\n std::vector args = parser.args();\n std::vector cowpath(options.all(\"cowpath\").cbegin(), options.all(\"cowpath\").cend());\n std::reverse(cowpath.begin(), cowpath.end());\n add_default_cowpath(cowpath);\n \n std::string tongue, eyes;\n eyes = (options[\"eyes\"] + \" \").substr(0, 2);\n if (options[\"tongue\"].empty()) {\n if (eyes == \"xx\" || eyes == \"**\") \/\/ one of the predefined dead faces\n tongue = \"U \";\n else\n tongue = \" \";\n } else\n tongue = (options[\"tongue\"] + \" \").substr(0, 2);\n \n if (options.is_set(\"list\")) {\n try {\n std::string path = findcow(cowpath, options[\"file\"]);\n#ifdef WIN32\n replace(path, \"\/\", \"\\\\\");\n#endif\n std::cout << path << std::endl;\n return 0;\n } catch (std::string e) {\n std::cerr << argv[0] << \": \" << e << std::endl;\n return 1;\n }\n }\n \n \/*for (auto i = cowpath.cbegin(); i < cowpath.cend(); ++i)\n std::cout << *i << '\\n';*\/\n std::string cow;\n std::vector lines;\n std::string input;\n try {\n cow = loadcow(findcow(cowpath, options[\"file\"]), options[\"thoughts\"], eyes, tongue);\n open_streams(input, args);\n int width = wrap(input, lines, options.get(\"wrap\"));\n write_ballon(stdout, lines, width, options[\"thoughts\"] == \"o\");\n fputs(cow.c_str(), stdout);\n } catch (std::string e) {\n std::cerr << argv[0] << \": \" << e << std::endl;\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: uicommanddescription.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 16:54:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_\n#define __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_\n\n\/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble\n with solaris headers ...\n*\/\n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\nclass ConfigurationAccess_UICommand;\nclass UICommandDescription : public com::sun::star::lang::XTypeProvider ,\n public com::sun::star::lang::XServiceInfo ,\n public com::sun::star::container::XNameAccess ,\n private ThreadHelpBase , \/\/ Struct for right initalization of mutex member! Must be first of baseclasses.\n public ::cppu::OWeakObject\n{\n public:\n UICommandDescription( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n virtual ~UICommandDescription();\n\n \/\/ XInterface, XTypeProvider, XServiceInfo\n DECLARE_XINTERFACE\n DECLARE_XTYPEPROVIDER\n DECLARE_XSERVICEINFO\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )\n throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType()\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements()\n throw (::com::sun::star::uno::RuntimeException);\n\n typedef ::std::hash_map< ::rtl::OUString,\n ::rtl::OUString,\n OUStringHashCode,\n ::std::equal_to< ::rtl::OUString > > ModuleToCommandFileMap;\n\n typedef ::std::hash_map< ::rtl::OUString,\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >,\n OUStringHashCode,\n ::std::equal_to< ::rtl::OUString > > UICommandsHashMap;\n\n private:\n sal_Bool m_bConfigRead;\n rtl::OUString m_aPrivateResourceURL;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;\n ModuleToCommandFileMap m_aModuleToCommandFileMap;\n UICommandsHashMap m_aUICommandsHashMap;\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xGenericUICommands;\n ::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XModuleManager > m_xModuleManager;\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_SERVICES_UICOMMANDDESCRPTION_HXX_\nINTEGRATION: CWS removedrafts (1.3.156); FILE MERGED 2005\/02\/17 12:45:56 cd 1.3.156.1: #i42557# move UNOIDL types from drafts to com\/*************************************************************************\n *\n * $RCSfile: uicommanddescription.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-03-01 19:31:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_\n#define __FRAMEWORK_UIELEMENT_UICOMMANDDESCRPTION_HXX_\n\n\/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble\n with solaris headers ...\n*\/\n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\nclass ConfigurationAccess_UICommand;\nclass UICommandDescription : public com::sun::star::lang::XTypeProvider ,\n public com::sun::star::lang::XServiceInfo ,\n public com::sun::star::container::XNameAccess ,\n private ThreadHelpBase , \/\/ Struct for right initalization of mutex member! Must be first of baseclasses.\n public ::cppu::OWeakObject\n{\n public:\n UICommandDescription( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n virtual ~UICommandDescription();\n\n \/\/ XInterface, XTypeProvider, XServiceInfo\n DECLARE_XINTERFACE\n DECLARE_XTYPEPROVIDER\n DECLARE_XSERVICEINFO\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )\n throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType()\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements()\n throw (::com::sun::star::uno::RuntimeException);\n\n typedef ::std::hash_map< ::rtl::OUString,\n ::rtl::OUString,\n OUStringHashCode,\n ::std::equal_to< ::rtl::OUString > > ModuleToCommandFileMap;\n\n typedef ::std::hash_map< ::rtl::OUString,\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >,\n OUStringHashCode,\n ::std::equal_to< ::rtl::OUString > > UICommandsHashMap;\n\n private:\n sal_Bool m_bConfigRead;\n rtl::OUString m_aPrivateResourceURL;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;\n ModuleToCommandFileMap m_aModuleToCommandFileMap;\n UICommandsHashMap m_aUICommandsHashMap;\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xGenericUICommands;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager > m_xModuleManager;\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_SERVICES_UICOMMANDDESCRPTION_HXX_\n<|endoftext|>"} {"text":"\/\/ Copyright 2011, Tokyo Institute of Technology.\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is distributed under the license described in\n\/\/ LICENSE.txt.\n\/\/\n\/\/ Author: Naoya Maruyama (naoya@matsulab.is.titech.ac.jp)\n\n\n\n#include \n#include \n#include \n\n#include \"mpi.h\"\n\n#include \"runtime\/mpi_runtime2.h\"\n#include \"runtime\/grid_mpi_debug_util.h\"\n#include \"runtime\/mpi_util.h\"\n#include \"runtime\/mpi_runtime_common.h\"\n\n#include \"physis\/physis_mpi.h\"\n#include \"physis\/physis_util.h\"\n\nusing std::map;\nusing std::string;\n\nusing namespace physis::runtime;\nusing physis::IndexArray;\nusing physis::IntArray;\nusing physis::SizeArray;\n\nnamespace physis {\nnamespace runtime {\n\n\n} \/\/ namespace runtime\n} \/\/ namespace physis\n\n\n#if 0\n\nstatic PSIndex __PSGridCalcOffset3D(PSIndex x, PSIndex y,\n PSIndex z, const IndexArray &base,\n const IndexArray &size) {\n return (x - base[0]) + (y - base[1]) * size[0] +\n (z - base[2]) * size[0] * size[1];\n}\n\nstatic PSIndex __PSGridCalcOffset3D(PSIndex x, PSIndex y, PSIndex z, \n const IndexArray &size)\n __attribute__ ((unused));\nstatic PSIndex __PSGridCalcOffset3D(PSIndex x, PSIndex y, PSIndex z, \n const IndexArray &size) {\n return x + y * size[0] + z * size[0] * size[1];\n} \n\nstatic PSIndex __PSGridCalcOffset3D(PSIndex x, PSIndex y, PSIndex z, \n PSIndex xsize, PSIndex ysize)\n __attribute__ ((unused));\nstatic PSIndex __PSGridCalcOffset3D(PSIndex x, PSIndex y, PSIndex z, \n PSIndex xsize, PSIndex ysize) {\n return x + y * xsize + z * xsize * ysize;\n} \n\nstatic PSIndex __PSGridCalcOffset3D(const IndexArray &index,\n const IndexArray &size) {\n return index[0] + index[1] * size[0] + index[2] * size[0] * size[1];\n}\n\n\/\/ REFACTORING: This should be a member of GridMPI class\ntemplate \nstatic T *__PSGridGetAddr(GridMPI *gm, IndexArray indices) {\n \/\/ Use the remote grid if remote_grid_active is true.\n if (gm->remote_grid_active()) {\n GridMPI *rmg = gm->remote_grid();\n indices -= rmg->local_offset();\n return ((T*)(rmg->_data())) +\n __PSGridCalcOffset3D(indices, rmg->local_size());\n }\n \n indices -= gm->local_offset();\n bool diag = gm->halo_has_diagonal();\n for (int i = 0; i < PS_MAX_DIM; ++i) {\n if (indices[i] < 0 || indices[i] >= gm->local_size()[i]) {\n for (int j = i+1; j < PS_MAX_DIM; ++j) {\n if (diag) indices[j] += gm->halo_bw_width()[j];\n }\n PSIndex offset;\n T *buf;\n if (indices[i] < 0) {\n indices[i] += gm->halo_bw_width()[i];\n offset = __PSGridCalcOffset3D(indices, gm->halo_bw_size()[i]);\n buf = (T*)gm->_halo_peer_bw()[i];\n } else {\n indices[i] -= gm->local_size()[i];\n offset = __PSGridCalcOffset3D(indices, gm->halo_fw_size()[i]);\n buf = (T*)gm->_halo_peer_fw()[i];\n }\n return buf + offset;\n }\n }\n\n return ((T*)(gm->_data())) +\n __PSGridCalcOffset3D(indices, gm->local_size());\n}\n\ntemplate \nT *__PSGridEmitAddr3D(__PSGridMPI *g, PSIndex x, PSIndex y,\n PSIndex z) {\n GridMPI *gm = (GridMPI*)g;\n PSIndex off = __PSGridCalcOffset3D(x, y, z,\n gm->local_offset(),\n gm->local_size());\n return ((T*)(gm->_data_emit())) + off;\n} \n\ntemplate \nT *__PSGridGetAddrNoHalo3D(__PSGridMPI *g, PSIndex x, PSIndex y,\n PSIndex z) {\n GridMPI *gm = (GridMPI*)g;\n PSIndex off = __PSGridCalcOffset3D(x, y, z,\n gm->local_offset(),\n gm->local_size());\n return ((T*)(gm->_data_emit())) + off;\n} \n\ntemplate \nT __PSGridGet(__PSGridMPI *g, va_list args) {\n GridMPI *gm = (GridMPI*)g;\n int nd = gm->num_dims();\n IndexArray index;\n for (int i = 0; i < nd; ++i) {\n index[i] = va_arg(args, PSIndex);\n }\n T v;\n master->GridGet(gm, &v, index);\n return v;\n}\n#endif\n\ntemplate \nstatic T *__PSGridGetAddr(void *g, const IndexArray &indices) {\n GridMPI2 *gm = (GridMPI2*)g;\n return (T*)(gm->GetAddress(indices));\n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x) {\n return __PSGridGetAddr(g, IndexArray(x));\n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, IndexArray(x, y)); \n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x, PSIndex y,\n PSIndex z) {\n return __PSGridGetAddr(g, IndexArray(x, y, z)); \n}\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n __PSGridMPI* __PSGridNewMPI2(PSType type, int elm_size, int dim,\n const PSVectorInt size,\n int double_buffering,\n int attr,\n const PSVectorInt global_offset,\n const PSVectorInt stencil_offset_min,\n const PSVectorInt stencil_offset_max) {\n \/\/ NOTE: global_offset is not set by the translator. 0 is assumed.\n PSAssert(global_offset == NULL);\n\n \/\/ ensure the grid size is within the global grid space size\n IndexArray gsize = IndexArray(size);\n if (gsize > gs->global_size()) {\n LOG_ERROR() << \"Cannot create grids (size: \" << gsize\n << \" larger than the grid space (\"\n << gs->global_size() << \"\\n\";\n return NULL;\n }\n return ((Master2*)master)->GridNew(\n type, elm_size, dim, gsize,\n IndexArray(), stencil_offset_min, stencil_offset_max,\n attr);\n }\n\n void __PSGridSwap(void *p) {\n \/\/ Do nothing\n \/\/((GridMPI *)p)->Swap();\n return;\n }\n \n float *__PSGridGetAddrFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridGetAddrFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridGetAddrFloat3D(__PSGridMPI *g, PSIndex x, PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridGetAddrDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n\n double *__PSGridGetAddrDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n \n double *__PSGridGetAddrDouble3D(__PSGridMPI *g, PSIndex x, PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n \/\/\n \/\/ Get No Halo\n \/\/ These routines are in fact the same as the above routines. Should\n \/\/ be removed.\n \/\/\n float *__PSGridGetAddrNoHaloFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n double *__PSGridGetAddrNoHaloDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridGetAddrNoHaloFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n double *__PSGridGetAddrNoHaloDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridGetAddrNoHaloFloat3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridGetAddrNoHaloDouble3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n \/\/\n \/\/ Emit\n \/\/\n float *__PSGridEmitAddrFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n double *__PSGridEmitAddrDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridEmitAddrFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n double *__PSGridEmitAddrDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridEmitAddrFloat3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridEmitAddrDouble3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n void __PSLoadNeighbor(__PSGridMPI *g,\n const PSVectorInt offset_min,\n const PSVectorInt offset_max,\n int diagonal, int reuse, int overlap,\n int periodic) {\n if (overlap) LOG_WARNING() << \"Overlap possible, but not implemented\\n\";\n GridMPI *gm = (GridMPI*)g;\n gs->LoadNeighbor(gm, IndexArray(offset_min), IndexArray(offset_max),\n (bool)diagonal, reuse, periodic);\n return;\n }\n\n#if 0\n float __PSGridGetFloat(__PSGridMPI *g, ...) {\n va_list args;\n va_start(args, g);\n float v = __PSGridGet(g, args);\n va_end(args);\n return v;\n }\n\n double __PSGridGetDouble(__PSGridMPI *g, ...) {\n va_list args;\n va_start(args, g);\n double v = __PSGridGet(g, args);\n va_end(args);\n return v;\n }\n \n void __PSGridSet(__PSGridMPI *g, void *buf, ...) {\n GridMPI *gm = (GridMPI*)g;\n int nd = gm->num_dims();\n va_list vl;\n va_start(vl, buf);\n IndexArray index;\n for (int i = 0; i < nd; ++i) {\n index[i] = va_arg(vl, PSIndex);\n }\n va_end(vl);\n master->GridSet(gm, buf, index);\n }\n\n void __PSRegisterStencilRunClient(int id, void *fptr) {\n __PS_stencils[id] = (__PSStencilRunClientFunction)fptr;\n }\n \n\n void __PSLoadSubgrid2D(__PSGridMPI *g, \n int min_dim1, PSIndex min_offset1,\n int min_dim2, PSIndex min_offset2,\n int max_dim1, PSIndex max_offset1,\n int max_dim2, PSIndex max_offset2,\n int reuse) {\n PSAssert(min_dim1 == max_dim1);\n PSAssert(min_dim2 == max_dim2);\n int dims[] = {min_dim1, min_dim2};\n LoadSubgrid((GridMPI*)g, gs, dims, IndexArray(min_offset1, min_offset2),\n IndexArray(max_offset1, max_offset2), reuse);\n return;\n }\n \n void __PSLoadSubgrid3D(__PSGridMPI *g, \n int min_dim1, PSIndex min_offset1,\n int min_dim2, PSIndex min_offset2,\n int min_dim3, PSIndex min_offset3,\n int max_dim1, PSIndex max_offset1,\n int max_dim2, PSIndex max_offset2,\n int max_dim3, PSIndex max_offset3,\n int reuse) {\n PSAssert(min_dim1 == max_dim1);\n PSAssert(min_dim2 == max_dim2);\n PSAssert(min_dim3 == max_dim3);\n int dims[] = {min_dim1, min_dim2, min_dim3};\n LoadSubgrid((GridMPI*)g, gs, dims, IndexArray(min_offset1, min_offset2, min_offset3),\n IndexArray(max_offset1, max_offset2, max_offset3), reuse);\n return;\n }\n\n void __PSActivateRemoteGrid(__PSGridMPI *g, int active) {\n GridMPI *gm = (GridMPI*)g;\n gm->remote_grid_active() = active;\n }\n\n int __PSIsRoot() {\n return pinfo->IsRoot();\n }\n\n void __PSReduceGridFloat(void *buf, enum PSReduceOp op,\n __PSGridMPI *g) {\n master->GridReduce(buf, op, (GridMPI*)g);\n }\n \n void __PSReduceGridDouble(void *buf, enum PSReduceOp op,\n __PSGridMPI *g) {\n master->GridReduce(buf, op, (GridMPI*)g); \n }\n#endif \n\n#ifdef __cplusplus\n}\n#endif\n\nREFACTORING: Remove unused code\/\/ Copyright 2011, Tokyo Institute of Technology.\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is distributed under the license described in\n\/\/ LICENSE.txt.\n\/\/\n\/\/ Author: Naoya Maruyama (naoya@matsulab.is.titech.ac.jp)\n\n\n\n#include \n#include \n#include \n\n#include \"mpi.h\"\n\n#include \"runtime\/mpi_runtime2.h\"\n#include \"runtime\/grid_mpi_debug_util.h\"\n#include \"runtime\/mpi_util.h\"\n#include \"runtime\/mpi_runtime_common.h\"\n\n#include \"physis\/physis_mpi.h\"\n#include \"physis\/physis_util.h\"\n\nusing std::map;\nusing std::string;\n\nusing namespace physis::runtime;\nusing physis::IndexArray;\nusing physis::IntArray;\nusing physis::SizeArray;\n\nnamespace physis {\nnamespace runtime {\n\n\n} \/\/ namespace runtime\n} \/\/ namespace physis\n\n\ntemplate \nstatic T *__PSGridGetAddr(void *g, const IndexArray &indices) {\n GridMPI2 *gm = (GridMPI2*)g;\n return (T*)(gm->GetAddress(indices));\n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x) {\n return __PSGridGetAddr(g, IndexArray(x));\n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, IndexArray(x, y)); \n}\ntemplate \nstatic T *__PSGridGetAddr(void *g, PSIndex x, PSIndex y,\n PSIndex z) {\n return __PSGridGetAddr(g, IndexArray(x, y, z)); \n}\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n __PSGridMPI* __PSGridNewMPI2(PSType type, int elm_size, int dim,\n const PSVectorInt size,\n int double_buffering,\n int attr,\n const PSVectorInt global_offset,\n const PSVectorInt stencil_offset_min,\n const PSVectorInt stencil_offset_max) {\n \/\/ NOTE: global_offset is not set by the translator. 0 is assumed.\n PSAssert(global_offset == NULL);\n\n \/\/ ensure the grid size is within the global grid space size\n IndexArray gsize = IndexArray(size);\n if (gsize > gs->global_size()) {\n LOG_ERROR() << \"Cannot create grids (size: \" << gsize\n << \" larger than the grid space (\"\n << gs->global_size() << \"\\n\";\n return NULL;\n }\n return ((Master2*)master)->GridNew(\n type, elm_size, dim, gsize,\n IndexArray(), stencil_offset_min, stencil_offset_max,\n attr);\n }\n\n void __PSGridSwap(void *p) {\n \/\/ Do nothing\n \/\/((GridMPI *)p)->Swap();\n return;\n }\n \n float *__PSGridGetAddrFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridGetAddrFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridGetAddrFloat3D(__PSGridMPI *g, PSIndex x, PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridGetAddrDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n\n double *__PSGridGetAddrDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n \n double *__PSGridGetAddrDouble3D(__PSGridMPI *g, PSIndex x, PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n \/\/\n \/\/ Get No Halo\n \/\/ These routines are in fact the same as the above routines. Should\n \/\/ be removed.\n \/\/\n float *__PSGridGetAddrNoHaloFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n double *__PSGridGetAddrNoHaloDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridGetAddrNoHaloFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n double *__PSGridGetAddrNoHaloDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridGetAddrNoHaloFloat3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridGetAddrNoHaloDouble3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n \/\/\n \/\/ Emit\n \/\/\n float *__PSGridEmitAddrFloat1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n double *__PSGridEmitAddrDouble1D(__PSGridMPI *g, PSIndex x) {\n return __PSGridGetAddr(g, x);\n }\n float *__PSGridEmitAddrFloat2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n double *__PSGridEmitAddrDouble2D(__PSGridMPI *g, PSIndex x, PSIndex y) {\n return __PSGridGetAddr(g, x, y);\n }\n float *__PSGridEmitAddrFloat3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n double *__PSGridEmitAddrDouble3D(__PSGridMPI *g, PSIndex x,\n PSIndex y, PSIndex z) {\n return __PSGridGetAddr(g, x, y, z);\n }\n\n void __PSLoadNeighbor(__PSGridMPI *g,\n const PSVectorInt offset_min,\n const PSVectorInt offset_max,\n int diagonal, int reuse, int overlap,\n int periodic) {\n if (overlap) LOG_WARNING() << \"Overlap possible, but not implemented\\n\";\n GridMPI *gm = (GridMPI*)g;\n gs->LoadNeighbor(gm, IndexArray(offset_min), IndexArray(offset_max),\n (bool)diagonal, reuse, periodic);\n return;\n }\n\n#if 0\n float __PSGridGetFloat(__PSGridMPI *g, ...) {\n va_list args;\n va_start(args, g);\n float v = __PSGridGet(g, args);\n va_end(args);\n return v;\n }\n\n double __PSGridGetDouble(__PSGridMPI *g, ...) {\n va_list args;\n va_start(args, g);\n double v = __PSGridGet(g, args);\n va_end(args);\n return v;\n }\n \n void __PSGridSet(__PSGridMPI *g, void *buf, ...) {\n GridMPI *gm = (GridMPI*)g;\n int nd = gm->num_dims();\n va_list vl;\n va_start(vl, buf);\n IndexArray index;\n for (int i = 0; i < nd; ++i) {\n index[i] = va_arg(vl, PSIndex);\n }\n va_end(vl);\n master->GridSet(gm, buf, index);\n }\n \n int __PSIsRoot() {\n return pinfo->IsRoot();\n }\n\n void __PSReduceGridFloat(void *buf, enum PSReduceOp op,\n __PSGridMPI *g) {\n master->GridReduce(buf, op, (GridMPI*)g);\n }\n \n void __PSReduceGridDouble(void *buf, enum PSReduceOp op,\n __PSGridMPI *g) {\n master->GridReduce(buf, op, (GridMPI*)g); \n }\n#endif \n\n#ifdef __cplusplus\n}\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ETable.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:13:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_\n#define _CONNECTIVITY_FLAT_TABLE_HXX_\n\n#ifndef _CONNECTIVITY_FILE_TABLE_HXX_\n#include \"file\/FTable.hxx\"\n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen wg. INetURLObject\n#include \n#endif\n\n\nnamespace connectivity\n{\n namespace flat\n {\n \/\/==================================================================\n \/\/ Ableitung von String mit ueberladenen GetToken\/GetTokenCount-Methoden\n \/\/ Speziell fuer FLAT FILE-Format: Strings koennen gequotet sein\n \/\/==================================================================\n class OFlatString : public String\n {\n public:\n OFlatString(){}\n\n xub_StrLen GetTokenCount( sal_Unicode cTok = ';', sal_Unicode cStrDel = '\\0' ) const;\n void GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok = ';', sal_Unicode cStrDel = '\\0' ) const;\n };\n\n\n typedef file::OFileTable OFlatTable_BASE;\n class OFlatConnection;\n\n typedef ::std::map< ::rtl::OUString,\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>, comphelper::UStringMixLess > OContainer;\n\n class OFlatTable : public OFlatTable_BASE\n {\n \/\/ maps a row postion to a file position\n ::std::map m_aRowToFilePos;\n ::std::vector m_aTypes; \/\/ holds all type for columns just to avoid to ask the propertyset\n ::std::vector m_aPrecisions; \/\/ same as aboth\n ::std::vector m_aScales;\n OFlatString m_aCurrentLine;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xNumberFormatter;\n sal_Int32 m_nRowPos;\n sal_Int32 m_nMaxRowCount; \/\/ will be set if stream is once eof\n public:\n\n private:\n void fillColumns();\n BOOL CreateFile(const INetURLObject& aFile, BOOL& bCreateMemo);\n\n sal_Bool checkHeaderLine();\n public:\n virtual void refreshColumns();\n\n public:\n \/\/ DECLARE_CTY_DEFAULTS( OFlatTable_BASE);\n OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection);\n OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection,\n const ::rtl::OUString& _Name,\n const ::rtl::OUString& _Type,\n const ::rtl::OUString& _Description = ::rtl::OUString(),\n const ::rtl::OUString& _SchemaName = ::rtl::OUString(),\n const ::rtl::OUString& _CatalogName = ::rtl::OUString()\n );\n\n void construct(); \/\/ can throw any exception\n\n virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);\n virtual sal_Bool fetchRow(OValueRefRow& _rRow,const OSQLColumns& _rCols, sal_Bool bIsTable,sal_Bool bRetrieveData);\n\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL disposing(void);\n\n \/\/ com::sun::star::lang::XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n\n String getEntry();\n };\n }\n}\n#endif \/\/ _CONNECTIVITY_FLAT_TABLE_HXX_\n\nINTEGRATION: CWS dba202a (1.13.36); FILE MERGED 2005\/11\/25 08:33:08 oj 1.13.36.1: #126933# check if char is > 127\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ETable.hxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: obo $ $Date: 2005-12-21 13:18:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_\n#define _CONNECTIVITY_FLAT_TABLE_HXX_\n\n#ifndef _CONNECTIVITY_FILE_TABLE_HXX_\n#include \"file\/FTable.hxx\"\n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen wg. INetURLObject\n#include \n#endif\n\n\nnamespace connectivity\n{\n namespace flat\n {\n \/\/==================================================================\n \/\/ Ableitung von String mit ueberladenen GetToken\/GetTokenCount-Methoden\n \/\/ Speziell fuer FLAT FILE-Format: Strings koennen gequotet sein\n \/\/==================================================================\n class OFlatString : public String\n {\n public:\n OFlatString(){}\n\n xub_StrLen GetTokenCount( sal_Unicode cTok = ';', sal_Unicode cStrDel = '\\0' ) const;\n void GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok = ';', sal_Unicode cStrDel = '\\0' ) const;\n };\n\n\n typedef file::OFileTable OFlatTable_BASE;\n class OFlatConnection;\n\n typedef ::std::map< ::rtl::OUString,\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>, comphelper::UStringMixLess > OContainer;\n\n class OFlatTable : public OFlatTable_BASE\n {\n \/\/ maps a row postion to a file position\n ::std::map m_aRowToFilePos;\n ::std::vector m_aTypes; \/\/ holds all type for columns just to avoid to ask the propertyset\n ::std::vector m_aPrecisions; \/\/ same as aboth\n ::std::vector m_aScales;\n OFlatString m_aCurrentLine;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xNumberFormatter;\n sal_Int32 m_nRowPos;\n sal_Int32 m_nMaxRowCount; \/\/ will be set if stream is once eof\n public:\n\n private:\n void fillColumns(const ::com::sun::star::lang::Locale& _aLocale);\n BOOL CreateFile(const INetURLObject& aFile, BOOL& bCreateMemo);\n\n sal_Bool checkHeaderLine();\n public:\n virtual void refreshColumns();\n\n public:\n \/\/ DECLARE_CTY_DEFAULTS( OFlatTable_BASE);\n OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection);\n OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection,\n const ::rtl::OUString& _Name,\n const ::rtl::OUString& _Type,\n const ::rtl::OUString& _Description = ::rtl::OUString(),\n const ::rtl::OUString& _SchemaName = ::rtl::OUString(),\n const ::rtl::OUString& _CatalogName = ::rtl::OUString()\n );\n\n void construct(); \/\/ can throw any exception\n\n virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);\n virtual sal_Bool fetchRow(OValueRefRow& _rRow,const OSQLColumns& _rCols, sal_Bool bIsTable,sal_Bool bRetrieveData);\n\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL disposing(void);\n\n \/\/ com::sun::star::lang::XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n\n String getEntry();\n };\n }\n}\n#endif \/\/ _CONNECTIVITY_FLAT_TABLE_HXX_\n\n<|endoftext|>"} {"text":"#include \"interpreter.h\"\n\n#include \"details\/autoconfigurer.h\"\n#include \"details\/robotImplementations\/unrealRobotModelImplementation.h\"\n#include \"details\/robotCommunication\/bluetoothRobotCommunicationThread.h\"\n#include \"details\/robotCommunication\/usbRobotCommunicationThread.h\"\n#include \"details\/tracer.h\"\n#include \"details\/debugHelper.h\"\n\n#include \n\nusing namespace qReal;\nusing namespace interpreters::robots;\nusing namespace interpreters::robots::details;\n\nconst Id startingElementType = Id(\"RobotsMetamodel\", \"RobotsDiagram\", \"InitialNode\");\nconst Id startingElementType1 = Id(\"RobotsMetamodel\", \"RobotsDiagram\", \"InitialBlock\");\n\nInterpreter::Interpreter()\n\t: mGraphicalModelApi(NULL)\n\t, mLogicalModelApi(NULL)\n\t, mInterpretersInterface(NULL)\n\t, mState(idle)\n\t, mRobotModel(new RobotModel())\n\t, mBlocksTable(NULL)\n\t, mRobotCommunication(new RobotCommunicator(SettingsManager::value(\"valueOfCommunication\", \"bluetooth\").toString()))\n\t, mImplementationType(robotModelType::null)\n\t, mWatchListWindow(NULL)\n\t, mActionConnectToRobot(NULL)\n{\n\tmParser = NULL;\n\tmBlocksTable = NULL;\n\tmTimer = new QTimer();\n\n\tmD2RobotModel = new d2Model::D2RobotModel();\n\tmD2ModelWidget = mD2RobotModel->createModelWidget();\n\n\tconnect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot()));\n\tconnect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot()));\n\tconnect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool)));\n}\n\nvoid Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi\n\t, LogicalModelAssistInterface const &logicalModelApi\n\t, qReal::gui::MainWindowInterpretersInterface &interpretersInterface)\n{\n\tmGraphicalModelApi = &graphicalModelApi;\n\tmLogicalModelApi = &logicalModelApi;\n\tmInterpretersInterface = &interpretersInterface;\n\n\tmParser = new RobotsBlockParser(mInterpretersInterface->errorReporter());\n\tmBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser);\n\n\trobotModelType::robotModelTypeEnum const modelType = static_cast(SettingsManager::value(\"robotModel\", \"1\").toInt());\n\tTracer::debug(tracer::initialization, \"Interpreter::init\", \"Going to set robot implementation, model type is \" + DebugHelper::toString(modelType));\n\tsetRobotImplementation(modelType);\n}\n\nInterpreter::~Interpreter()\n{\n\tforeach (Thread * const thread, mThreads)\n\t\tdelete thread;\n\tdelete mBlocksTable;\n}\n\nvoid Interpreter::interpret()\n{\n\tTracer::debug(tracer::initialization, \"Interpreter::interpret\", \"Preparing for interpretation\");\n\n\tmInterpretersInterface->errorReporter()->clear();\n\n\tId const ¤tDiagramId = mInterpretersInterface->activeDiagram();\n\n\tif (!mConnected) {\n\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"No connection to robot\"));\n\t\treturn;\n\t}\n\tif (mState != idle) {\n\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"Interpreter is already running\"));\n\t\treturn;\n\t}\n\n\tmState = waitingForSensorsConfiguredToLaunch;\n\n\tmBlocksTable->setIdleForBlocks();\n\n\tId const startingElement = findStartingElement(currentDiagramId);\n\tif (startingElement == Id()) {\n\t\tmInterpretersInterface->errorReporter()->addError(tr(\"No entry point found, please add Initial Node to a diagram\"));\n\t\tmState = idle;\n\t\treturn;\n\t}\n\n\tAutoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel);\n\tif (!configurer.configure(currentDiagramId))\n\t\treturn;\n}\n\nvoid Interpreter::stopRobot()\n{\n\tmRobotModel->stopRobot();\n\tmState = idle;\n\tforeach (Thread *thread, mThreads) {\n\t\tdelete thread;\n\t\tmThreads.removeAll(thread);\n\t}\n\tmBlocksTable->setFailure();\n\t\/*mBlocksTable->clear();\n\tmThreads.clear();\n\tmTimer->stop();*\/\n}\n\nvoid Interpreter::showWatchList() {\n\tif (mWatchListWindow != NULL) {\n\t\tmWatchListWindow->close();\n\t}\n\tmWatchListWindow = new watchListWindow(mParser);\n\tmWatchListWindow->show();\n}\n\nvoid Interpreter::closeD2ModelWidget()\n{\n\tif (mD2ModelWidget)\n\t\tmD2ModelWidget->close();\n}\n\nvoid Interpreter::showD2ModelWidget(bool isVisible)\n{\n\tmD2ModelWidget->init(isVisible);\n\tmD2ModelWidget->activateWindow();\n\tmD2ModelWidget->showNormal();\n}\n\nvoid Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction)\n{\n\tmD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction);\n}\n\nvoid Interpreter::enableD2ModelWidgetRunStopButtons()\n{\n\tmD2ModelWidget->enableRunStopButtons();\n}\n\nvoid Interpreter::disableD2ModelWidgetRunStopButtons()\n{\n\tmD2ModelWidget->disableRunStopButtons();\n}\n\nvoid Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType)\n{\n\tmConnected = false;\n\trobotImplementations::AbstractRobotModelImplementation *robotImpl =\n\t\t\trobotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel);\n\tsetRobotImplementation(robotImpl);\n\tmImplementationType = implementationType;\n\tif (mImplementationType != robotModelType::real)\n\t\tmRobotModel->init();\n}\n\nvoid Interpreter::connectedSlot(bool success)\n{\n\tif (success) {\n\t\tif (mRobotModel->needsConnection()) {\n\t\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"Connected successfully\"));\n\t\t}\n\t} else {\n\t\tTracer::debug(tracer::initialization, \"Interpreter::connectedSlot\", \"Robot connection status: \" + QString::number(success));\n\t\tmInterpretersInterface->errorReporter()->addError(tr(\"Can't connect to a robot.\"));\n\t}\n\tmConnected = success;\n\tmActionConnectToRobot->setChecked(success);\n}\n\nvoid Interpreter::sensorsConfiguredSlot()\n{\n\tTracer::debug(tracer::initialization, \"Interpreter::sensorsConfiguredSlot\", \"Sensors are configured\");\n\n\tmConnected = true;\n\tmActionConnectToRobot->setChecked(mConnected);\n\n\tif (mState == waitingForSensorsConfiguredToLaunch) {\n\t\tmState = interpreting;\n\n\t\tTracer::debug(tracer::initialization, \"Interpreter::sensorsConfiguredSlot\", \"Starting interpretation\");\n\t\tmRobotModel->startInterpretation();\n\n\t\tId const ¤tDiagramId = mInterpretersInterface->activeDiagram();\n\t\tId const startingElement = findStartingElement(currentDiagramId);\n\t\tThread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement);\n\t\taddThread(initialThread);\n\t}\n}\n\nId const Interpreter::findStartingElement(Id const &diagram) const\n{\n\tIdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram);\n\n\tforeach (Id const child, children) {\n\t\tif (child.type() == startingElementType || child.type() == startingElementType1)\n\t\t\treturn child;\n\t}\n\n\treturn Id();\n}\n\nvoid Interpreter::threadStopped()\n{\n\tThread *thread = static_cast(sender());\n\n\tmThreads.removeAll(thread);\n\tdelete thread;\n\n\tif (mThreads.isEmpty()) {\n\t\tstopRobot();\n\t}\n}\n\nvoid Interpreter::newThread(details::blocks::Block * const startBlock)\n{\n\tThread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id());\n\taddThread(thread);\n}\n\nvoid Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1\n\t\t, sensorType::SensorTypeEnum const &port2\n\t\t, sensorType::SensorTypeEnum const &port3\n\t\t, sensorType::SensorTypeEnum const &port4)\n{\n\tmRobotModel->configureSensors(port1, port2, port3, port4);\n}\n\nvoid Interpreter::addThread(details::Thread * const thread)\n{\n\tmThreads.append(thread);\n\tconnect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));\n\tconnect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const)));\n\n\tthread->interpret();\n}\n\ninterpreters::robots::details::RobotModel *Interpreter::robotModel()\n{\n\treturn mRobotModel;\n}\n\nvoid Interpreter::setRobotModel(details::RobotModel * const robotModel)\n{\n\tmRobotModel = robotModel;\n}\n\nvoid Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl)\n{\n\tmRobotModel->setRobotImplementation(robotImpl);\n\tif (robotImpl)\n\t\tconnect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer()));\n}\n\nvoid Interpreter::runTimer()\n{\n\tmTimer->start(1000);\n\tconnect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()));\n\tif (mRobotModel->sensor(inputPort::port1)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port2)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port3)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port4)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n}\n\nvoid Interpreter::readSensorValues()\n{\n\tif (mState == idle)\n\t\treturn;\n\n\tif (mRobotModel->sensor(inputPort::port1))\n\t\tmRobotModel->sensor(inputPort::port1)->read();\n\tif (mRobotModel->sensor(inputPort::port2))\n\t\tmRobotModel->sensor(inputPort::port2)->read();\n\tif (mRobotModel->sensor(inputPort::port3))\n\t\tmRobotModel->sensor(inputPort::port3)->read();\n\tif (mRobotModel->sensor(inputPort::port4))\n\t\tmRobotModel->sensor(inputPort::port4)->read();\n}\n\nvoid Interpreter::slotFailure()\n{\n\tTracer::debug(tracer::autoupdatedSensorValues, \"Interpreter::slotFailure\", \"\");\n}\n\nvoid Interpreter::responseSlot1(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor1\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot2(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor2\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot3(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor3\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot4(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor4\"), sensorValue);\n}\n\nvoid Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue)\n{\n\t(*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType);\n\tTracer::debug(tracer::autoupdatedSensorValues, \"Interpreter::updateSensorValues\", sensorVariableName + QString::number(sensorValue));\n}\n\nvoid Interpreter::connectToRobot()\n{\n\tif (mConnected) {\n\t\tmRobotModel->stopRobot();\n\t\tmRobotModel->disconnectFromRobot();\n\t} else {\n\t\tmRobotModel->init();\n\t}\n\tmActionConnectToRobot->setChecked(mConnected);\n}\n\nvoid Interpreter::disconnectSlot()\n{\n\tmActionConnectToRobot->setChecked(false);\n\tmConnected = false;\n}\n\nvoid Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType)\n{\n\tsetRobotImplementation(robotModelType);\n}\n\nvoid Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName)\n{\n\tRobotCommunicationThreadInterface *communicator = NULL;\n\tif (valueOfCommunication == \"bluetooth\")\n\t\tcommunicator = new BluetoothRobotCommunicationThread();\n\telse\n\t\tcommunicator = new UsbRobotCommunicationThread();\n\n\tmRobotCommunication->setRobotCommunicationThreadObject(communicator);\n\tmRobotCommunication->setPortName(portName);\n\n\tdisconnectSlot();\n}\n\nvoid Interpreter::setConnectRobotAction(QAction *actionConnect)\n{\n\tmActionConnectToRobot = actionConnect;\n}\nfixed 2d model window#include \"interpreter.h\"\n\n#include \"details\/autoconfigurer.h\"\n#include \"details\/robotImplementations\/unrealRobotModelImplementation.h\"\n#include \"details\/robotCommunication\/bluetoothRobotCommunicationThread.h\"\n#include \"details\/robotCommunication\/usbRobotCommunicationThread.h\"\n#include \"details\/tracer.h\"\n#include \"details\/debugHelper.h\"\n\n#include \n\nusing namespace qReal;\nusing namespace interpreters::robots;\nusing namespace interpreters::robots::details;\n\nconst Id startingElementType = Id(\"RobotsMetamodel\", \"RobotsDiagram\", \"InitialNode\");\nconst Id startingElementType1 = Id(\"RobotsMetamodel\", \"RobotsDiagram\", \"InitialBlock\");\n\nInterpreter::Interpreter()\n\t: mGraphicalModelApi(NULL)\n\t, mLogicalModelApi(NULL)\n\t, mInterpretersInterface(NULL)\n\t, mState(idle)\n\t, mRobotModel(new RobotModel())\n\t, mBlocksTable(NULL)\n\t, mRobotCommunication(new RobotCommunicator(SettingsManager::value(\"valueOfCommunication\", \"bluetooth\").toString()))\n\t, mImplementationType(robotModelType::null)\n\t, mWatchListWindow(NULL)\n\t, mActionConnectToRobot(NULL)\n{\n\tmParser = NULL;\n\tmBlocksTable = NULL;\n\tmTimer = new QTimer();\n\n\tmD2RobotModel = new d2Model::D2RobotModel();\n\tmD2ModelWidget = mD2RobotModel->createModelWidget();\n\n\tconnect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot()));\n\tconnect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot()));\n\tconnect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool)));\n}\n\nvoid Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi\n\t, LogicalModelAssistInterface const &logicalModelApi\n\t, qReal::gui::MainWindowInterpretersInterface &interpretersInterface)\n{\n\tmGraphicalModelApi = &graphicalModelApi;\n\tmLogicalModelApi = &logicalModelApi;\n\tmInterpretersInterface = &interpretersInterface;\n\n\tmParser = new RobotsBlockParser(mInterpretersInterface->errorReporter());\n\tmBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser);\n\n\trobotModelType::robotModelTypeEnum const modelType = static_cast(SettingsManager::value(\"robotModel\", \"1\").toInt());\n\tTracer::debug(tracer::initialization, \"Interpreter::init\", \"Going to set robot implementation, model type is \" + DebugHelper::toString(modelType));\n\tsetRobotImplementation(modelType);\n}\n\nInterpreter::~Interpreter()\n{\n\tforeach (Thread * const thread, mThreads)\n\t\tdelete thread;\n\tdelete mBlocksTable;\n}\n\nvoid Interpreter::interpret()\n{\n\tTracer::debug(tracer::initialization, \"Interpreter::interpret\", \"Preparing for interpretation\");\n\n\tmInterpretersInterface->errorReporter()->clear();\n\n\tId const ¤tDiagramId = mInterpretersInterface->activeDiagram();\n\n\tif (!mConnected) {\n\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"No connection to robot\"));\n\t\treturn;\n\t}\n\tif (mState != idle) {\n\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"Interpreter is already running\"));\n\t\treturn;\n\t}\n\n\tmState = waitingForSensorsConfiguredToLaunch;\n\n\tmBlocksTable->setIdleForBlocks();\n\n\tId const startingElement = findStartingElement(currentDiagramId);\n\tif (startingElement == Id()) {\n\t\tmInterpretersInterface->errorReporter()->addError(tr(\"No entry point found, please add Initial Node to a diagram\"));\n\t\tmState = idle;\n\t\treturn;\n\t}\n\n\tAutoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel);\n\tif (!configurer.configure(currentDiagramId))\n\t\treturn;\n}\n\nvoid Interpreter::stopRobot()\n{\n\tmRobotModel->stopRobot();\n\tmState = idle;\n\tforeach (Thread *thread, mThreads) {\n\t\tdelete thread;\n\t\tmThreads.removeAll(thread);\n\t}\n\tmBlocksTable->setFailure();\n\t\/*mBlocksTable->clear();\n\tmThreads.clear();\n\tmTimer->stop();*\/\n}\n\nvoid Interpreter::showWatchList() {\n\tif (mWatchListWindow != NULL) {\n\t\tmWatchListWindow->close();\n\t}\n\tmWatchListWindow = new watchListWindow(mParser);\n\tmWatchListWindow->show();\n}\n\nvoid Interpreter::closeD2ModelWidget()\n{\n\tif (mD2ModelWidget)\n\t\tmD2ModelWidget->close();\n}\n\nvoid Interpreter::showD2ModelWidget(bool isVisible)\n{\n\tmD2ModelWidget->init(isVisible);\n\tif (isVisible) {\n\t\tmD2ModelWidget->activateWindow();\n\t\tmD2ModelWidget->showNormal();\n\t}\n}\n\nvoid Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction)\n{\n\tmD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction);\n}\n\nvoid Interpreter::enableD2ModelWidgetRunStopButtons()\n{\n\tmD2ModelWidget->enableRunStopButtons();\n}\n\nvoid Interpreter::disableD2ModelWidgetRunStopButtons()\n{\n\tmD2ModelWidget->disableRunStopButtons();\n}\n\nvoid Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType)\n{\n\tmConnected = false;\n\trobotImplementations::AbstractRobotModelImplementation *robotImpl =\n\t\t\trobotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel);\n\tsetRobotImplementation(robotImpl);\n\tmImplementationType = implementationType;\n\tif (mImplementationType != robotModelType::real)\n\t\tmRobotModel->init();\n}\n\nvoid Interpreter::connectedSlot(bool success)\n{\n\tif (success) {\n\t\tif (mRobotModel->needsConnection()) {\n\t\t\tmInterpretersInterface->errorReporter()->addInformation(tr(\"Connected successfully\"));\n\t\t}\n\t} else {\n\t\tTracer::debug(tracer::initialization, \"Interpreter::connectedSlot\", \"Robot connection status: \" + QString::number(success));\n\t\tmInterpretersInterface->errorReporter()->addError(tr(\"Can't connect to a robot.\"));\n\t}\n\tmConnected = success;\n\tmActionConnectToRobot->setChecked(success);\n}\n\nvoid Interpreter::sensorsConfiguredSlot()\n{\n\tTracer::debug(tracer::initialization, \"Interpreter::sensorsConfiguredSlot\", \"Sensors are configured\");\n\n\tmConnected = true;\n\tmActionConnectToRobot->setChecked(mConnected);\n\n\tif (mState == waitingForSensorsConfiguredToLaunch) {\n\t\tmState = interpreting;\n\n\t\tTracer::debug(tracer::initialization, \"Interpreter::sensorsConfiguredSlot\", \"Starting interpretation\");\n\t\tmRobotModel->startInterpretation();\n\n\t\tId const ¤tDiagramId = mInterpretersInterface->activeDiagram();\n\t\tId const startingElement = findStartingElement(currentDiagramId);\n\t\tThread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement);\n\t\taddThread(initialThread);\n\t}\n}\n\nId const Interpreter::findStartingElement(Id const &diagram) const\n{\n\tIdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram);\n\n\tforeach (Id const child, children) {\n\t\tif (child.type() == startingElementType || child.type() == startingElementType1)\n\t\t\treturn child;\n\t}\n\n\treturn Id();\n}\n\nvoid Interpreter::threadStopped()\n{\n\tThread *thread = static_cast(sender());\n\n\tmThreads.removeAll(thread);\n\tdelete thread;\n\n\tif (mThreads.isEmpty()) {\n\t\tstopRobot();\n\t}\n}\n\nvoid Interpreter::newThread(details::blocks::Block * const startBlock)\n{\n\tThread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id());\n\taddThread(thread);\n}\n\nvoid Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1\n\t\t, sensorType::SensorTypeEnum const &port2\n\t\t, sensorType::SensorTypeEnum const &port3\n\t\t, sensorType::SensorTypeEnum const &port4)\n{\n\tmRobotModel->configureSensors(port1, port2, port3, port4);\n}\n\nvoid Interpreter::addThread(details::Thread * const thread)\n{\n\tmThreads.append(thread);\n\tconnect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));\n\tconnect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const)));\n\n\tthread->interpret();\n}\n\ninterpreters::robots::details::RobotModel *Interpreter::robotModel()\n{\n\treturn mRobotModel;\n}\n\nvoid Interpreter::setRobotModel(details::RobotModel * const robotModel)\n{\n\tmRobotModel = robotModel;\n}\n\nvoid Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl)\n{\n\tmRobotModel->setRobotImplementation(robotImpl);\n\tif (robotImpl)\n\t\tconnect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer()));\n}\n\nvoid Interpreter::runTimer()\n{\n\tmTimer->start(1000);\n\tconnect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()));\n\tif (mRobotModel->sensor(inputPort::port1)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port2)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port3)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n\tif (mRobotModel->sensor(inputPort::port4)) {\n\t\tconnect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int)));\n\t\tconnect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));\n\t}\n}\n\nvoid Interpreter::readSensorValues()\n{\n\tif (mState == idle)\n\t\treturn;\n\n\tif (mRobotModel->sensor(inputPort::port1))\n\t\tmRobotModel->sensor(inputPort::port1)->read();\n\tif (mRobotModel->sensor(inputPort::port2))\n\t\tmRobotModel->sensor(inputPort::port2)->read();\n\tif (mRobotModel->sensor(inputPort::port3))\n\t\tmRobotModel->sensor(inputPort::port3)->read();\n\tif (mRobotModel->sensor(inputPort::port4))\n\t\tmRobotModel->sensor(inputPort::port4)->read();\n}\n\nvoid Interpreter::slotFailure()\n{\n\tTracer::debug(tracer::autoupdatedSensorValues, \"Interpreter::slotFailure\", \"\");\n}\n\nvoid Interpreter::responseSlot1(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor1\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot2(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor2\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot3(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor3\"), sensorValue);\n}\n\nvoid Interpreter::responseSlot4(int sensorValue)\n{\n\tupdateSensorValues(QObject::tr(\"Sensor4\"), sensorValue);\n}\n\nvoid Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue)\n{\n\t(*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType);\n\tTracer::debug(tracer::autoupdatedSensorValues, \"Interpreter::updateSensorValues\", sensorVariableName + QString::number(sensorValue));\n}\n\nvoid Interpreter::connectToRobot()\n{\n\tif (mConnected) {\n\t\tmRobotModel->stopRobot();\n\t\tmRobotModel->disconnectFromRobot();\n\t} else {\n\t\tmRobotModel->init();\n\t}\n\tmActionConnectToRobot->setChecked(mConnected);\n}\n\nvoid Interpreter::disconnectSlot()\n{\n\tmActionConnectToRobot->setChecked(false);\n\tmConnected = false;\n}\n\nvoid Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType)\n{\n\tsetRobotImplementation(robotModelType);\n}\n\nvoid Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName)\n{\n\tRobotCommunicationThreadInterface *communicator = NULL;\n\tif (valueOfCommunication == \"bluetooth\")\n\t\tcommunicator = new BluetoothRobotCommunicationThread();\n\telse\n\t\tcommunicator = new UsbRobotCommunicationThread();\n\n\tmRobotCommunication->setRobotCommunicationThreadObject(communicator);\n\tmRobotCommunication->setPortName(portName);\n\n\tdisconnectSlot();\n}\n\nvoid Interpreter::setConnectRobotAction(QAction *actionConnect)\n{\n\tmActionConnectToRobot = actionConnect;\n}\n<|endoftext|>"} {"text":"#include \"AT91.h\"\n\n#ifdef INCLUDE_SD\n\/\/ stm32f4\n\nstatic TinyCLR_SdCard_Provider sdCardProvider;\nstatic TinyCLR_Api_Info sdApi;\n\n#define AT91_SD_SECTOR_SIZE 512\n#define AT91_SD_TIMEOUT 5000000\n\nstruct SdController {\n int32_t controller;\n size_t sectorCount;\n\n size_t *sectorSizes;\n uint8_t *pBuffer;\n};\n\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data0_Pins[] = AT91_SD_DATA0_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data1_Pins[] = AT91_SD_DATA1_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data2_Pins[] = AT91_SD_DATA2_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data3_Pins[] = AT91_SD_DATA3_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Clk_Pins[] = AT91_SD_CLK_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Cmd_Pins[] = AT91_SD_CMD_PINS;\n\nSdController sdController[1];\n\nvoid AT91_SdCard_Interrupt(void* param) {\n SD_ProcessIRQSrc();\n}\n\nconst TinyCLR_Api_Info* AT91_SdCard_GetApi() {\n sdCardProvider.Parent = &sdApi;\n\n sdCardProvider.Acquire = &AT91_SdCard_Acquire;\n sdCardProvider.Release = &AT91_SdCard_Release;\n sdCardProvider.GetControllerCount = &AT91_SdCard_GetControllerCount;\n\n sdCardProvider.WriteSectors = &AT91_SdCard_WriteSector;\n sdCardProvider.ReadSectors = &AT91_SdCard_ReadSector;\n sdCardProvider.EraseSectors = &AT91_SdCard_EraseSector;\n sdCardProvider.IsSectorErased = &AT91_SdCard_IsSectorErased;\n sdCardProvider.GetSectorMap = &AT91_SdCard_GetSectorMap;\n\n sdApi.Author = \"GHI Electronics, LLC\";\n sdApi.Name = \"GHIElectronics.TinyCLR.NativeApis.AT91.SdCardProvider\";\n sdApi.Type = TinyCLR_Api_Type::SdCardProvider;\n sdApi.Version = 0;\n sdApi.Implementation = &sdCardProvider;\n\n return &sdApi;\n}\n\nTinyCLR_Result AT91_SdCard_Acquire(const TinyCLR_SdCard_Provider* self, int32_t controller) {\n sdController[controller].controller = controller;\n \/\/ Initialize hal layer here\n\n auto d0 = g_AT91_SdCard_Data0_Pins[controller];\n auto d1 = g_AT91_SdCard_Data1_Pins[controller];\n auto d2 = g_AT91_SdCard_Data2_Pins[controller];\n auto d3 = g_AT91_SdCard_Data3_Pins[controller];\n auto clk = g_AT91_SdCard_Clk_Pins[controller];\n auto cmd = g_AT91_SdCard_Cmd_Pins[controller];\n\n if (!AT91_GpioInternal_OpenPin(d0.number)\n || !AT91_GpioInternal_OpenPin(d1.number)\n || !AT91_GpioInternal_OpenPin(d2.number)\n || !AT91_GpioInternal_OpenPin(d3.number)\n || !AT91_GpioInternal_OpenPin(clk.number)\n || !AT91_GpioInternal_OpenPin(cmd.number)\n )\n return TinyCLR_Result::SharingViolation;\n\n AT91_GpioInternal_ConfigurePin(d0.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d0.alternateFunction);\n AT91_GpioInternal_ConfigurePin(d1.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d1.alternateFunction);\n AT91_GpioInternal_ConfigurePin(d2.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d2.alternateFunction);\n AT91_GpioInternal_ConfigurePin(d3.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d3.alternateFunction);\n AT91_GpioInternal_ConfigurePin(clk.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::None, clk.alternateFunction);\n AT91_GpioInternal_ConfigurePin(cmd.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, cmd.alternateFunction);\n\n RCC->APB2ENR |= (1 << 11);\n\n auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);\n\n sdController[controller].pBuffer = (uint8_t*)memoryProvider->Allocate(memoryProvider, AT91_SD_SECTOR_SIZE);\n sdController[controller].sectorSizes = (size_t*)memoryProvider->Allocate(memoryProvider, sizeof(size_t));\n\n SD_DeInit();\n\n int32_t to = 2;\n\n SD_Error error = SD_Init();\n\n if (error != SD_OK) \/\/ try one more time\n return SD_Init() == SD_OK ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;\n\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_Release(const TinyCLR_SdCard_Provider* self, int32_t controller) {\n auto d0 = g_AT91_SdCard_Data0_Pins[controller];\n auto d1 = g_AT91_SdCard_Data1_Pins[controller];\n auto d2 = g_AT91_SdCard_Data2_Pins[controller];\n auto d3 = g_AT91_SdCard_Data3_Pins[controller];\n auto clk = g_AT91_SdCard_Clk_Pins[controller];\n auto cmd = g_AT91_SdCard_Cmd_Pins[controller];\n\n SD_DeInit();\n\n RCC->APB2ENR &= ~(1 << 11);\n\n auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);\n\n memoryProvider->Free(memoryProvider, sdController[controller].pBuffer);\n memoryProvider->Free(memoryProvider, sdController[controller].sectorSizes);\n\n AT91_GpioInternal_ClosePin(d0.number);\n AT91_GpioInternal_ClosePin(d1.number);\n AT91_GpioInternal_ClosePin(d2.number);\n AT91_GpioInternal_ClosePin(d3.number);\n AT91_GpioInternal_ClosePin(clk.number);\n AT91_GpioInternal_ClosePin(cmd.number);\n\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_GetControllerCount(const TinyCLR_SdCard_Provider* self, int32_t& count) {\n count = SIZEOF_ARRAY(g_AT91_SdCard_Data0_Pins);\n\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_WriteSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, const uint8_t* data, int32_t timeout) {\n int32_t index = 0;\n\n int32_t to;\n\n auto sectorCount = count;\n\n auto sectorNum = sector;\n\n uint8_t* pData = (uint8_t*)data;\n\n while (sectorCount) {\n to = timeout;\n\n while (SD_GetStatus() != SD_TRANSFER_OK && to--) {\n AT91_Time_Delay(nullptr, 1);\n }\n\n if (to > 0 && SD_WriteBlock(&pData[index], sectorNum * AT91_SD_SECTOR_SIZE, AT91_SD_SECTOR_SIZE) == SD_OK) {\n index += AT91_SD_SECTOR_SIZE;\n sectorNum++;\n sectorCount--;\n }\n else {\n SD_StopTransfer();\n }\n\n if (!to) {\n return TinyCLR_Result::InvalidOperation;\n }\n }\n\n return TinyCLR_Result::Success;\n\n}\n\nTinyCLR_Result AT91_SdCard_ReadSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, uint8_t* data, int32_t timeout) {\n int32_t index = 0;\n\n int32_t to;\n\n auto sectorCount = count;\n\n auto sectorNum = sector;\n\n while (sectorCount) {\n to = timeout;\n\n while (SD_GetStatus() != SD_TRANSFER_OK && to--) {\n AT91_Time_Delay(nullptr, 1);\n }\n\n if (to > 0 && SD_ReadBlock(&data[index], sectorNum * AT91_SD_SECTOR_SIZE, AT91_SD_SECTOR_SIZE) == SD_OK) {\n\n index += AT91_SD_SECTOR_SIZE;\n sectorNum++;\n sectorCount--;\n }\n else {\n SD_StopTransfer();\n }\n\n if (!to) {\n return TinyCLR_Result::InvalidOperation;\n }\n }\n\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_IsSectorErased(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, bool& erased) {\n erased = true;\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_EraseSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, int32_t timeout) {\n uint32_t addressStart = sector * AT91_SD_SECTOR_SIZE;\n\n uint32_t addressEnd = addressStart + (count * AT91_SD_SECTOR_SIZE);\n\n return SD_Erase(addressStart, addressEnd) == SD_OK ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;\n}\n\nTinyCLR_Result AT91_SdCard_GetSectorMap(const TinyCLR_SdCard_Provider* self, int32_t controller, const size_t*& sizes, size_t& count, bool& isUniform) {\n sdController[controller].sectorSizes[0] = AT91_SD_SECTOR_SIZE;\n\n sizes = sdController[controller].sectorSizes;\n count = SDCardInfo.CardCapacity \/ AT91_SD_SECTOR_SIZE;\n\n return TinyCLR_Result::Success;\n}\n\nTinyCLR_Result AT91_SdCard_Reset() {\n return TinyCLR_Result::Success;\n}\n#endif \/\/ INCLUDE_SDFileSystem: Returns NotImplemented for Hydra#include \"AT91.h\"\n\n#ifdef INCLUDE_SD\n\/\/ stm32f4\n\nstatic TinyCLR_SdCard_Provider sdCardProvider;\nstatic TinyCLR_Api_Info sdApi;\n\n#define AT91_SD_SECTOR_SIZE 512\n#define AT91_SD_TIMEOUT 5000000\n\nstruct SdController {\n int32_t controller;\n size_t sectorCount;\n\n size_t *sectorSizes;\n uint8_t *pBuffer;\n};\n\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data0_Pins[] = AT91_SD_DATA0_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data1_Pins[] = AT91_SD_DATA1_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data2_Pins[] = AT91_SD_DATA2_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Data3_Pins[] = AT91_SD_DATA3_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Clk_Pins[] = AT91_SD_CLK_PINS;\nstatic const AT91_Gpio_Pin g_AT91_SdCard_Cmd_Pins[] = AT91_SD_CMD_PINS;\n\nSdController sdController[1];\n\nvoid AT91_SdCard_Interrupt(void* param) {\n SD_ProcessIRQSrc();\n}\n\nconst TinyCLR_Api_Info* AT91_SdCard_GetApi() {\n sdCardProvider.Parent = &sdApi;\n\n sdCardProvider.Acquire = &AT91_SdCard_Acquire;\n sdCardProvider.Release = &AT91_SdCard_Release;\n sdCardProvider.GetControllerCount = &AT91_SdCard_GetControllerCount;\n\n sdCardProvider.WriteSectors = &AT91_SdCard_WriteSector;\n sdCardProvider.ReadSectors = &AT91_SdCard_ReadSector;\n sdCardProvider.EraseSectors = &AT91_SdCard_EraseSector;\n sdCardProvider.IsSectorErased = &AT91_SdCard_IsSectorErased;\n sdCardProvider.GetSectorMap = &AT91_SdCard_GetSectorMap;\n\n sdApi.Author = \"GHI Electronics, LLC\";\n sdApi.Name = \"GHIElectronics.TinyCLR.NativeApis.AT91.SdCardProvider\";\n sdApi.Type = TinyCLR_Api_Type::SdCardProvider;\n sdApi.Version = 0;\n sdApi.Implementation = &sdCardProvider;\n\n return &sdApi;\n}\n\nTinyCLR_Result AT91_SdCard_Acquire(const TinyCLR_SdCard_Provider* self, int32_t controller) {\n sdController[controller].controller = controller;\n \/\/ Initialize hal layer here\n\n auto d0 = g_AT91_SdCard_Data0_Pins[controller];\n auto d1 = g_AT91_SdCard_Data1_Pins[controller];\n auto d2 = g_AT91_SdCard_Data2_Pins[controller];\n auto d3 = g_AT91_SdCard_Data3_Pins[controller];\n auto clk = g_AT91_SdCard_Clk_Pins[controller];\n auto cmd = g_AT91_SdCard_Cmd_Pins[controller];\n\n if (!AT91_GpioInternal_OpenPin(d0.number)\n || !AT91_GpioInternal_OpenPin(d1.number)\n || !AT91_GpioInternal_OpenPin(d2.number)\n || !AT91_GpioInternal_OpenPin(d3.number)\n || !AT91_GpioInternal_OpenPin(clk.number)\n || !AT91_GpioInternal_OpenPin(cmd.number)\n )\n return TinyCLR_Result::SharingViolation;\n\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_Release(const TinyCLR_SdCard_Provider* self, int32_t controller) {\n auto d0 = g_AT91_SdCard_Data0_Pins[controller];\n auto d1 = g_AT91_SdCard_Data1_Pins[controller];\n auto d2 = g_AT91_SdCard_Data2_Pins[controller];\n auto d3 = g_AT91_SdCard_Data3_Pins[controller];\n auto clk = g_AT91_SdCard_Clk_Pins[controller];\n auto cmd = g_AT91_SdCard_Cmd_Pins[controller];\n\n auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);\n\n memoryProvider->Free(memoryProvider, sdController[controller].pBuffer);\n memoryProvider->Free(memoryProvider, sdController[controller].sectorSizes);\n\n AT91_GpioInternal_ClosePin(d0.number);\n AT91_GpioInternal_ClosePin(d1.number);\n AT91_GpioInternal_ClosePin(d2.number);\n AT91_GpioInternal_ClosePin(d3.number);\n AT91_GpioInternal_ClosePin(clk.number);\n AT91_GpioInternal_ClosePin(cmd.number);\n\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_GetControllerCount(const TinyCLR_SdCard_Provider* self, int32_t& count) {\n count = SIZEOF_ARRAY(g_AT91_SdCard_Data0_Pins);\n\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_WriteSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, const uint8_t* data, int32_t timeout) {\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_ReadSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, uint8_t* data, int32_t timeout) {\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_IsSectorErased(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, bool& erased) {\n erased = true;\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_EraseSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, int32_t timeout) {\n uint32_t addressStart = sector * AT91_SD_SECTOR_SIZE;\n\n uint32_t addressEnd = addressStart + (count * AT91_SD_SECTOR_SIZE);\n\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_GetSectorMap(const TinyCLR_SdCard_Provider* self, int32_t controller, const size_t*& sizes, size_t& count, bool& isUniform) {\n return TinyCLR_Result::NotImplemented;\n}\n\nTinyCLR_Result AT91_SdCard_Reset() {\n return TinyCLR_Result::NotImplemented;\n}\n#endif \/\/ INCLUDE_SD<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/global.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/test.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\nTEST_SUITE(Renderer_Global_ParamArray)\n{\n TEST_CASE(GetPath_GivenItemName_ReturnsItemValue)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n const char* value = params.get_path(\"x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(GetPath_GivenParentNameAndItemName_ReturnsItemValue)\n {\n ParamArray params;\n params.push(\"parent\").insert(\"x\", 42);\n\n const char* value = params.get_path(\"parent.x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(GetPath_GivenInvalidItemName_ThrowsExceptionDictionaryItemNotFound)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,\n {\n const char* value = params.get_path(\"y\");\n });\n }\n\n TEST_CASE(GetPath_GivenInvalidParentName_ThrowsExceptionDictionaryItemNotFound)\n {\n ParamArray params;\n params.push(\"parent\").insert(\"x\", 42);\n\n EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,\n {\n const char* value = params.get_path(\"other.x\");\n });\n }\n\n TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithDifferentNames_InsertsDestIntIntoSource)\n {\n ParamArray dst;\n dst.insert(\"A\", 1);\n\n ParamArray src;\n src.insert(\"B\", 2);\n\n dst.merge(src);\n\n EXPECT_EQ(2, dst.size());\n EXPECT_EQ(1, dst.get(\"A\"));\n EXPECT_EQ(2, dst.get(\"B\"));\n }\n\n TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithSameNames_OverwritesDestValueWithSourceValue)\n {\n ParamArray dst;\n dst.insert(\"A\", 1);\n\n ParamArray src;\n src.insert(\"A\", 2);\n\n dst.merge(src);\n\n EXPECT_EQ(1, dst.size());\n EXPECT_EQ(2, dst.get(\"A\"));\n }\n\n TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithDifferentNames_MergesDestDicIntoSource)\n {\n ParamArray dst_child;\n dst_child.insert(\"AA\", 1);\n\n ParamArray dst;\n dst.dictionaries().insert(\"A\", dst_child);\n\n ParamArray src_child;\n src_child.insert(\"BB\", 2);\n\n ParamArray src;\n src.dictionaries().insert(\"B\", src_child);\n\n dst.merge(src);\n\n EXPECT_EQ(2, dst.size());\n EXPECT_EQ(1, dst.dictionary(\"A\").get(\"AA\"));\n EXPECT_EQ(2, dst.dictionary(\"B\").get(\"BB\"));\n }\n\n TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithSameNames_MergesDicContents)\n {\n ParamArray dst_child;\n dst_child.insert(\"AA\", 1);\n\n ParamArray dst;\n dst.dictionaries().insert(\"A\", dst_child);\n\n ParamArray src_child;\n src_child.insert(\"BB\", 2);\n\n ParamArray src;\n src.dictionaries().insert(\"A\", src_child);\n\n dst.merge(src);\n\n EXPECT_EQ(1, dst.size());\n EXPECT_EQ(1, dst.dictionary(\"A\").get(\"AA\"));\n EXPECT_EQ(2, dst.dictionary(\"A\").get(\"BB\"));\n }\n\n TEST_CASE(TestConstructionOfDictionaryFromParamArray)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n const Dictionary dic = params;\n\n ASSERT_EQ(1, dic.strings().size());\n EXPECT_EQ(42, dic.get(\"x\"));\n }\n}\nadded unit tests for renderer::ParamArray::insert_path().\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/global.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/test.h\"\n\n\/\/ Standard headers.\n#include \n\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\nTEST_SUITE(Renderer_Global_ParamArray)\n{\n TEST_CASE(InsertPath_GivenItemName_InsertsItem)\n {\n ParamArray params;\n params.insert_path(\"x\", 42);\n\n const char* value = params.strings().get(\"x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(InsertPath_GivenParentNameAndItemName_InsertsItem)\n {\n ParamArray params;\n params.insert_path(\"parent.x\", 42);\n\n const char* value = params.dictionaries().get(\"parent\").strings().get(\"x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(GetPath_GivenItemName_ReturnsItemValue)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n const char* value = params.get_path(\"x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(GetPath_GivenParentNameAndItemName_ReturnsItemValue)\n {\n ParamArray params;\n params.push(\"parent\").insert(\"x\", 42);\n\n const char* value = params.get_path(\"parent.x\");\n\n EXPECT_EQ(\"42\", string(value));\n }\n\n TEST_CASE(GetPath_GivenInvalidItemName_ThrowsExceptionDictionaryItemNotFound)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,\n {\n const char* value = params.get_path(\"y\");\n });\n }\n\n TEST_CASE(GetPath_GivenInvalidParentName_ThrowsExceptionDictionaryItemNotFound)\n {\n ParamArray params;\n params.push(\"parent\").insert(\"x\", 42);\n\n EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,\n {\n const char* value = params.get_path(\"other.x\");\n });\n }\n\n TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithDifferentNames_InsertsDestIntIntoSource)\n {\n ParamArray dst;\n dst.insert(\"A\", 1);\n\n ParamArray src;\n src.insert(\"B\", 2);\n\n dst.merge(src);\n\n EXPECT_EQ(2, dst.size());\n EXPECT_EQ(1, dst.get(\"A\"));\n EXPECT_EQ(2, dst.get(\"B\"));\n }\n\n TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithSameNames_OverwritesDestValueWithSourceValue)\n {\n ParamArray dst;\n dst.insert(\"A\", 1);\n\n ParamArray src;\n src.insert(\"A\", 2);\n\n dst.merge(src);\n\n EXPECT_EQ(1, dst.size());\n EXPECT_EQ(2, dst.get(\"A\"));\n }\n\n TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithDifferentNames_MergesDestDicIntoSource)\n {\n ParamArray dst_child;\n dst_child.insert(\"AA\", 1);\n\n ParamArray dst;\n dst.dictionaries().insert(\"A\", dst_child);\n\n ParamArray src_child;\n src_child.insert(\"BB\", 2);\n\n ParamArray src;\n src.dictionaries().insert(\"B\", src_child);\n\n dst.merge(src);\n\n EXPECT_EQ(2, dst.size());\n EXPECT_EQ(1, dst.dictionary(\"A\").get(\"AA\"));\n EXPECT_EQ(2, dst.dictionary(\"B\").get(\"BB\"));\n }\n\n TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithSameNames_MergesDicContents)\n {\n ParamArray dst_child;\n dst_child.insert(\"AA\", 1);\n\n ParamArray dst;\n dst.dictionaries().insert(\"A\", dst_child);\n\n ParamArray src_child;\n src_child.insert(\"BB\", 2);\n\n ParamArray src;\n src.dictionaries().insert(\"A\", src_child);\n\n dst.merge(src);\n\n EXPECT_EQ(1, dst.size());\n EXPECT_EQ(1, dst.dictionary(\"A\").get(\"AA\"));\n EXPECT_EQ(2, dst.dictionary(\"A\").get(\"BB\"));\n }\n\n TEST_CASE(TestConstructionOfDictionaryFromParamArray)\n {\n ParamArray params;\n params.insert(\"x\", 42);\n\n const Dictionary dic = params;\n\n ASSERT_EQ(1, dic.strings().size());\n EXPECT_EQ(42, dic.get(\"x\"));\n }\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef __mitkTbssImporter_cpp\n#define __mitkTbssImporter_cpp\n\n#include \"mitkTbssImporter.h\"\n#include \n#include \"mitkImagePixelReadAccessor.h\"\n\nnamespace mitk\n{\n\nTbssImage::Pointer TbssImporter::Import()\n{\n mitk::TbssImage::Pointer tbssImg = mitk::TbssImage::New();\n mitkPixelTypeMultiplex1( Import, m_InputVolume->GetPixelType(), tbssImg);\n return tbssImg;\n}\n\ntemplate \nvoid TbssImporter::Import(const mitk::PixelType , mitk::TbssImage::Pointer tbssImg)\n{\n \/\/ read all images with all_*.nii.gz\n MITK_INFO << \"called import ...\";\n m_Data = DataImageType::New();\n\n mitk::Geometry3D* geo = m_InputVolume->GetGeometry();\n mitk::Vector3D spacing = geo->GetSpacing();\n mitk::Point3D origin = geo->GetOrigin();\n\n \/\/Size size\n DataImageType::SizeType dataSize;\n dataSize[0] = m_InputVolume->GetDimension(0);\n dataSize[1] = m_InputVolume->GetDimension(1);\n dataSize[2] = m_InputVolume->GetDimension(2);\n\n m_Data->SetRegions(dataSize);\n\n \/\/ Set spacing\n DataImageType::SpacingType dataSpacing;\n dataSpacing[0] = spacing[0];\n dataSpacing[1] = spacing[1];\n dataSpacing[2] = spacing[2];\n m_Data->SetSpacing(dataSpacing);\n\n DataImageType::PointType dataOrigin;\n dataOrigin[0] = origin[0];\n dataOrigin[1] = origin[1];\n dataOrigin[2] = origin[2];\n m_Data->SetOrigin(dataOrigin);\n\n \/\/Direction must be set\n DataImageType::DirectionType dir;\n const itk::Transform* transform3D = geo->GetParametricTransform();\n itk::Transform::ParametersType p = transform3D->GetParameters();\n int t=0;\n for(int i=0; i<3; i++)\n {\n for(int j=0; j<3; j++)\n {\n dir[i][j] = p[t]; \/\/ row-major order (where the column index varies the fastest)\n t++;\n }\n }\n\n m_Data->SetDirection(dir);\n\n \/\/ Set the length to one because otherwise allocate fails. Should be changed when groups\/measurements are added\n m_Data->SetVectorLength(m_InputVolume->GetDimension(3));\n m_Data->Allocate();\n\n \/\/ Determine vector size of m_Data\n\n int vecSize = m_Data->GetVectorLength();\n\n MITK_INFO << \"vecsize \" < readTbss( m_InputVolume );\n\n for(int i=0; i pixel;\n itk::Index<3> id;\n itk::Index<4> ix;\n\n ix[0] = id[0] = i;\n ix[1] = id[1] = j;\n ix[2] = id[2] = k;\n for(int z=0; zGetPixel(id);\n pixel.SetElement(z, value);\n }\n m_Data->SetPixel(id, pixel);\n }\n }\n }\n }\n catch ( mitk::Exception& e )\n {\n MITK_ERROR << \"TbssImporter::Import: No read access to tbss image. \" << e.what() ;\n }\n\n tbssImg->SetGroupInfo(m_Groups);\n tbssImg->SetMeasurementInfo(m_MeasurementInfo);\n tbssImg->SetImage(m_Data);\n\n tbssImg->InitializeFromVectorImage();\n\n}\n\n\n}\n#endif \/\/ __mitkTbssImporter_cpp\nprevent overwriting of edited pixel\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef __mitkTbssImporter_cpp\n#define __mitkTbssImporter_cpp\n\n#include \"mitkTbssImporter.h\"\n#include \n#include \"mitkImagePixelReadAccessor.h\"\n\nnamespace mitk\n{\n\nTbssImage::Pointer TbssImporter::Import()\n{\n mitk::TbssImage::Pointer tbssImg = mitk::TbssImage::New();\n mitkPixelTypeMultiplex1( Import, m_InputVolume->GetPixelType(), tbssImg);\n return tbssImg;\n}\n\ntemplate \nvoid TbssImporter::Import(const mitk::PixelType , mitk::TbssImage::Pointer tbssImg)\n{\n \/\/ read all images with all_*.nii.gz\n MITK_INFO << \"called import ...\";\n m_Data = DataImageType::New();\n\n mitk::Geometry3D* geo = m_InputVolume->GetGeometry();\n mitk::Vector3D spacing = geo->GetSpacing();\n mitk::Point3D origin = geo->GetOrigin();\n\n \/\/Size size\n DataImageType::SizeType dataSize;\n dataSize[0] = m_InputVolume->GetDimension(0);\n dataSize[1] = m_InputVolume->GetDimension(1);\n dataSize[2] = m_InputVolume->GetDimension(2);\n\n m_Data->SetRegions(dataSize);\n\n \/\/ Set spacing\n DataImageType::SpacingType dataSpacing;\n dataSpacing[0] = spacing[0];\n dataSpacing[1] = spacing[1];\n dataSpacing[2] = spacing[2];\n m_Data->SetSpacing(dataSpacing);\n\n DataImageType::PointType dataOrigin;\n dataOrigin[0] = origin[0];\n dataOrigin[1] = origin[1];\n dataOrigin[2] = origin[2];\n m_Data->SetOrigin(dataOrigin);\n\n \/\/Direction must be set\n DataImageType::DirectionType dir;\n const itk::Transform* transform3D = geo->GetParametricTransform();\n itk::Transform::ParametersType p = transform3D->GetParameters();\n int t=0;\n for(int i=0; i<3; i++)\n {\n for(int j=0; j<3; j++)\n {\n dir[i][j] = p[t]; \/\/ row-major order (where the column index varies the fastest)\n t++;\n }\n }\n\n m_Data->SetDirection(dir);\n\n \/\/ Set the length to one because otherwise allocate fails. Should be changed when groups\/measurements are added\n m_Data->SetVectorLength(m_InputVolume->GetDimension(3));\n m_Data->Allocate();\n\n \/\/ Determine vector size of m_Data\n\n int vecSize = m_Data->GetVectorLength();\n\n MITK_INFO << \"vecsize \" < readTbss( m_InputVolume );\n\n for(int i=0; i pixel;\n itk::Index<3> id;\n itk::Index<4> ix;\n\n ix[0] = id[0] = i;\n ix[1] = id[1] = j;\n ix[2] = id[2] = k;\n\n pixel = m_Data->GetPixel(id);\n\n for(int z=0; zSetPixel(id, pixel);\n }\n }\n }\n }\n catch ( mitk::Exception& e )\n {\n MITK_ERROR << \"TbssImporter::Import: No read access to tbss image. \" << e.what() ;\n }\n\n tbssImg->SetGroupInfo(m_Groups);\n tbssImg->SetMeasurementInfo(m_MeasurementInfo);\n tbssImg->SetImage(m_Data);\n\n tbssImg->InitializeFromVectorImage();\n\n}\n\n\n}\n#endif \/\/ __mitkTbssImporter_cpp\n<|endoftext|>"} {"text":"#include \n#include \n#include \"inlineFunctions.h\"\n#include \"stringutil.h\"\n#include \"symtab.h\"\n#include \"replaceReturns.h\"\n\nvoid InlineFunctions::postProcessExpr(Expr* expr) {\n \/\/no inlining compiler flag was set on the command-line\n if (no_inline)\n return;\n \/\/function call\n if (CallExpr* fn_call = dynamic_cast(expr)) {\n if (fn_call->isPrimitive() || fn_call->opTag != OP_NONE) {\n return;\n }\n \/\/for now, only leaf getter\/setter functions will be inlined \n FnSymbol* fn_sym = fn_call->findFnSymbol(); \n if (fn_sym->hasPragma(\"inline\") && isCodegened(fn_sym)) { \n _ok_to_inline = true;\n \/\/map formal parameters to actual arguments\n Map* formal_to_actual_arg_map = createFormalToActualArgMappings(fn_call, fn_sym->formals); \n \/\/inline body if it is ok to do so even after examining the actual arguments\n if (_ok_to_inline) {\n Stmt* inlined_body = fn_sym->body->copy(true,formal_to_actual_arg_map,NULL);\n ReplaceReturns* rep_returns;\n if (fn_sym->retType && (fn_sym->retType != dtVoid)) {\n DefExpr* temp_def = createTempVariable(fn_sym->retType);\n fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));\n \/\/replace all returns in the inlined function body \n \/\/with an assignment the return expression\n rep_returns = new ReplaceReturns(temp_def->sym);\n inlined_body->traverse(rep_returns);\n \/\/inlined function\n fn_call->parentStmt->insertBefore(inlined_body);\n fn_call->replace(new Variable(temp_def->sym));\n }\n else {\n \/\/inlined function\n fn_call->parentStmt->insertBefore(inlined_body);\n fn_call->parentStmt->remove();\n }\n \/\/report inlining compiler flag was set of the command-line\n if (report_inlining)\n printf(\"chapel compiler: reporting inlining, %s function was inlined \\n\", fn_sym->name);\n }\n }\n }\n}\n\nbool InlineFunctions::isCodegened(FnSymbol* fn_sym) {\n \/\/do not inline methods that are not codegened (e.g. prelude)\n ModuleSymbol* mod_sym = fn_sym->paramScope->getModule();\n return (!fn_sym->hasPragma(\"no codegen\") && (mod_sym->modtype != MOD_INTERNAL)); \n}\n\nDefExpr* InlineFunctions::createTempVariable(Type* type, Expr* init) {\n static int id = 1;\n char* temp_name = glomstrings(2, \"_inline_temp_\", intstring(id++));\n DefExpr* temp_def = Symboltable::defineSingleVarDef(temp_name,\n type,\n init,\n VAR_NORMAL,\n VAR_VAR);\n dynamic_cast(temp_def->sym)->noDefaultInit = true;\n return temp_def;\n}\n\nbool InlineFunctions::isFormalParamOut(ParamSymbol* p_sym) {\n return ((p_sym->intent == PARAM_INOUT) || (p_sym->intent == PARAM_OUT));\n}\n\nbool InlineFunctions::isFormalParamRef(ParamSymbol* p_sym) {\n return (p_sym->intent == PARAM_REF) || dynamic_cast(p_sym->type);\n}\n\nbool InlineFunctions::isTypeVar(ParamSymbol* p_sym) {\n return (p_sym->typeVariable != NULL);\n}\n\nMap* InlineFunctions::createFormalToActualArgMappings(CallExpr* fn_call, AList* formal_params) {\n Expr* curr_arg;\n DefExpr* curr_param;\n AList* actual_args = fn_call->argList;\n \n if (actual_args) {\n curr_arg = actual_args->first();\n curr_param = formal_params->first();\n }\n \/\/go through all the actual arguments\n Map* formal_to_actual_arg_map = new Map();\n while(curr_arg) {\n bool param_ref = isFormalParamRef(dynamic_cast(curr_param->sym));\n bool param_intent_out = isFormalParamOut(dynamic_cast(curr_param->sym));\n bool typeVar = isTypeVar(dynamic_cast(curr_param->sym)); \n \/\/do not inline the function call if an argument is a ref to a expression that is no\n \/\/a variable\n Variable* variable;\n if (param_ref || typeVar) {\n variable = dynamic_cast(curr_arg);\n if (!variable) {\n _ok_to_inline = false;\n return NULL;\n }\n }\n \n \/\/create temporary variable and initialize it with the actual argument \n DefExpr* temp_def;\n if (!param_ref && !typeVar) {\n temp_def = createTempVariable(curr_arg->typeInfo(), curr_arg->copy());\n fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));\n \/\/map variable of param symbol to temp symbol so that when copy is passed the map, it\n \/\/will replace the formal parameter symbol with the temp symbol \n formal_to_actual_arg_map->put(curr_param->sym, temp_def->sym);\n }\n \/\/since a temporary variable was not created, map the actual argument to the formal parameter\n else \n formal_to_actual_arg_map->put(curr_param->sym, variable->var);\n \n \/\/copy temp back to actual arg if formal param out\n if (param_intent_out)\n if (Variable* v = dynamic_cast(curr_arg))\n fn_call->parentStmt->insertAfter(new ExprStmt(new CallExpr(OP_GETSNORM, new Variable(v->var), new Variable(temp_def->sym))));\n \n\n curr_arg = actual_args->next();\n curr_param = formal_params->next();\n }\n return formal_to_actual_arg_map;\n}\n\n\n\n\nAdded line that ensures that pragmas have been copied to function symbol for uniformity sake. Currently, pragmas sometime appear on the function symbol and sometime appear on the function definition statement.#include \n#include \n#include \"inlineFunctions.h\"\n#include \"stringutil.h\"\n#include \"symtab.h\"\n#include \"replaceReturns.h\"\n\nvoid InlineFunctions::postProcessExpr(Expr* expr) {\n \/\/no inlining compiler flag was set on the command-line\n if (no_inline)\n return;\n \/\/function call\n if (CallExpr* fn_call = dynamic_cast(expr)) {\n if (fn_call->isPrimitive() || fn_call->opTag != OP_NONE) {\n return;\n }\n FnSymbol* fn_sym = fn_call->findFnSymbol(); \n \/\/copy pragmas from function definition stmt to its function symbol\n fn_sym->copyPragmas(fn_sym->defPoint->parentStmt->pragmas);\n \/\/inline function\n if (fn_sym->hasPragma(\"inline\") && isCodegened(fn_sym)) { \n _ok_to_inline = true;\n \/\/map formal parameters to actual arguments\n Map* formal_to_actual_arg_map = createFormalToActualArgMappings(fn_call, fn_sym->formals); \n \/\/inline body if it is ok to do so even after examining the actual arguments\n if (_ok_to_inline) {\n Stmt* inlined_body = fn_sym->body->copy(true,formal_to_actual_arg_map,NULL);\n ReplaceReturns* rep_returns;\n if (fn_sym->retType && (fn_sym->retType != dtVoid)) {\n DefExpr* temp_def = createTempVariable(fn_sym->retType);\n fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));\n \/\/replace all returns in the inlined function body \n \/\/with an assignment the return expression\n rep_returns = new ReplaceReturns(temp_def->sym);\n inlined_body->traverse(rep_returns);\n \/\/inlined function\n fn_call->parentStmt->insertBefore(inlined_body);\n fn_call->replace(new Variable(temp_def->sym));\n }\n else {\n \/\/inlined function\n fn_call->parentStmt->insertBefore(inlined_body);\n fn_call->parentStmt->remove();\n }\n \/\/report inlining compiler flag was set of the command-line\n if (report_inlining)\n printf(\"chapel compiler: reporting inlining, %s function was inlined \\n\", fn_sym->name);\n }\n }\n }\n}\n\nbool InlineFunctions::isCodegened(FnSymbol* fn_sym) {\n \/\/do not inline methods that are not codegened (e.g. prelude)\n ModuleSymbol* mod_sym = fn_sym->paramScope->getModule();\n return (!fn_sym->hasPragma(\"no codegen\") && (mod_sym->modtype != MOD_INTERNAL)); \n}\n\nDefExpr* InlineFunctions::createTempVariable(Type* type, Expr* init) {\n static int id = 1;\n char* temp_name = glomstrings(2, \"_inline_temp_\", intstring(id++));\n DefExpr* temp_def = Symboltable::defineSingleVarDef(temp_name,\n type,\n init,\n VAR_NORMAL,\n VAR_VAR);\n dynamic_cast(temp_def->sym)->noDefaultInit = true;\n return temp_def;\n}\n\nbool InlineFunctions::isFormalParamOut(ParamSymbol* p_sym) {\n return ((p_sym->intent == PARAM_INOUT) || (p_sym->intent == PARAM_OUT));\n}\n\nbool InlineFunctions::isFormalParamRef(ParamSymbol* p_sym) {\n return (p_sym->intent == PARAM_REF) || dynamic_cast(p_sym->type);\n}\n\nbool InlineFunctions::isTypeVar(ParamSymbol* p_sym) {\n return (p_sym->typeVariable != NULL);\n}\n\nMap* InlineFunctions::createFormalToActualArgMappings(CallExpr* fn_call, AList* formal_params) {\n Expr* curr_arg;\n DefExpr* curr_param;\n AList* actual_args = fn_call->argList;\n \n if (actual_args) {\n curr_arg = actual_args->first();\n curr_param = formal_params->first();\n }\n \/\/go through all the actual arguments\n Map* formal_to_actual_arg_map = new Map();\n while(curr_arg) {\n bool param_ref = isFormalParamRef(dynamic_cast(curr_param->sym));\n bool param_intent_out = isFormalParamOut(dynamic_cast(curr_param->sym));\n bool typeVar = isTypeVar(dynamic_cast(curr_param->sym)); \n \/\/do not inline the function call if an argument is a ref to a expression that is no\n \/\/a variable\n Variable* variable;\n if (param_ref || typeVar) {\n variable = dynamic_cast(curr_arg);\n if (!variable) {\n _ok_to_inline = false;\n return NULL;\n }\n }\n \n \/\/create temporary variable and initialize it with the actual argument \n DefExpr* temp_def;\n if (!param_ref && !typeVar) {\n temp_def = createTempVariable(curr_arg->typeInfo(), curr_arg->copy());\n fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));\n \/\/map variable of param symbol to temp symbol so that when copy is passed the map, it\n \/\/will replace the formal parameter symbol with the temp symbol \n formal_to_actual_arg_map->put(curr_param->sym, temp_def->sym);\n }\n \/\/since a temporary variable was not created, map the actual argument to the formal parameter\n else \n formal_to_actual_arg_map->put(curr_param->sym, variable->var);\n \n \/\/copy temp back to actual arg if formal param out\n if (param_intent_out)\n if (Variable* v = dynamic_cast(curr_arg))\n fn_call->parentStmt->insertAfter(new ExprStmt(new CallExpr(OP_GETSNORM, new Variable(v->var), new Variable(temp_def->sym))));\n \n\n curr_arg = actual_args->next();\n curr_param = formal_params->next();\n }\n return formal_to_actual_arg_map;\n}\n\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2015 The Communi Project\n *\n * This test is free, and not covered by the BSD license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"ircbuffer.h\"\n#include \"ircmessage.h\"\n#include \n#include \n\nclass tst_IrcBuffer : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testDefaults();\n void testTitleNamePrefix();\n void testSticky();\n void testPersistent();\n void testReceive();\n void testDebug();\n};\n\nvoid tst_IrcBuffer::testDefaults()\n{\n IrcBuffer buffer;\n QVERIFY(buffer.title().isEmpty());\n QVERIFY(buffer.name().isEmpty());\n QVERIFY(buffer.prefix().isEmpty());\n QVERIFY(!buffer.isChannel());\n QVERIFY(!buffer.toChannel());\n QVERIFY(!buffer.connection());\n QVERIFY(!buffer.network());\n QVERIFY(!buffer.model());\n QVERIFY(!buffer.isActive());\n QVERIFY(!buffer.isSticky());\n QVERIFY(!buffer.isPersistent());\n}\n\nvoid tst_IrcBuffer::testTitleNamePrefix()\n{\n IrcBuffer buffer;\n\n QSignalSpy titleSpy(&buffer, SIGNAL(titleChanged(QString)));\n QSignalSpy nameSpy(&buffer, SIGNAL(nameChanged(QString)));\n QSignalSpy prefixSpy(&buffer, SIGNAL(prefixChanged(QString)));\n QVERIFY(titleSpy.isValid());\n QVERIFY(nameSpy.isValid());\n QVERIFY(prefixSpy.isValid());\n\n buffer.setName(\"name\");\n QCOMPARE(buffer.title(), QString(\"name\"));\n QCOMPARE(buffer.name(), QString(\"name\"));\n QCOMPARE(buffer.prefix(), QString());\n QCOMPARE(titleSpy.count(), 1);\n QCOMPARE(titleSpy.last().first().toString(), QString(\"name\"));\n QCOMPARE(nameSpy.count(), 1);\n QCOMPARE(nameSpy.last().first().toString(), QString(\"name\"));\n QCOMPARE(prefixSpy.count(), 0);\n\n buffer.setPrefix(\"prefix\");\n QCOMPARE(buffer.title(), QString(\"prefixname\"));\n QCOMPARE(buffer.name(), QString(\"name\"));\n QCOMPARE(buffer.prefix(), QString(\"prefix\"));\n QCOMPARE(titleSpy.count(), 2);\n QCOMPARE(titleSpy.last().first().toString(), QString(\"prefixname\"));\n QCOMPARE(nameSpy.count(), 1);\n QCOMPARE(prefixSpy.count(), 1);\n QCOMPARE(prefixSpy.last().first().toString(), QString(\"prefix\"));\n}\n\nvoid tst_IrcBuffer::testSticky()\n{\n IrcBuffer buffer;\n QVERIFY(!buffer.isSticky());\n\n QSignalSpy spy(&buffer, SIGNAL(stickyChanged(bool)));\n QVERIFY(spy.isValid());\n\n buffer.setSticky(true);\n QVERIFY(buffer.isSticky());\n QCOMPARE(spy.count(), 1);\n QVERIFY(spy.last().last().toBool());\n\n buffer.setSticky(false);\n QVERIFY(!buffer.isSticky());\n QCOMPARE(spy.count(), 2);\n QVERIFY(!spy.last().last().toBool());\n}\n\nvoid tst_IrcBuffer::testPersistent()\n{\n IrcBuffer buffer;\n QVERIFY(!buffer.isPersistent());\n\n QSignalSpy spy(&buffer, SIGNAL(persistentChanged(bool)));\n QVERIFY(spy.isValid());\n\n buffer.setPersistent(true);\n QVERIFY(buffer.isPersistent());\n QCOMPARE(spy.count(), 1);\n QVERIFY(spy.last().last().toBool());\n\n buffer.setPersistent(false);\n QVERIFY(!buffer.isPersistent());\n QCOMPARE(spy.count(), 2);\n QVERIFY(!spy.last().last().toBool());\n}\n\nvoid tst_IrcBuffer::testReceive()\n{\n Irc::registerMetaTypes();\n\n IrcBuffer buffer;\n\n QSignalSpy spy(&buffer, SIGNAL(messageReceived(IrcMessage*)));\n QVERIFY(spy.isValid());\n\n buffer.receiveMessage(0);\n QCOMPARE(spy.count(), 0);\n\n IrcMessage msg(0);\n buffer.receiveMessage(&msg);\n QCOMPARE(spy.count(), 1);\n QCOMPARE(spy.last().at(0).value(), &msg);\n}\n\nvoid tst_IrcBuffer::testDebug()\n{\n QString str;\n QDebug dbg(&str);\n\n dbg << static_cast(0);\n QCOMPARE(str.trimmed(), QString::fromLatin1(\"IrcBuffer(0x0)\"));\n str.clear();\n\n IrcBuffer buffer;\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+\\\\) \").exactMatch(str));\n str.clear();\n\n buffer.setObjectName(\"obj\");\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+, name=obj\\\\) \").exactMatch(str));\n str.clear();\n\n buffer.setName(\"buf\");\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+, name=obj, title=buf\\\\) \").exactMatch(str));\n str.clear();\n}\n\nQTEST_MAIN(tst_IrcBuffer)\n\n#include \"tst_ircbuffer.moc\"\nTest IrcBuffer::userData\/*\n * Copyright (C) 2008-2015 The Communi Project\n *\n * This test is free, and not covered by the BSD license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"ircbuffer.h\"\n#include \"ircmessage.h\"\n#include \n#include \n\nclass tst_IrcBuffer : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testDefaults();\n void testTitleNamePrefix();\n void testSticky();\n void testPersistent();\n void testReceive();\n void testDebug();\n void testUserData();\n};\n\nvoid tst_IrcBuffer::testDefaults()\n{\n IrcBuffer buffer;\n QVERIFY(buffer.title().isEmpty());\n QVERIFY(buffer.name().isEmpty());\n QVERIFY(buffer.prefix().isEmpty());\n QVERIFY(!buffer.isChannel());\n QVERIFY(!buffer.toChannel());\n QVERIFY(!buffer.connection());\n QVERIFY(!buffer.network());\n QVERIFY(!buffer.model());\n QVERIFY(!buffer.isActive());\n QVERIFY(!buffer.isSticky());\n QVERIFY(!buffer.isPersistent());\n QVERIFY(buffer.userData().isEmpty());\n}\n\nvoid tst_IrcBuffer::testTitleNamePrefix()\n{\n IrcBuffer buffer;\n\n QSignalSpy titleSpy(&buffer, SIGNAL(titleChanged(QString)));\n QSignalSpy nameSpy(&buffer, SIGNAL(nameChanged(QString)));\n QSignalSpy prefixSpy(&buffer, SIGNAL(prefixChanged(QString)));\n QVERIFY(titleSpy.isValid());\n QVERIFY(nameSpy.isValid());\n QVERIFY(prefixSpy.isValid());\n\n buffer.setName(\"name\");\n QCOMPARE(buffer.title(), QString(\"name\"));\n QCOMPARE(buffer.name(), QString(\"name\"));\n QCOMPARE(buffer.prefix(), QString());\n QCOMPARE(titleSpy.count(), 1);\n QCOMPARE(titleSpy.last().first().toString(), QString(\"name\"));\n QCOMPARE(nameSpy.count(), 1);\n QCOMPARE(nameSpy.last().first().toString(), QString(\"name\"));\n QCOMPARE(prefixSpy.count(), 0);\n\n buffer.setPrefix(\"prefix\");\n QCOMPARE(buffer.title(), QString(\"prefixname\"));\n QCOMPARE(buffer.name(), QString(\"name\"));\n QCOMPARE(buffer.prefix(), QString(\"prefix\"));\n QCOMPARE(titleSpy.count(), 2);\n QCOMPARE(titleSpy.last().first().toString(), QString(\"prefixname\"));\n QCOMPARE(nameSpy.count(), 1);\n QCOMPARE(prefixSpy.count(), 1);\n QCOMPARE(prefixSpy.last().first().toString(), QString(\"prefix\"));\n}\n\nvoid tst_IrcBuffer::testSticky()\n{\n IrcBuffer buffer;\n QVERIFY(!buffer.isSticky());\n\n QSignalSpy spy(&buffer, SIGNAL(stickyChanged(bool)));\n QVERIFY(spy.isValid());\n\n buffer.setSticky(true);\n QVERIFY(buffer.isSticky());\n QCOMPARE(spy.count(), 1);\n QVERIFY(spy.last().last().toBool());\n\n buffer.setSticky(false);\n QVERIFY(!buffer.isSticky());\n QCOMPARE(spy.count(), 2);\n QVERIFY(!spy.last().last().toBool());\n}\n\nvoid tst_IrcBuffer::testPersistent()\n{\n IrcBuffer buffer;\n QVERIFY(!buffer.isPersistent());\n\n QSignalSpy spy(&buffer, SIGNAL(persistentChanged(bool)));\n QVERIFY(spy.isValid());\n\n buffer.setPersistent(true);\n QVERIFY(buffer.isPersistent());\n QCOMPARE(spy.count(), 1);\n QVERIFY(spy.last().last().toBool());\n\n buffer.setPersistent(false);\n QVERIFY(!buffer.isPersistent());\n QCOMPARE(spy.count(), 2);\n QVERIFY(!spy.last().last().toBool());\n}\n\nvoid tst_IrcBuffer::testReceive()\n{\n Irc::registerMetaTypes();\n\n IrcBuffer buffer;\n\n QSignalSpy spy(&buffer, SIGNAL(messageReceived(IrcMessage*)));\n QVERIFY(spy.isValid());\n\n buffer.receiveMessage(0);\n QCOMPARE(spy.count(), 0);\n\n IrcMessage msg(0);\n buffer.receiveMessage(&msg);\n QCOMPARE(spy.count(), 1);\n QCOMPARE(spy.last().at(0).value(), &msg);\n}\n\nvoid tst_IrcBuffer::testDebug()\n{\n QString str;\n QDebug dbg(&str);\n\n dbg << static_cast(0);\n QCOMPARE(str.trimmed(), QString::fromLatin1(\"IrcBuffer(0x0)\"));\n str.clear();\n\n IrcBuffer buffer;\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+\\\\) \").exactMatch(str));\n str.clear();\n\n buffer.setObjectName(\"obj\");\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+, name=obj\\\\) \").exactMatch(str));\n str.clear();\n\n buffer.setName(\"buf\");\n dbg << &buffer;\n QVERIFY(QRegExp(\"IrcBuffer\\\\(0x[0-9A-Fa-f]+, name=obj, title=buf\\\\) \").exactMatch(str));\n str.clear();\n}\n\nvoid tst_IrcBuffer::testUserData()\n{\n QVariantMap ud;\n ud.insert(\"foo\", \"bar\");\n\n IrcBuffer buffer;\n buffer.setUserData(ud);\n QCOMPARE(buffer.userData(), ud);\n\n buffer.setUserData(QVariantMap());\n QVERIFY(buffer.userData().isEmpty());\n}\n\nQTEST_MAIN(tst_IrcBuffer)\n\n#include \"tst_ircbuffer.moc\"\n<|endoftext|>"} {"text":"\/*\n * =====================================================================================\n *\n * Filename: gaussian.cpp\n *\n * Description: \n *\n * Version: 1.0\n * Created: 11\/28\/2015 9:53:55 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Gabe Jespersen (), gzackwebs@tfwno.gf\n * Organization: \n *\n * =====================================================================================\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"gaussian.h\"\n\nusing namespace std;\n\ndouble gaussian(int base, int standardDeviation)\n{\n \/\/uses box-muller transformation or something\n double u1 = (1.0+rand())\/(1.0+RAND_MAX);\/\/generating 2 linearly random numbers between 1 & 0\n double u2 = (1.0+rand())\/(1.0+RAND_MAX);\n\n double answer = cos(8.*atan(1.)*u2)*sqrt(-2.*log(u1));\/\/uses the box-muller transformation\n answer *= standardDeviation;\/\/multiplies the value by the standard deviation\n answer += base;\/\/adds the base\n return answer;\n}\nadded comments to explain stuff\/*\n * =====================================================================================\n *\n * Filename: gaussian.cpp\n *\n * Description: \n *\n * Version: 1.0\n * Created: 11\/28\/2015 9:53:55 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Gabe Jespersen (), gzackwebs@tfwno.gf\n * Organization: \n *\n * =====================================================================================\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"gaussian.h\"\n\nusing namespace std;\n\ndouble gaussian(int base, int standardDeviation)\n{\n \/\/uses box-muller transformation or something\n double u1 = (1.0+rand())\/(1.0+RAND_MAX);\/\/generating 2 linearly random numbers between 1 & 0\n double u2 = (1.0+rand())\/(1.0+RAND_MAX);\n\n double answer = cos(8.0*atan(1.0)*u2)*sqrt(-2.0*log(u1));\/\/uses the box- \n \/\/muller transfor-\n \/\/mation\n \n \/\/using decimals \n \/\/to force it to\n \/\/be a float\n answer *= standardDeviation;\/\/multiplies the value by the standard deviation\n answer += base;\/\/adds the base\n return answer;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright © 2017 INFN Torino - INDIGO-DataCloud\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"RPCManager.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Fass.h\"\n#include \"FassLog.h\"\n#include \"RequestSystem.h\"\n#include \"RequestOneProxy.h\"\n#include \"Request.h\"\n\nRPCManager::RPCManager(\n const string& _one_endpoint,\n const string& _port,\n\/\/ int _port,\n int _max_conn,\n int _max_conn_backlog,\n int _keepalive_timeout,\n int _keepalive_max_conn,\n int _timeout,\n const string _xml_log_file,\n const string call_log_format,\n const string _listen_address,\n int _message_size):\n one_endpoint(_one_endpoint),\n port(_port),\n socket_fd(-1),\n max_conn(_max_conn),\n max_conn_backlog(_max_conn_backlog),\n keepalive_timeout(_keepalive_timeout),\n keepalive_max_conn(_keepalive_max_conn),\n timeout(_timeout),\n xml_log_file(_xml_log_file),\n listen_address(_listen_address),\n message_size(_message_size) {\n Request::set_call_log_format(call_log_format);\n\n xmlrpc_limit_set(XMLRPC_XML_SIZE_LIMIT_ID, message_size);\n\n \/\/\/ No Action Manager class, by now. Think if needed in the future\n \/\/ am.addListener(this);\n}\n\nextern \"C\" void * rm_xml_server_loop(void *arg) {\n RPCManager * rm;\n\n if ( arg == 0 ) {\n return 0;\n }\n\n rm = static_cast(arg);\n \/\/\/ Set cancel state for the thread\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);\n\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);\n\n \/\/\/ Start the server\n\n xmlrpc_c::serverAbyss::constrOpt opt = xmlrpc_c::serverAbyss::constrOpt();\n\n opt.registryP(&rm->RPCManagerRegistry);\n opt.keepaliveTimeout(rm->keepalive_timeout);\n opt.keepaliveMaxConn(rm->keepalive_max_conn);\n opt.timeout(rm->timeout);\n opt.socketFd(rm->socket_fd);\n\n if (!rm->xml_log_file.empty()) {\n opt.logFileName(rm->xml_log_file);\n }\n\n opt.maxConn(rm->max_conn);\n opt.maxConnBacklog(rm->max_conn_backlog);\n\n rm->AbyssServer = new xmlrpc_c::serverAbyss(opt);\n\n rm->AbyssServer->run();\n\n return 0;\n}\n\nvoid RPCManager::register_xml_methods(){\n \/\/ Fass& fass = Fass::instance();\n\n \/\/\/ methods go here\n \/\/ TODO(valzacc or svallero): new methods\n\n \/\/\/ System Methods\n xmlrpc_c::methodPtr system_version(new SystemVersion());\n \/\/\/ ONE Proxy Methods\n xmlrpc_c::defaultMethodPtr one_proxy(new RequestOneProxy(one_endpoint,\n message_size,\n timeout));\n \/\/ add to registry\n RPCManagerRegistry.addMethod(\"fass.system.version\", system_version);\n RPCManagerRegistry.setDefaultMethod(one_proxy);\n}\n\nbool RPCManager::start(){\n \/\/ cout << \"Starting RPC Manager...\" << endl;\n\n pthread_attr_t pattr;\n ostringstream oss;\n\n FassLog::log(\"RPCM\", Log::INFO, \"Starting RPC Manager...\");\n\n int rc = setup_socket();\n\n if ( rc != 0 ) {\n return false;\n }\n\n register_xml_methods();\n\n \/\/ Action loop\n \/\/ pthread_attr_init (&pattr);\n \/\/ pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);\n\n \/\/ pthread_create(&rm_thread,&pattr,rm_action_loop,(void *)this);\n\n \/\/\/ Server loop\n pthread_attr_init(&pattr);\n pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_JOINABLE);\n\n oss << \"Starting XML-RPC server, port \" << port << \" ...\";\n FassLog::log(\"RPCM\", Log::INFO, oss);\n\n pthread_create(&rm_xml_server_thread, &pattr, rm_xml_server_loop,\n reinterpret_cast(this));\n\n return true;\n}\n\nbool RPCManager::setup_socket() {\n int rc;\n int yes = 1;\n struct sockaddr_in rm_addr;\n\n socket_fd = socket(AF_INET, SOCK_STREAM, 0);\n\n if ( socket_fd == -1 ) {\n ostringstream oss;\n\n oss << \"Cannot open server socket: \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n return false;\n }\n\n rc = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));\n\n if ( rc == -1 ) {\n ostringstream oss;\n\n oss << \"Cannot set socket options: \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n fcntl(socket_fd, F_SETFD, FD_CLOEXEC); \/\/ set close-on-exec\n rm_addr.sin_family = AF_INET;\n \/\/ converts the unsigned short integer hostshort\n \/\/ from host byte order to network byte order\n rm_addr.sin_port = htons(atoi(port.c_str()));\n\n \/\/ converts the Internet host address cp\n \/\/ from IPv4 numbers-and-dots notation\n \/\/ into binary data in network byte order\n rc = inet_aton(listen_address.c_str(), &rm_addr.sin_addr);\n\n if ( rc == 0 ) {\n ostringstream oss;\n\n oss << \"Invalid listen address: \" << listen_address;\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n\n\n rc = bind(socket_fd, (struct sockaddr *) &(rm_addr), sizeof(struct sockaddr));\n\n if ( rc == -1) {\n ostringstream oss;\n \n oss << \"Cannot bind to \" << listen_address \n << \":\" << port << \" : \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n\n return 0;\n}\nUpdate RPCManager.cc\/**\n * Copyright © 2017 INFN Torino - INDIGO-DataCloud\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"RPCManager.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Fass.h\"\n#include \"FassLog.h\"\n#include \"RequestSystem.h\"\n#include \"RequestOneProxy.h\"\n#include \"Request.h\"\n\nRPCManager::RPCManager(\n const string& _one_endpoint,\n const string& _port,\n\/\/ int _port,\n int _max_conn,\n int _max_conn_backlog,\n int _keepalive_timeout,\n int _keepalive_max_conn,\n int _timeout,\n const string _xml_log_file,\n const string call_log_format,\n const string _listen_address,\n int _message_size):\n one_endpoint(_one_endpoint),\n port(_port),\n socket_fd(-1),\n max_conn(_max_conn),\n max_conn_backlog(_max_conn_backlog),\n keepalive_timeout(_keepalive_timeout),\n keepalive_max_conn(_keepalive_max_conn),\n timeout(_timeout),\n xml_log_file(_xml_log_file),\n listen_address(_listen_address),\n message_size(_message_size) {\n Request::set_call_log_format(call_log_format);\n\n xmlrpc_limit_set(XMLRPC_XML_SIZE_LIMIT_ID, message_size);\n\n \/\/\/ No Action Manager class, by now. Think if needed in the future\n \/\/ am.addListener(this);\n}\n\nextern \"C\" void * rm_xml_server_loop(void *arg) {\n RPCManager * rm;\n\n if ( arg == 0 ) {\n return 0;\n }\n\n rm = static_cast(arg);\n \/\/\/ Set cancel state for the thread\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);\n\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);\n\n \/\/\/ Start the server\n\n xmlrpc_c::serverAbyss::constrOpt opt = xmlrpc_c::serverAbyss::constrOpt();\n\n opt.registryP(&rm->RPCManagerRegistry);\n opt.keepaliveTimeout(rm->keepalive_timeout);\n opt.keepaliveMaxConn(rm->keepalive_max_conn);\n opt.timeout(rm->timeout);\n opt.socketFd(rm->socket_fd);\n\n if (!rm->xml_log_file.empty()) {\n opt.logFileName(rm->xml_log_file);\n }\n\n opt.maxConn(rm->max_conn);\n opt.maxConnBacklog(rm->max_conn_backlog);\n\n rm->AbyssServer = new xmlrpc_c::serverAbyss(opt);\n\n rm->AbyssServer->run();\n\n return 0;\n}\n\nvoid RPCManager::register_xml_methods() {\n \/\/ Fass& fass = Fass::instance();\n\n \/\/\/ methods go here\n \/\/ TODO(valzacc or svallero): new methods\n\n \/\/\/ System Methods\n xmlrpc_c::methodPtr system_version(new SystemVersion());\n \/\/\/ ONE Proxy Methods\n xmlrpc_c::defaultMethodPtr one_proxy(new RequestOneProxy(one_endpoint,\n message_size,\n timeout));\n \/\/ add to registry\n RPCManagerRegistry.addMethod(\"fass.system.version\", system_version);\n RPCManagerRegistry.setDefaultMethod(one_proxy);\n}\n\nbool RPCManager::start() {\n \/\/ cout << \"Starting RPC Manager...\" << endl;\n\n pthread_attr_t pattr;\n ostringstream oss;\n\n FassLog::log(\"RPCM\", Log::INFO, \"Starting RPC Manager...\");\n\n int rc = setup_socket();\n\n if ( rc != 0 ) {\n return false;\n }\n\n register_xml_methods();\n\n \/\/ Action loop\n \/\/ pthread_attr_init (&pattr);\n \/\/ pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);\n\n \/\/ pthread_create(&rm_thread,&pattr,rm_action_loop,(void *)this);\n\n \/\/\/ Server loop\n pthread_attr_init(&pattr);\n pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_JOINABLE);\n\n oss << \"Starting XML-RPC server, port \" << port << \" ...\";\n FassLog::log(\"RPCM\", Log::INFO, oss);\n\n pthread_create(&rm_xml_server_thread, &pattr, rm_xml_server_loop,\n reinterpret_cast(this));\n\n return true;\n}\n\nbool RPCManager::setup_socket() {\n int rc;\n int yes = 1;\n struct sockaddr_in rm_addr;\n\n socket_fd = socket(AF_INET, SOCK_STREAM, 0);\n\n if ( socket_fd == -1 ) {\n ostringstream oss;\n\n oss << \"Cannot open server socket: \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n return false;\n }\n\n rc = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));\n\n if ( rc == -1 ) {\n ostringstream oss;\n\n oss << \"Cannot set socket options: \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n fcntl(socket_fd, F_SETFD, FD_CLOEXEC); \/\/ set close-on-exec\n rm_addr.sin_family = AF_INET;\n \/\/ converts the unsigned short integer hostshort\n \/\/ from host byte order to network byte order\n rm_addr.sin_port = htons(atoi(port.c_str()));\n\n \/\/ converts the Internet host address cp\n \/\/ from IPv4 numbers-and-dots notation\n \/\/ into binary data in network byte order\n rc = inet_aton(listen_address.c_str(), &rm_addr.sin_addr);\n\n if ( rc == 0 ) {\n ostringstream oss;\n\n oss << \"Invalid listen address: \" << listen_address;\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n\n\n rc = bind(socket_fd, (struct sockaddr *) &(rm_addr),\n sizeof(struct sockaddr));\n\n if ( rc == -1) {\n ostringstream oss;\n oss << \"Cannot bind to \" << listen_address\n << \":\" << port << \" : \" << strerror(errno);\n FassLog::log(\"RPCM\", Log::ERROR, oss);\n\n close(socket_fd);\n\n return false;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \n#include \n\n#include \"core\/sstring.hh\"\n#include \"core\/thread.hh\"\n\n#include \"database.hh\"\n#include \"mutation_reader.hh\"\n#include \"schema_builder.hh\"\n#include \"partition_slice_builder.hh\"\n#include \"tmpdir.hh\"\n#include \"sstable_mutation_readers.hh\"\n#include \"cell_locking.hh\"\n\n#include \"tests\/test-utils.hh\"\n#include \"tests\/mutation_assertions.hh\"\n#include \"tests\/mutation_reader_assertions.hh\"\n#include \"tests\/result_set_assertions.hh\"\n#include \"tests\/simple_schema.hh\"\n#include \"tests\/sstable_utils.hh\"\n#include \"tests\/sstable_test.hh\"\n\nthread_local disk_error_signal_type commit_error;\nthread_local disk_error_signal_type general_disk_error;\n\nstruct sst_factory {\n schema_ptr s;\n sstring path;\n unsigned gen;\n int level;\n\n sst_factory(schema_ptr s, const sstring& path, unsigned gen, int level)\n : s(s)\n , path(path)\n , gen(gen)\n , level(level)\n {}\n\n sstables::shared_sstable operator()() {\n auto sst = sstables::make_sstable(s, path, gen, sstables::sstable::version_types::la, sstables::sstable::format_types::big);\n sst->set_unshared();\n\n \/\/TODO set sstable level, to make the test more interesting\n\n return sst;\n }\n};\n\nSEASTAR_TEST_CASE(combined_mutation_reader_test) {\n return seastar::async([] {\n \/\/logging::logger_registry().set_logger_level(\"database\", logging::log_level::trace);\n\n simple_schema s;\n\n const auto pkeys = s.make_pkeys(4);\n const auto ckeys = s.make_ckeys(4);\n\n std::vector base_mutations = boost::copy_range>(\n pkeys | boost::adaptors::transformed([&s](const auto& k) { return mutation(k, s.schema()); }));\n\n \/\/ Data layout:\n \/\/ d[xx]\n \/\/ b[xx][xx]c\n \/\/ a[x x]\n\n int i{0};\n\n \/\/ sstable d\n std::vector table_d_mutations;\n\n i = 1;\n table_d_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_d_mutations.back(), ckeys[i], sprint(\"val_d_%i\", i));\n\n i = 2;\n table_d_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_d_mutations.back(), ckeys[i], sprint(\"val_d_%i\", i));\n const auto t_static_row = s.add_static_row(table_d_mutations.back(), sprint(\"%i_static_val\", i));\n\n \/\/ sstable b\n std::vector table_b_mutations;\n\n i = 0;\n table_b_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_b_mutations.back(), ckeys[i], sprint(\"val_b_%i\", i));\n\n i = 1;\n table_b_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_b_mutations.back(), ckeys[i], sprint(\"val_b_%i\", i));\n\n \/\/ sstable c\n std::vector table_c_mutations;\n\n i = 2;\n table_c_mutations.emplace_back(base_mutations[i]);\n const auto t_row = s.add_row(table_c_mutations.back(), ckeys[i], sprint(\"val_c_%i\", i));\n\n i = 3;\n table_c_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_c_mutations.back(), ckeys[i], sprint(\"val_c_%i\", i));\n\n \/\/ sstable a\n std::vector table_a_mutations;\n\n i = 0;\n table_a_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_a_mutations.back(), ckeys[i], sprint(\"val_a_%i\", i));\n\n i = 3;\n table_a_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_a_mutations.back(), ckeys[i], sprint(\"val_a_%i\", i));\n\n auto tmp = make_lw_shared();\n\n std::cout << tmp->path << std::endl;\n\n unsigned gen{0};\n\n std::vector tables = {\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 0), table_a_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 1), table_b_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 1), table_c_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 2), table_d_mutations)\n };\n\n auto cs = sstables::make_compaction_strategy(sstables::compaction_strategy_type::leveled, {});\n auto sstables = make_lw_shared(cs.make_sstable_set(s.schema()));\n\n std::vector sstable_mutation_readers;\n\n for (auto table : tables) {\n sstables->insert(table);\n\n sstable_mutation_readers.emplace_back(make_mutation_reader(\n table,\n s.schema(),\n query::full_partition_range,\n query::full_slice,\n seastar::default_priority_class(),\n streamed_mutation::forwarding::no,\n ::mutation_reader::forwarding::yes));\n }\n\n auto list_reader = make_combined_reader(std::move(sstable_mutation_readers), ::mutation_reader::forwarding::yes);\n\n auto incremental_reader = make_range_sstable_reader(\n s.schema(),\n sstables,\n query::full_partition_range,\n query::full_slice,\n seastar::default_priority_class(),\n nullptr,\n streamed_mutation::forwarding::no,\n ::mutation_reader::forwarding::yes);\n\n \/\/ merge c[0] with d[1]\n i = 2;\n auto c_d_merged = mutation(pkeys[i], s.schema());\n s.add_row(c_d_merged, ckeys[i], sprint(\"val_c_%i\", i), t_row);\n s.add_static_row(c_d_merged, sprint(\"%i_static_val\", i), t_static_row);\n\n assert_that(std::move(list_reader))\n .produces(table_a_mutations.front())\n .produces(table_b_mutations[1])\n .produces(c_d_merged)\n .produces(table_a_mutations.back());\n\n assert_that(std::move(incremental_reader))\n .produces(table_a_mutations.front())\n .produces(table_b_mutations[1])\n .produces(c_d_merged)\n .produces(table_a_mutations.back());\n });\n};\ncombined_mutation_reader_test: remove leftover debug logging\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \n#include \n\n#include \"core\/sstring.hh\"\n#include \"core\/thread.hh\"\n\n#include \"database.hh\"\n#include \"mutation_reader.hh\"\n#include \"schema_builder.hh\"\n#include \"partition_slice_builder.hh\"\n#include \"tmpdir.hh\"\n#include \"sstable_mutation_readers.hh\"\n#include \"cell_locking.hh\"\n\n#include \"tests\/test-utils.hh\"\n#include \"tests\/mutation_assertions.hh\"\n#include \"tests\/mutation_reader_assertions.hh\"\n#include \"tests\/result_set_assertions.hh\"\n#include \"tests\/simple_schema.hh\"\n#include \"tests\/sstable_utils.hh\"\n#include \"tests\/sstable_test.hh\"\n\nthread_local disk_error_signal_type commit_error;\nthread_local disk_error_signal_type general_disk_error;\n\nstruct sst_factory {\n schema_ptr s;\n sstring path;\n unsigned gen;\n int level;\n\n sst_factory(schema_ptr s, const sstring& path, unsigned gen, int level)\n : s(s)\n , path(path)\n , gen(gen)\n , level(level)\n {}\n\n sstables::shared_sstable operator()() {\n auto sst = sstables::make_sstable(s, path, gen, sstables::sstable::version_types::la, sstables::sstable::format_types::big);\n sst->set_unshared();\n\n \/\/TODO set sstable level, to make the test more interesting\n\n return sst;\n }\n};\n\nSEASTAR_TEST_CASE(combined_mutation_reader_test) {\n return seastar::async([] {\n \/\/logging::logger_registry().set_logger_level(\"database\", logging::log_level::trace);\n\n simple_schema s;\n\n const auto pkeys = s.make_pkeys(4);\n const auto ckeys = s.make_ckeys(4);\n\n std::vector base_mutations = boost::copy_range>(\n pkeys | boost::adaptors::transformed([&s](const auto& k) { return mutation(k, s.schema()); }));\n\n \/\/ Data layout:\n \/\/ d[xx]\n \/\/ b[xx][xx]c\n \/\/ a[x x]\n\n int i{0};\n\n \/\/ sstable d\n std::vector table_d_mutations;\n\n i = 1;\n table_d_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_d_mutations.back(), ckeys[i], sprint(\"val_d_%i\", i));\n\n i = 2;\n table_d_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_d_mutations.back(), ckeys[i], sprint(\"val_d_%i\", i));\n const auto t_static_row = s.add_static_row(table_d_mutations.back(), sprint(\"%i_static_val\", i));\n\n \/\/ sstable b\n std::vector table_b_mutations;\n\n i = 0;\n table_b_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_b_mutations.back(), ckeys[i], sprint(\"val_b_%i\", i));\n\n i = 1;\n table_b_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_b_mutations.back(), ckeys[i], sprint(\"val_b_%i\", i));\n\n \/\/ sstable c\n std::vector table_c_mutations;\n\n i = 2;\n table_c_mutations.emplace_back(base_mutations[i]);\n const auto t_row = s.add_row(table_c_mutations.back(), ckeys[i], sprint(\"val_c_%i\", i));\n\n i = 3;\n table_c_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_c_mutations.back(), ckeys[i], sprint(\"val_c_%i\", i));\n\n \/\/ sstable a\n std::vector table_a_mutations;\n\n i = 0;\n table_a_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_a_mutations.back(), ckeys[i], sprint(\"val_a_%i\", i));\n\n i = 3;\n table_a_mutations.emplace_back(base_mutations[i]);\n s.add_row(table_a_mutations.back(), ckeys[i], sprint(\"val_a_%i\", i));\n\n auto tmp = make_lw_shared();\n\n unsigned gen{0};\n\n std::vector tables = {\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 0), table_a_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 1), table_b_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 1), table_c_mutations),\n make_sstable_containing(sst_factory(s.schema(), tmp->path, gen++, 2), table_d_mutations)\n };\n\n auto cs = sstables::make_compaction_strategy(sstables::compaction_strategy_type::leveled, {});\n auto sstables = make_lw_shared(cs.make_sstable_set(s.schema()));\n\n std::vector sstable_mutation_readers;\n\n for (auto table : tables) {\n sstables->insert(table);\n\n sstable_mutation_readers.emplace_back(make_mutation_reader(\n table,\n s.schema(),\n query::full_partition_range,\n query::full_slice,\n seastar::default_priority_class(),\n streamed_mutation::forwarding::no,\n ::mutation_reader::forwarding::yes));\n }\n\n auto list_reader = make_combined_reader(std::move(sstable_mutation_readers), ::mutation_reader::forwarding::yes);\n\n auto incremental_reader = make_range_sstable_reader(\n s.schema(),\n sstables,\n query::full_partition_range,\n query::full_slice,\n seastar::default_priority_class(),\n nullptr,\n streamed_mutation::forwarding::no,\n ::mutation_reader::forwarding::yes);\n\n \/\/ merge c[0] with d[1]\n i = 2;\n auto c_d_merged = mutation(pkeys[i], s.schema());\n s.add_row(c_d_merged, ckeys[i], sprint(\"val_c_%i\", i), t_row);\n s.add_static_row(c_d_merged, sprint(\"%i_static_val\", i), t_static_row);\n\n assert_that(std::move(list_reader))\n .produces(table_a_mutations.front())\n .produces(table_b_mutations[1])\n .produces(c_d_merged)\n .produces(table_a_mutations.back());\n\n assert_that(std::move(incremental_reader))\n .produces(table_a_mutations.front())\n .produces(table_b_mutations[1])\n .produces(c_d_merged)\n .produces(table_a_mutations.back());\n });\n};\n<|endoftext|>"} {"text":"#include \"config.h\"\n\nConfigReader::ConfigReader(std::string filename, std::string filedir) {\n\treadConfig(filename, filedir);\n}\n\nvoid ConfigReader::readConfig(std::string filename, std::string filedir) {\n\tstd::ifstream configFile;\n\tstd::string absConfFile = filedir + \"\/\" + filename;\n\tconfigFile.open(absConfFile.c_str());\n\tif (configFile.fail()) {\n\t\tstd::perror(\"Config file does not exist or could not be opened\");\n\t\tstd::exit(0);\n\t}\n\tchar configuration;\n\tint lineNumber = 1;\n\tstd::string sectionType = \"\", sectionName = \"\", varName = \"\", currentValue = \"\", concatingVar = \"\";\n\tbool inBlock = false, typingSection = false, namingSection = false, escaped = false, escapedNow = false, commentable = true, writing = false, acceptVar = false, concatable = false, concatening = false;\n\tstd::vector includes;\n\tstd::tr1::unordered_map oneBlock;\n\twhile (configFile.good()) {\n\t\tconfiguration = configFile.get();\n\t\tif (configuration == '\\n')\n\t\t\tlineNumber++;\n\t\t\n\t\tif (!inBlock && sectionType == \"\")\n\t\t\ttypingSection = true;\n\t\t\n\t\tif (commentable && configuration == '#') {\n\t\t\twhile (configuration != '\\n' && configFile.good()) {\n\t\t\t\tconfiguration = configFile.get(); \/\/ do nothing with it--ignore the line\n\t\t\t}\n\t\t\tlineNumber++; \/\/ count it as a line, since the \\n won't reach the part of the loop where the line number increments\n\t\t} else if ((configuration == ' ' || configuration == '\\t' || configuration == '\\r' || configuration == '\\n') && !writing) {\n\t\t\t\/\/ ignore whitespace that's not part of a string\n\t\t} else if (typingSection) {\n\t\t\twhile (configuration != ' ' && configFile.good()) {\n\t\t\t\tsectionType += configuration;\n\t\t\t\tconfiguration = configFile.get();\n\t\t\t}\n\t\t\ttypingSection = false;\n\t\t\tnamingSection = true;\n\t\t} else if (namingSection) {\n\t\t\twhile (configuration != ' ' && configuration != '{' && configuration != ';' && configFile.good()) {\n\t\t\t\tsectionName += configuration;\n\t\t\t\tconfiguration = configFile.get();\n\t\t\t}\n\t\t\tif (!configFile.good()) {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An error occurred reading a section name from the configuration file. This error occurred on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tnamingSection = false;\n\t\t\tif (configuration == '{') { \/\/ handle this now since next iteration will handle the next character\n\t\t\t\tinBlock = true;\n\t\t\t\tacceptVar = true;\n\t\t\t}\n\t\t\tif (configuration == ';' && sectionType == \"include\")\n\t\t\t\tincludes.push_back(sectionName);\n\t\t} else if (configuration == '{') {\n\t\t\tinBlock = true;\n\t\t\tacceptVar = true;\n\t\t} else if (configuration == '}' && !writing) {\n\t\t\tif (!inBlock) {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An end brace occurred outside a block before a corresponding opening brace existed in the configuration file. The offending brace can be found on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tinBlock = false;\n\t\t\ttypingSection = true;\n\t\t\tif (sectionType == \"server\")\n\t\t\t\tserverConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"serverconf\")\n\t\t\t\tserverKeepConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"module\")\n\t\t\t\tmodLoadConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"moduleconf\")\n\t\t\t\tmodKeepConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An invalid block type was declared in the configuration file. This block is of type \" + sectionType + \" and ends on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tsectionType = \"\";\n\t\t\tsectionName = \"\";\n\t\t\toneBlock.clear();\n\t\t} else if (configuration == '\\\\' && !escaped)\n\t\t\tescaped = escapedNow = true;\n\t\telse if (escaped && configuration == '\"')\n\t\t\tcurrentValue += \"\\\"\";\n\t\telse if (!escaped && configuration == '\"') {\n\t\t\tif (writing) {\n\t\t\t\twriting = false;\n\t\t\t\tcommentable = true;\n\t\t\t\tconcatable = true;\n\t\t\t} else {\n\t\t\t\twriting = true;\n\t\t\t\tcommentable = false;\n\t\t\t\tconcatable = false;\n\t\t\t\tconcatening = false;\n\t\t\t}\n\t\t} else if (writing) {\n\t\t\tcurrentValue += configuration;\n\t\t} else if (configuration == '=') {\n\t\t\tacceptVar = false;\n\t\t\tconcatening = true;\n\t\t} else if (!escaped && !writing && configuration == ';') { \/\/ parse the end of a statement\n\t\t\tif (!inBlock) {\n\t\t\t\tif (sectionType == \"include\")\n\t\t\t\t\tincludes.push_back(sectionName);\n\t\t\t\telse {\n\t\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\t\tlineSS << lineNumber;\n\t\t\t\t\tstd::string message = \"An invalid semicolon was found in the configuration file on line \" + lineSS.str();\n\t\t\t\t\tstd::perror(message.c_str());\n\t\t\t\t\tstd::exit(0);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (concatening)\n\t\t\t\t\tcurrentValue += oneBlock[concatingVar];\n\t\t\t\toneBlock.insert(std::pair (varName, currentValue));\n\t\t\t}\n\t\t\tvarName = \"\";\n\t\t\tcurrentValue = \"\";\n\t\t\tconcatingVar = \"\";\n\t\t\tacceptVar = true;\n\t\t\tconcatable = false;\n\t\t\tconcatening = false;\n\t\t} else if (acceptVar)\n\t\t\tvarName += configuration;\n\t\telse if (concatable && configuration == '+') {\n\t\t\tconcatable = false;\n\t\t\tconcatening = true;\n\t\t} else if (concatening && configuration == '+') {\n\t\t\tconcatening = false;\n\t\t\tconcatable = true;\n\t\t\tcurrentValue += oneBlock[concatingVar];\n\t\t\tconcatingVar = \"\";\n\t\t} else if (concatening)\n\t\t\tconcatingVar += configuration;\n\t\t\n\t\tif (!escapedNow && escaped) {\n\t\t\tescaped = false;\n\t\t}\n \t\tescapedNow = false;\n\t}\n\tconfigFile.close();\n\tfor (unsigned int i = 0; i < includes.size(); i++)\n\t\treadConfig(includes[i], filedir);\n}\n\nstd::tr1::unordered_map > ConfigReader::getServerConfig(bool connecting) {\n\tif (connecting)\n\t\treturn serverConfig;\n\treturn serverKeepConfig;\n}\n\nstd::tr1::unordered_map > ConfigReader::getModConfig(bool loading) {\n\tif (loading)\n\t\treturn modLoadConfig;\n\treturn modKeepConfig;\n}Allow whitespace other than spaces to break section types and section names.#include \"config.h\"\n\nConfigReader::ConfigReader(std::string filename, std::string filedir) {\n\treadConfig(filename, filedir);\n}\n\nvoid ConfigReader::readConfig(std::string filename, std::string filedir) {\n\tstd::ifstream configFile;\n\tstd::string absConfFile = filedir + \"\/\" + filename;\n\tconfigFile.open(absConfFile.c_str());\n\tif (configFile.fail()) {\n\t\tstd::perror(\"Config file does not exist or could not be opened\");\n\t\tstd::exit(0);\n\t}\n\tchar configuration;\n\tint lineNumber = 1;\n\tstd::string sectionType = \"\", sectionName = \"\", varName = \"\", currentValue = \"\", concatingVar = \"\";\n\tbool inBlock = false, typingSection = false, namingSection = false, escaped = false, escapedNow = false, commentable = true, writing = false, acceptVar = false, concatable = false, concatening = false;\n\tstd::vector includes;\n\tstd::tr1::unordered_map oneBlock;\n\twhile (configFile.good()) {\n\t\tconfiguration = configFile.get();\n\t\tif (configuration == '\\n')\n\t\t\tlineNumber++;\n\t\t\n\t\tif (!inBlock && sectionType == \"\")\n\t\t\ttypingSection = true;\n\t\t\n\t\tif (commentable && configuration == '#') {\n\t\t\twhile (configuration != '\\n' && configFile.good()) {\n\t\t\t\tconfiguration = configFile.get(); \/\/ do nothing with it--ignore the line\n\t\t\t}\n\t\t\tlineNumber++; \/\/ count it as a line, since the \\n won't reach the part of the loop where the line number increments\n\t\t} else if ((configuration == ' ' || configuration == '\\t' || configuration == '\\r' || configuration == '\\n') && !writing) {\n\t\t\t\/\/ ignore whitespace that's not part of a string\n\t\t} else if (typingSection) {\n\t\t\twhile (configuration != ' ' && configuration != '\\t' && configuration != '\\r' && configuration != '\\n' && configFile.good()) {\n\t\t\t\tsectionType += configuration;\n\t\t\t\tconfiguration = configFile.get();\n\t\t\t}\n\t\t\ttypingSection = false;\n\t\t\tnamingSection = true;\n\t\t} else if (namingSection) {\n\t\t\twhile (configuration != ' ' && configuration != '\\t' && configuration != '\\r' && configuration != '\\n' && configuration != '{' && configuration != ';' && configFile.good()) {\n\t\t\t\tsectionName += configuration;\n\t\t\t\tconfiguration = configFile.get();\n\t\t\t}\n\t\t\tif (!configFile.good()) {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An error occurred reading a section name from the configuration file. This error occurred on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tnamingSection = false;\n\t\t\tif (configuration == '{') { \/\/ handle this now since next iteration will handle the next character\n\t\t\t\tinBlock = true;\n\t\t\t\tacceptVar = true;\n\t\t\t}\n\t\t\tif (configuration == ';' && sectionType == \"include\")\n\t\t\t\tincludes.push_back(sectionName);\n\t\t} else if (configuration == '{') {\n\t\t\tinBlock = true;\n\t\t\tacceptVar = true;\n\t\t} else if (configuration == '}' && !writing) {\n\t\t\tif (!inBlock) {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An end brace occurred outside a block before a corresponding opening brace existed in the configuration file. The offending brace can be found on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tinBlock = false;\n\t\t\ttypingSection = true;\n\t\t\tif (sectionType == \"server\")\n\t\t\t\tserverConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"serverconf\")\n\t\t\t\tserverKeepConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"module\")\n\t\t\t\tmodLoadConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse if (sectionType == \"moduleconf\")\n\t\t\t\tmodKeepConfig.insert(std::pair > (sectionName, oneBlock));\n\t\t\telse {\n\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\tlineSS << lineNumber;\n\t\t\t\tstd::string message = \"An invalid block type was declared in the configuration file. This block is of type \" + sectionType + \" and ends on line \" + lineSS.str();\n\t\t\t\tstd::perror(message.c_str());\n\t\t\t\tstd::exit(0);\n\t\t\t}\n\t\t\tsectionType = \"\";\n\t\t\tsectionName = \"\";\n\t\t\toneBlock.clear();\n\t\t} else if (configuration == '\\\\' && !escaped)\n\t\t\tescaped = escapedNow = true;\n\t\telse if (escaped && configuration == '\"')\n\t\t\tcurrentValue += \"\\\"\";\n\t\telse if (!escaped && configuration == '\"') {\n\t\t\tif (writing) {\n\t\t\t\twriting = false;\n\t\t\t\tcommentable = true;\n\t\t\t\tconcatable = true;\n\t\t\t} else {\n\t\t\t\twriting = true;\n\t\t\t\tcommentable = false;\n\t\t\t\tconcatable = false;\n\t\t\t\tconcatening = false;\n\t\t\t}\n\t\t} else if (writing) {\n\t\t\tcurrentValue += configuration;\n\t\t} else if (configuration == '=') {\n\t\t\tacceptVar = false;\n\t\t\tconcatening = true;\n\t\t} else if (!escaped && !writing && configuration == ';') { \/\/ parse the end of a statement\n\t\t\tif (!inBlock) {\n\t\t\t\tif (sectionType == \"include\")\n\t\t\t\t\tincludes.push_back(sectionName);\n\t\t\t\telse {\n\t\t\t\t\tstd::ostringstream lineSS;\n\t\t\t\t\tlineSS << lineNumber;\n\t\t\t\t\tstd::string message = \"An invalid semicolon was found in the configuration file on line \" + lineSS.str();\n\t\t\t\t\tstd::perror(message.c_str());\n\t\t\t\t\tstd::exit(0);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (concatening)\n\t\t\t\t\tcurrentValue += oneBlock[concatingVar];\n\t\t\t\toneBlock.insert(std::pair (varName, currentValue));\n\t\t\t}\n\t\t\tvarName = \"\";\n\t\t\tcurrentValue = \"\";\n\t\t\tconcatingVar = \"\";\n\t\t\tacceptVar = true;\n\t\t\tconcatable = false;\n\t\t\tconcatening = false;\n\t\t} else if (acceptVar)\n\t\t\tvarName += configuration;\n\t\telse if (concatable && configuration == '+') {\n\t\t\tconcatable = false;\n\t\t\tconcatening = true;\n\t\t} else if (concatening && configuration == '+') {\n\t\t\tconcatening = false;\n\t\t\tconcatable = true;\n\t\t\tcurrentValue += oneBlock[concatingVar];\n\t\t\tconcatingVar = \"\";\n\t\t} else if (concatening)\n\t\t\tconcatingVar += configuration;\n\t\t\n\t\tif (!escapedNow && escaped) {\n\t\t\tescaped = false;\n\t\t}\n \t\tescapedNow = false;\n\t}\n\tconfigFile.close();\n\tfor (unsigned int i = 0; i < includes.size(); i++)\n\t\treadConfig(includes[i], filedir);\n}\n\nstd::tr1::unordered_map > ConfigReader::getServerConfig(bool connecting) {\n\tif (connecting)\n\t\treturn serverConfig;\n\treturn serverKeepConfig;\n}\n\nstd::tr1::unordered_map > ConfigReader::getModConfig(bool loading) {\n\tif (loading)\n\t\treturn modLoadConfig;\n\treturn modKeepConfig;\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/crash_reporter\/crash_reporter_win.h\"\n\n#include \n\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/common\/result_codes.h\"\n#include \"gin\/public\/debug.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n\n#pragma intrinsic(_AddressOfReturnAddress)\n#pragma intrinsic(_ReturnAddress)\n\n#ifdef _WIN64\n\/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\ntypedef struct _UNWIND_INFO {\n unsigned char Version : 3;\n unsigned char Flags : 5;\n unsigned char SizeOfProlog;\n unsigned char CountOfCodes;\n unsigned char FrameRegister : 4;\n unsigned char FrameOffset : 4;\n ULONG ExceptionHandler;\n} UNWIND_INFO, *PUNWIND_INFO;\n#endif\n\nnamespace crash_reporter {\n\nnamespace {\n\n\/\/ Minidump with stacks, PEB, TEB, and unloaded module list.\nconst MINIDUMP_TYPE kSmallDumpType = static_cast(\n MiniDumpWithProcessThreadData | \/\/ Get PEB and TEB.\n MiniDumpWithUnloadedModules); \/\/ Get unloaded modules when available.\n\nconst wchar_t kWaitEventFormat[] = L\"$1CrashServiceWaitEvent\";\nconst wchar_t kPipeNameFormat[] = L\"\\\\\\\\.\\\\pipe\\\\$1 Crash Service\";\n\ntypedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,\n NTSTATUS ExitStatus);\nchar* g_real_terminate_process_stub = NULL;\n\nvoid TerminateProcessWithoutDump() {\n \/\/ Patched stub exists based on conditions (See InitCrashReporter).\n \/\/ As a side note this function also gets called from\n \/\/ WindowProcExceptionFilter.\n if (g_real_terminate_process_stub == NULL) {\n ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);\n } else {\n NtTerminateProcessPtr real_terminate_proc =\n reinterpret_cast(\n static_cast(g_real_terminate_process_stub));\n real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);\n }\n}\n\n#ifdef _WIN64\nint CrashForExceptionInNonABICompliantCodeRange(\n PEXCEPTION_RECORD ExceptionRecord,\n ULONG64 EstablisherFrame,\n PCONTEXT ContextRecord,\n PDISPATCHER_CONTEXT DispatcherContext) {\n EXCEPTION_POINTERS info = { ExceptionRecord, ContextRecord };\n if (!CrashReporter::GetInstance())\n return EXCEPTION_CONTINUE_SEARCH;\n return static_cast(CrashReporter::GetInstance())->\n CrashForException(&info);\n}\n\nstruct ExceptionHandlerRecord {\n RUNTIME_FUNCTION runtime_function;\n UNWIND_INFO unwind_info;\n unsigned char thunk[12];\n};\n\nvoid RegisterNonABICompliantCodeRange(void* start, size_t size_in_bytes) {\n ExceptionHandlerRecord* record =\n reinterpret_cast(start);\n\n \/\/ We assume that the first page of the code range is executable and\n \/\/ committed and reserved for breakpad. What could possibly go wrong?\n\n \/\/ All addresses are 32bit relative offsets to start.\n record->runtime_function.BeginAddress = 0;\n record->runtime_function.EndAddress =\n base::checked_cast(size_in_bytes);\n record->runtime_function.UnwindData =\n offsetof(ExceptionHandlerRecord, unwind_info);\n\n \/\/ Create unwind info that only specifies an exception handler.\n record->unwind_info.Version = 1;\n record->unwind_info.Flags = UNW_FLAG_EHANDLER;\n record->unwind_info.SizeOfProlog = 0;\n record->unwind_info.CountOfCodes = 0;\n record->unwind_info.FrameRegister = 0;\n record->unwind_info.FrameOffset = 0;\n record->unwind_info.ExceptionHandler =\n offsetof(ExceptionHandlerRecord, thunk);\n\n \/\/ Hardcoded thunk.\n \/\/ mov imm64, rax\n record->thunk[0] = 0x48;\n record->thunk[1] = 0xb8;\n void* handler = &CrashForExceptionInNonABICompliantCodeRange;\n memcpy(&record->thunk[2], &handler, 8);\n\n \/\/ jmp rax\n record->thunk[10] = 0xff;\n record->thunk[11] = 0xe0;\n\n \/\/ Protect reserved page against modifications.\n DWORD old_protect;\n CHECK(VirtualProtect(\n start, sizeof(ExceptionHandlerRecord), PAGE_EXECUTE_READ, &old_protect));\n CHECK(RtlAddFunctionTable(\n &record->runtime_function, 1, reinterpret_cast(start)));\n}\n\nvoid UnregisterNonABICompliantCodeRange(void* start) {\n ExceptionHandlerRecord* record =\n reinterpret_cast(start);\n\n CHECK(RtlDeleteFunctionTable(&record->runtime_function));\n}\n#endif \/\/ _WIN64\n\n} \/\/ namespace\n\nCrashReporterWin::CrashReporterWin() {\n}\n\nCrashReporterWin::~CrashReporterWin() {\n}\n\nvoid CrashReporterWin::InitBreakpad(const std::string& product_name,\n const std::string& version,\n const std::string& company_name,\n const std::string& submit_url,\n bool auto_submit,\n bool skip_system_crash_handler) {\n skip_system_crash_handler_ = skip_system_crash_handler;\n\n base::FilePath temp_dir;\n if (!base::GetTempDir(&temp_dir)) {\n LOG(ERROR) << \"Cannot get temp directory\";\n return;\n }\n\n base::string16 pipe_name = ReplaceStringPlaceholders(\n kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);\n base::string16 wait_name = ReplaceStringPlaceholders(\n kWaitEventFormat, base::UTF8ToUTF16(product_name), NULL);\n\n \/\/ Wait until the crash service is started.\n HANDLE wait_event = ::CreateEventW(NULL, TRUE, FALSE, wait_name.c_str());\n if (wait_event != NULL) {\n WaitForSingleObject(wait_event, 1000);\n CloseHandle(wait_event);\n }\n\n \/\/ ExceptionHandler() attaches our handler and ~ExceptionHandler() detaches\n \/\/ it, so we must explicitly reset *before* we instantiate our new handler\n \/\/ to allow any previous handler to detach in the correct order.\n breakpad_.reset();\n\n breakpad_.reset(new google_breakpad::ExceptionHandler(\n temp_dir.value(),\n FilterCallback,\n MinidumpCallback,\n this,\n google_breakpad::ExceptionHandler::HANDLER_ALL,\n kSmallDumpType,\n pipe_name.c_str(),\n GetCustomInfo(product_name, version, company_name)));\n\n if (!breakpad_->IsOutOfProcess())\n LOG(ERROR) << \"Cannot initialize out-of-process crash handler\";\n\n#ifdef _WIN64\n \/\/ Hook up V8 to breakpad.\n {\n \/\/ gin::Debug::SetCodeRangeCreatedCallback only runs the callback when\n \/\/ Isolate is just created, so we have to manually run following code here.\n void* code_range = nullptr;\n size_t size = 0;\n v8::Isolate::GetCurrent()->GetCodeRange(&code_range, &size);\n if (code_range && size)\n RegisterNonABICompliantCodeRange(code_range, size);\n }\n gin::Debug::SetCodeRangeDeletedCallback(UnregisterNonABICompliantCodeRange);\n#endif\n}\n\nvoid CrashReporterWin::SetUploadParameters() {\n upload_parameters_[\"platform\"] = \"win32\";\n}\n\nint CrashReporterWin::CrashForException(EXCEPTION_POINTERS* info) {\n if (breakpad_) {\n breakpad_->WriteMinidumpForException(info);\n TerminateProcessWithoutDump();\n }\n return EXCEPTION_CONTINUE_SEARCH;\n}\n\n\/\/ static\nbool CrashReporterWin::FilterCallback(void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion) {\n return true;\n}\n\n\/\/ static\nbool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,\n const wchar_t* minidump_id,\n void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion,\n bool succeeded) {\n CrashReporterWin* self = static_cast(context);\n if (succeeded && !self->skip_system_crash_handler_)\n return true;\n else\n return false;\n}\n\ngoogle_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(\n const std::string& product_name,\n const std::string& version,\n const std::string& company_name) {\n custom_info_entries_.clear();\n custom_info_entries_.reserve(2 + upload_parameters_.size());\n\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"prod\", L\"Electron\"));\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"ver\", base::UTF8ToWide(version).c_str()));\n\n for (StringMap::const_iterator iter = upload_parameters_.begin();\n iter != upload_parameters_.end(); ++iter) {\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n base::UTF8ToWide(iter->first).c_str(),\n base::UTF8ToWide(iter->second).c_str()));\n }\n\n custom_info_.entries = &custom_info_entries_.front();\n custom_info_.count = custom_info_entries_.size();\n return &custom_info_;\n}\n\n\/\/ static\nCrashReporterWin* CrashReporterWin::GetInstance() {\n return Singleton::get();\n}\n\n\/\/ static\nCrashReporter* CrashReporter::GetInstance() {\n return CrashReporterWin::GetInstance();\n}\n\n} \/\/ namespace crash_reporter\nwin: Guard against failure of RtlAddFunctionTable\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/crash_reporter\/crash_reporter_win.h\"\n\n#include \n\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/common\/result_codes.h\"\n#include \"gin\/public\/debug.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n\n#pragma intrinsic(_AddressOfReturnAddress)\n#pragma intrinsic(_ReturnAddress)\n\n#ifdef _WIN64\n\/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/ddssxxy8.aspx\ntypedef struct _UNWIND_INFO {\n unsigned char Version : 3;\n unsigned char Flags : 5;\n unsigned char SizeOfProlog;\n unsigned char CountOfCodes;\n unsigned char FrameRegister : 4;\n unsigned char FrameOffset : 4;\n ULONG ExceptionHandler;\n} UNWIND_INFO, *PUNWIND_INFO;\n#endif\n\nnamespace crash_reporter {\n\nnamespace {\n\n\/\/ Minidump with stacks, PEB, TEB, and unloaded module list.\nconst MINIDUMP_TYPE kSmallDumpType = static_cast(\n MiniDumpWithProcessThreadData | \/\/ Get PEB and TEB.\n MiniDumpWithUnloadedModules); \/\/ Get unloaded modules when available.\n\nconst wchar_t kWaitEventFormat[] = L\"$1CrashServiceWaitEvent\";\nconst wchar_t kPipeNameFormat[] = L\"\\\\\\\\.\\\\pipe\\\\$1 Crash Service\";\n\ntypedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,\n NTSTATUS ExitStatus);\nchar* g_real_terminate_process_stub = NULL;\n\nvoid TerminateProcessWithoutDump() {\n \/\/ Patched stub exists based on conditions (See InitCrashReporter).\n \/\/ As a side note this function also gets called from\n \/\/ WindowProcExceptionFilter.\n if (g_real_terminate_process_stub == NULL) {\n ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);\n } else {\n NtTerminateProcessPtr real_terminate_proc =\n reinterpret_cast(\n static_cast(g_real_terminate_process_stub));\n real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);\n }\n}\n\n#ifdef _WIN64\nint CrashForExceptionInNonABICompliantCodeRange(\n PEXCEPTION_RECORD ExceptionRecord,\n ULONG64 EstablisherFrame,\n PCONTEXT ContextRecord,\n PDISPATCHER_CONTEXT DispatcherContext) {\n EXCEPTION_POINTERS info = { ExceptionRecord, ContextRecord };\n if (!CrashReporter::GetInstance())\n return EXCEPTION_CONTINUE_SEARCH;\n return static_cast(CrashReporter::GetInstance())->\n CrashForException(&info);\n}\n\nstruct ExceptionHandlerRecord {\n RUNTIME_FUNCTION runtime_function;\n UNWIND_INFO unwind_info;\n unsigned char thunk[12];\n};\n\nbool RegisterNonABICompliantCodeRange(void* start, size_t size_in_bytes) {\n ExceptionHandlerRecord* record =\n reinterpret_cast(start);\n\n \/\/ We assume that the first page of the code range is executable and\n \/\/ committed and reserved for breakpad. What could possibly go wrong?\n\n \/\/ All addresses are 32bit relative offsets to start.\n record->runtime_function.BeginAddress = 0;\n record->runtime_function.EndAddress =\n base::checked_cast(size_in_bytes);\n record->runtime_function.UnwindData =\n offsetof(ExceptionHandlerRecord, unwind_info);\n\n \/\/ Create unwind info that only specifies an exception handler.\n record->unwind_info.Version = 1;\n record->unwind_info.Flags = UNW_FLAG_EHANDLER;\n record->unwind_info.SizeOfProlog = 0;\n record->unwind_info.CountOfCodes = 0;\n record->unwind_info.FrameRegister = 0;\n record->unwind_info.FrameOffset = 0;\n record->unwind_info.ExceptionHandler =\n offsetof(ExceptionHandlerRecord, thunk);\n\n \/\/ Hardcoded thunk.\n \/\/ mov imm64, rax\n record->thunk[0] = 0x48;\n record->thunk[1] = 0xb8;\n void* handler = &CrashForExceptionInNonABICompliantCodeRange;\n memcpy(&record->thunk[2], &handler, 8);\n\n \/\/ jmp rax\n record->thunk[10] = 0xff;\n record->thunk[11] = 0xe0;\n\n \/\/ Protect reserved page against modifications.\n DWORD old_protect;\n return VirtualProtect(start, sizeof(ExceptionHandlerRecord),\n PAGE_EXECUTE_READ, &old_protect) &&\n RtlAddFunctionTable(&record->runtime_function, 1,\n reinterpret_cast(start));\n}\n\nvoid UnregisterNonABICompliantCodeRange(void* start) {\n ExceptionHandlerRecord* record =\n reinterpret_cast(start);\n\n RtlDeleteFunctionTable(&record->runtime_function);\n}\n#endif \/\/ _WIN64\n\n} \/\/ namespace\n\nCrashReporterWin::CrashReporterWin() {\n}\n\nCrashReporterWin::~CrashReporterWin() {\n}\n\nvoid CrashReporterWin::InitBreakpad(const std::string& product_name,\n const std::string& version,\n const std::string& company_name,\n const std::string& submit_url,\n bool auto_submit,\n bool skip_system_crash_handler) {\n skip_system_crash_handler_ = skip_system_crash_handler;\n\n base::FilePath temp_dir;\n if (!base::GetTempDir(&temp_dir)) {\n LOG(ERROR) << \"Cannot get temp directory\";\n return;\n }\n\n base::string16 pipe_name = ReplaceStringPlaceholders(\n kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);\n base::string16 wait_name = ReplaceStringPlaceholders(\n kWaitEventFormat, base::UTF8ToUTF16(product_name), NULL);\n\n \/\/ Wait until the crash service is started.\n HANDLE wait_event = ::CreateEventW(NULL, TRUE, FALSE, wait_name.c_str());\n if (wait_event != NULL) {\n WaitForSingleObject(wait_event, 1000);\n CloseHandle(wait_event);\n }\n\n \/\/ ExceptionHandler() attaches our handler and ~ExceptionHandler() detaches\n \/\/ it, so we must explicitly reset *before* we instantiate our new handler\n \/\/ to allow any previous handler to detach in the correct order.\n breakpad_.reset();\n\n breakpad_.reset(new google_breakpad::ExceptionHandler(\n temp_dir.value(),\n FilterCallback,\n MinidumpCallback,\n this,\n google_breakpad::ExceptionHandler::HANDLER_ALL,\n kSmallDumpType,\n pipe_name.c_str(),\n GetCustomInfo(product_name, version, company_name)));\n\n if (!breakpad_->IsOutOfProcess())\n LOG(ERROR) << \"Cannot initialize out-of-process crash handler\";\n\n#ifdef _WIN64\n bool registered = false;\n \/\/ Hook up V8 to breakpad.\n {\n \/\/ gin::Debug::SetCodeRangeCreatedCallback only runs the callback when\n \/\/ Isolate is just created, so we have to manually run following code here.\n void* code_range = nullptr;\n size_t size = 0;\n v8::Isolate::GetCurrent()->GetCodeRange(&code_range, &size);\n if (code_range && size)\n registered = RegisterNonABICompliantCodeRange(code_range, size);\n }\n if (registered)\n gin::Debug::SetCodeRangeDeletedCallback(UnregisterNonABICompliantCodeRange);\n#endif\n}\n\nvoid CrashReporterWin::SetUploadParameters() {\n upload_parameters_[\"platform\"] = \"win32\";\n}\n\nint CrashReporterWin::CrashForException(EXCEPTION_POINTERS* info) {\n if (breakpad_) {\n breakpad_->WriteMinidumpForException(info);\n TerminateProcessWithoutDump();\n }\n return EXCEPTION_CONTINUE_SEARCH;\n}\n\n\/\/ static\nbool CrashReporterWin::FilterCallback(void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion) {\n return true;\n}\n\n\/\/ static\nbool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,\n const wchar_t* minidump_id,\n void* context,\n EXCEPTION_POINTERS* exinfo,\n MDRawAssertionInfo* assertion,\n bool succeeded) {\n CrashReporterWin* self = static_cast(context);\n if (succeeded && !self->skip_system_crash_handler_)\n return true;\n else\n return false;\n}\n\ngoogle_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(\n const std::string& product_name,\n const std::string& version,\n const std::string& company_name) {\n custom_info_entries_.clear();\n custom_info_entries_.reserve(2 + upload_parameters_.size());\n\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"prod\", L\"Electron\"));\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n L\"ver\", base::UTF8ToWide(version).c_str()));\n\n for (StringMap::const_iterator iter = upload_parameters_.begin();\n iter != upload_parameters_.end(); ++iter) {\n custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(\n base::UTF8ToWide(iter->first).c_str(),\n base::UTF8ToWide(iter->second).c_str()));\n }\n\n custom_info_.entries = &custom_info_entries_.front();\n custom_info_.count = custom_info_entries_.size();\n return &custom_info_;\n}\n\n\/\/ static\nCrashReporterWin* CrashReporterWin::GetInstance() {\n return Singleton::get();\n}\n\n\/\/ static\nCrashReporter* CrashReporter::GetInstance() {\n return CrashReporterWin::GetInstance();\n}\n\n} \/\/ namespace crash_reporter\n<|endoftext|>"} {"text":"#include \"steamhelper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nbool SteamHelper::doesExist()\n{\n #if defined(__linux__)\n QProcess which;\n which.start(\"which\", QStringList() << \"steam\");\n which.waitForFinished();\n return which.exitCode() == 0;\n #elif defined(_WIN32) || defined(_WIN64)\n QSettings settings(\"HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\", QSettings::NativeFormat);\n return settings.contains(\"SteamPath\");\n #elif defined(__APPLE__)\n QDir folder = QDir(QDir::home().filePath(\"Library\/Application Support\/Steam\"));\n return folder.exists();\n #endif\n}\n\nQString SteamHelper::getFolder()\n{\n if (!doesExist())\n {\n return \"\";\n }\n\n #if defined(__linux__)\n return QDir(QDir::homePath() + \"\/.local\/share\/Steam\").canonicalPath();\n #elif defined(_WIN32) || defined(_WIN64)\n QSettings settings(\"HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\", QSettings::NativeFormat);\n return QDir(settings.value(\"SteamPath\").toString()).canonicalPath();\n #elif defined(__APPLE__)\n return QDir(QDir::home().filePath(\"Library\/Application Support\/Steam\")).canonicalPath();\n #endif\n}\n\nQMap SteamHelper::getVdfKeyVals(QString vdfPath)\n{\n QFile vdfFile(vdfPath);\n\n if (!vdfFile.open(QIODevice::ReadOnly))\n {\n return QMap();\n }\n\n QTextStream fileStream(&vdfFile);\n\n QRegExp keyValPairRegex(\"^(?:\\\\s+)?\\\"(.+)\\\"\\\\s+\\\"(.+)\\\"(?:\\\\s+)?$\");\n\n QMap keyVals;\n\n while (!fileStream.atEnd())\n {\n QString line = fileStream.readLine();\n if (line.contains(keyValPairRegex))\n {\n keyValPairRegex.indexIn(line);\n QString key = keyValPairRegex.cap(1);\n QString val = keyValPairRegex.cap(2);\n keyVals[key] = val;\n }\n }\n\n return keyVals;\n}\n\nQList SteamHelper::getLibFolders()\n{\n if (!doesExist())\n {\n return QList();\n }\n\n QDir steamappsPath = QDir(getFolder());\n if (steamappsPath.exists(\"steamapps\"))\n {\n steamappsPath.cd(\"steamapps\");\n }\n else if (steamappsPath.exists(\"SteamApps\"))\n {\n steamappsPath.cd(\"SteamApps\");\n }\n else\n {\n return QList();\n }\n QString libraryFoldersPath = steamappsPath.filePath(\"libraryfolders.vdf\");\n\n QMap keyVals = getVdfKeyVals(libraryFoldersPath);\n\n QList libFolders;\n\n for (QString key : keyVals.keys())\n {\n if (key != \"TimeNextStatsReport\" && key != \"ContentStatsID\")\n {\n libFolders << keyVals[key];\n }\n }\n\n return libFolders;\n}\n\nQMap SteamHelper::getGamesInFolder(QString folderPath)\n{\n QDir folder(folderPath);\n if (folder.exists(\"steamapps\"))\n {\n folder.cd(\"steamapps\");\n }\n else if (folder.exists(\"SteamApps\"))\n {\n folder.cd(\"SteamApps\");\n }\n else\n {\n return QMap();\n }\n\n folder.setNameFilters(QStringList(\"appmanifest_*.acf\"));\n QFileInfoList appmanifests = folder.entryInfoList();\n\n QMap games;\n\n for (QFileInfo appmanifest : appmanifests)\n {\n QMap keyVals = getVdfKeyVals(appmanifest.canonicalFilePath());\n\n if (!keyVals.contains(\"name\")) { continue; }\n if (keyVals.contains(\"appid\"))\n {\n games[keyVals[\"name\"]] = keyVals[\"appid\"];\n }\n else if (keyVals.contains(\"appID\"))\n {\n games[keyVals[\"name\"]] = keyVals[\"appID\"];\n }\n else\n {\n continue;\n }\n }\n\n return games;\n}\n\nQMap SteamHelper::getGames()\n{\n if (!doesExist())\n {\n return QMap();\n }\n\n QString steamPath = getFolder();\n QDir steamappsPath(steamPath);\n if (steamappsPath.exists(\"steamapps\"))\n {\n steamappsPath.cd(\"steamapps\");\n }\n else if (steamappsPath.exists(\"SteamApps\"))\n {\n steamappsPath.cd(\"SteamApps\");\n }\n else\n {\n return QMap();\n }\n\n QMap gamesList;\n\n QList libraryFolders = getLibFolders();\n libraryFolders << steamPath;\n\n for (QString folder : libraryFolders)\n {\n QMap games = getGamesInFolder(folder);\n\n for (QString game : games.keys())\n {\n if (gamesList.contains(game)) { continue; }\n gamesList[game] = games[game];\n }\n }\n\n return gamesList;\n}\nAdd docs for SteamHelper class#include \"steamhelper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/** Checks if Steam exists on the system\n* \\return true if Steam is installed, false otherwise\n*\/\nbool SteamHelper::doesExist()\n{\n #if defined(__linux__)\n QProcess which;\n which.start(\"which\", QStringList() << \"steam\");\n which.waitForFinished();\n return which.exitCode() == 0;\n #elif defined(_WIN32) || defined(_WIN64)\n QSettings settings(\"HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\", QSettings::NativeFormat);\n return settings.contains(\"SteamPath\");\n #elif defined(__APPLE__)\n QDir folder = QDir(QDir::home().filePath(\"Library\/Application Support\/Steam\"));\n return folder.exists();\n #endif\n}\n\n\/** Gets the path to Steam\n* \\return The path to the Steam installation folder\n*\/\nQString SteamHelper::getFolder()\n{\n if (!doesExist())\n {\n return \"\";\n }\n\n #if defined(__linux__)\n return QDir(QDir::homePath() + \"\/.local\/share\/Steam\").canonicalPath();\n #elif defined(_WIN32) || defined(_WIN64)\n QSettings settings(\"HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\", QSettings::NativeFormat);\n return QDir(settings.value(\"SteamPath\").toString()).canonicalPath();\n #elif defined(__APPLE__)\n return QDir(QDir::home().filePath(\"Library\/Application Support\/Steam\")).canonicalPath();\n #endif\n}\n\n\/** Returns a map of key\/value pairs in a VDF file.\n* Really hacky. Ignores objects (e.g. a = \"b\", b { z = \"s\" }, c { z = \"z\" })\n* z will be \"z\" because the objects get ignored. Will break if Valve\n* complicates the one file that this is used for.\n*\n* \\param vdfPath a path to the VDF file to be read\n* \\return A QMap of key\/value pairs in a VDF file.\n*\/\nQMap SteamHelper::getVdfKeyVals(QString vdfPath)\n{\n QFile vdfFile(vdfPath);\n\n if (!vdfFile.open(QIODevice::ReadOnly))\n {\n return QMap();\n }\n\n QTextStream fileStream(&vdfFile);\n\n QRegExp keyValPairRegex(\"^(?:\\\\s+)?\\\"(.+)\\\"\\\\s+\\\"(.+)\\\"(?:\\\\s+)?$\");\n\n QMap keyVals;\n\n while (!fileStream.atEnd())\n {\n QString line = fileStream.readLine();\n if (line.contains(keyValPairRegex))\n {\n keyValPairRegex.indexIn(line);\n QString key = keyValPairRegex.cap(1);\n QString val = keyValPairRegex.cap(2);\n keyVals[key] = val;\n }\n }\n\n return keyVals;\n}\n\n\/** Gets list of Steam library folders\n* \\return A QList with paths to Steam library folders. Does NOT include main folder.\n*\/\nQList SteamHelper::getLibFolders()\n{\n if (!doesExist())\n {\n return QList();\n }\n\n QDir steamappsPath = QDir(getFolder());\n if (steamappsPath.exists(\"steamapps\"))\n {\n steamappsPath.cd(\"steamapps\");\n }\n else if (steamappsPath.exists(\"SteamApps\"))\n {\n steamappsPath.cd(\"SteamApps\");\n }\n else\n {\n return QList();\n }\n QString libraryFoldersPath = steamappsPath.filePath(\"libraryfolders.vdf\");\n\n QMap keyVals = getVdfKeyVals(libraryFoldersPath);\n\n QList libFolders;\n\n for (QString key : keyVals.keys())\n {\n if (key != \"TimeNextStatsReport\" && key != \"ContentStatsID\")\n {\n libFolders << keyVals[key];\n }\n }\n\n return libFolders;\n}\n\n\/** Get a list of all games in a Steam library folder\n* \\param folderPath A path to the Steam library folder\n* \\return A map of games. Key is the name, value is the appID.\n*\/\nQMap SteamHelper::getGamesInFolder(QString folderPath)\n{\n QDir folder(folderPath);\n if (folder.exists(\"steamapps\"))\n {\n folder.cd(\"steamapps\");\n }\n else if (folder.exists(\"SteamApps\"))\n {\n folder.cd(\"SteamApps\");\n }\n else\n {\n return QMap();\n }\n\n folder.setNameFilters(QStringList(\"appmanifest_*.acf\"));\n QFileInfoList appmanifests = folder.entryInfoList();\n\n QMap games;\n\n for (QFileInfo appmanifest : appmanifests)\n {\n QMap keyVals = getVdfKeyVals(appmanifest.canonicalFilePath());\n\n if (!keyVals.contains(\"name\")) { continue; }\n if (keyVals.contains(\"appid\"))\n {\n games[keyVals[\"name\"]] = keyVals[\"appid\"];\n }\n else if (keyVals.contains(\"appID\"))\n {\n games[keyVals[\"name\"]] = keyVals[\"appID\"];\n }\n else\n {\n continue;\n }\n }\n\n return games;\n}\n\n\/** Get a map of ALL games in all Steam library folders.\n* \\return A map of games. Key is the name, value is the appID.\n*\/\nQMap SteamHelper::getGames()\n{\n if (!doesExist())\n {\n return QMap();\n }\n\n QString steamPath = getFolder();\n QDir steamappsPath(steamPath);\n if (steamappsPath.exists(\"steamapps\"))\n {\n steamappsPath.cd(\"steamapps\");\n }\n else if (steamappsPath.exists(\"SteamApps\"))\n {\n steamappsPath.cd(\"SteamApps\");\n }\n else\n {\n return QMap();\n }\n\n QMap gamesList;\n\n QList libraryFolders = getLibFolders();\n libraryFolders << steamPath;\n\n for (QString folder : libraryFolders)\n {\n QMap games = getGamesInFolder(folder);\n\n for (QString game : games.keys())\n {\n if (gamesList.contains(game)) { continue; }\n gamesList[game] = games[game];\n }\n }\n\n return gamesList;\n}\n<|endoftext|>"} {"text":"#include \"generator.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"dictionary.h\"\n#include \"label.h\"\n\nstatic void compileCall(FILE* f, const char* wordName, const Tokens& tokens,\n Tokens::const_iterator* it, bool* state, Dictionary* dictionary) {\n ++*it;\n bool tailCall = (*it != tokens.end() && (*it)->type == SemiColon);\n --*it;\n fprintf(f, tailCall ? \"\\tjmp %s\\n\" : \"\\tjsr %s\\n\", label(wordName).c_str());\n if (tailCall) {\n ++*it; \/\/ Skips ;\n *state = false;\n }\n dictionary->markAsUsed(wordName);\n}\n\nvoid generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) {\n std::deque stack;\n int localLabel = 0;\n bool state = false;\n std::set undefinedVariables;\n int variableLabel = 0;\n std::map variableLabels;\n\n for (auto it = tokens.begin(); it != tokens.end(); ++it) {\n switch (it->type) {\n case Cells:\n if (state) {\n compileCall(f, \"2*\", tokens, &it, &state, dictionary);\n } else {\n stack.back() *= 2;\n }\n break;\n case Allot:\n assert(!stack.empty());\n fprintf(f, \"* = * + %i\\n\", stack.back());\n stack.pop_back();\n break;\n case Create:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"create must be followed by a word name!\");\n exit(1);\n }\n \/\/ printf(\"Create '%s'\\n\", it->stringData);\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n free(it->stringData);\n break;\n case String:\n fprintf(f, \"\\tjsr litstring\\n!byte %i\\n!text \\\"%s\\\"\\n\",\n (int)strlen(it->stringData), it->stringData);\n dictionary->markAsUsed(\"litstring\");\n free(it->stringData);\n break;\n case Variable:\n \/\/ puts(\"Variable\");\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"variable must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #<+\\n\\tldy #>+\\n\\tjmp pushya\\n+\\n!word vl_%i\\n\", variableLabel);\n undefinedVariables.insert(variableLabel);\n variableLabels[it->stringData] = variableLabel;\n ++variableLabel;\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n case Store:\n if (!state) {\n int variableLabel = stack.back();\n stack.pop_back();\n int value = stack.back();\n stack.pop_back();\n fprintf(f, \"vl_%i = %i\\n\", variableLabel, value);\n undefinedVariables.erase(variableLabel);\n break;\n } else {\n compileCall(f, \"!\", tokens, &it, &state, dictionary);\n }\n break;\n case WordName:\n \/\/ printf(\"WordName %s\\n\", it->stringData);\n assert(it->stringData);\n if (state) {\n compileCall(f, it->stringData, tokens, &it, &state, dictionary);\n free(it->stringData);\n } else {\n char* wordName = it->stringData;\n if (variableLabels.find(wordName) != variableLabels.end()) {\n stack.push_back(variableLabels[wordName]);\n free(it->stringData);\n } else {\n fprintf(stderr, \"Variable '%s' not defined\\n\", wordName);\n exit(1);\n }\n }\n break;\n case Number:\n \/\/ puts(\"Number\");\n if (state) {\n dictionary->markAsUsed(\"lit\");\n fprintf(f, \"\\tjsr lit\\n\\t!word %i\\n\", it->intData);\n } else {\n stack.push_back(it->intData);\n }\n break;\n case Code:\n \/\/ puts(\"Code\");\n {\n char* p = it->stringData;\n std::string wordName;\n while (!isspace(*p)) {\n wordName.push_back(*p);\n ++p;\n }\n dictionary->addWord(wordName.c_str());\n if (*p == '\\n') {\n ++p;\n }\n if (label(wordName.c_str()) != wordName) {\n fprintf(f, \"%s:\\t; %s\\n%s\\n\", label(wordName.c_str()).c_str(),\n wordName.c_str(), p);\n } else {\n fprintf(f, \"%s:\\n%s\\n\", wordName.c_str(), p);\n }\n }\n free(it->stringData);\n break;\n case Colon:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \": must be followed by a word name! (is type %i)\\n\", it->type);\n exit(1);\n }\n fprintf(f, \"\\n%s:\", label(it->stringData).c_str());\n \/\/ printf(\"Colon %s\\n\", it->stringData);\n dictionary->addWord(it->stringData);\n if (it->stringData != label(it->stringData)) {\n fprintf(f, \"\\t; %s\", it->stringData);\n }\n fprintf(f, \"\\n\");\n free(it->stringData);\n state = true;\n break;\n case Drop:\n fputs(\"\\tinx\\t; drop\\n\", f);\n break;\n case SemiColon:\n fputs(\"\\trts\\n\", f);\n state = false;\n break;\n case If:\n fprintf(f, \"\\tjsr ifcmp\\n\\tbeq .l%i\\n\", localLabel);\n dictionary->markAsUsed(\"ifcmp\");\n stack.push_back(localLabel++);\n break;\n case Else:\n fprintf(f, \"\\tjmp .l%i\\n.l%i:\\n\", localLabel, stack.back());\n stack.pop_back();\n stack.push_back(localLabel++);\n break;\n case Then:\n fprintf(f, \".l%i:\\n\", stack.back());\n stack.pop_back();\n break;\n case Begin:\n stack.push_back(localLabel);\n fprintf(f, \".l%i:\\n\", localLabel++);\n break;\n case Again:\n fprintf(f, \"\\tjmp .l%i\\n\", stack.back());\n stack.pop_back();\n break;\n case Value:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"value must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #%i\\n\", stack.back() & 0xff);\n fprintf(f, \"\\tldy #%i\\n\", stack.back() >> 8);\n fprintf(f, \"\\tjmp pushya\\n\");\n stack.pop_back();\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n }\n }\n}\nfixed possible memleak#include \"generator.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"dictionary.h\"\n#include \"label.h\"\n\nstatic void compileCall(FILE* f, const char* wordName, const Tokens& tokens,\n Tokens::const_iterator* it, bool* state, Dictionary* dictionary) {\n ++*it;\n bool tailCall = (*it != tokens.end() && (*it)->type == SemiColon);\n --*it;\n fprintf(f, tailCall ? \"\\tjmp %s\\n\" : \"\\tjsr %s\\n\", label(wordName).c_str());\n if (tailCall) {\n ++*it; \/\/ Skips ;\n *state = false;\n }\n dictionary->markAsUsed(wordName);\n}\n\nvoid generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) {\n std::deque stack;\n int localLabel = 0;\n bool state = false;\n std::set undefinedVariables;\n int variableLabel = 0;\n std::map variableLabels;\n\n for (auto it = tokens.begin(); it != tokens.end(); ++it) {\n switch (it->type) {\n case Cells:\n if (state) {\n compileCall(f, \"2*\", tokens, &it, &state, dictionary);\n } else {\n stack.back() *= 2;\n }\n break;\n case Allot:\n assert(!stack.empty());\n fprintf(f, \"* = * + %i\\n\", stack.back());\n stack.pop_back();\n break;\n case Create:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"create must be followed by a word name!\");\n exit(1);\n }\n \/\/ printf(\"Create '%s'\\n\", it->stringData);\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n free(it->stringData);\n break;\n case String:\n fprintf(f, \"\\tjsr litstring\\n!byte %i\\n!text \\\"%s\\\"\\n\",\n (int)strlen(it->stringData), it->stringData);\n dictionary->markAsUsed(\"litstring\");\n free(it->stringData);\n break;\n case Variable:\n \/\/ puts(\"Variable\");\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"variable must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #<+\\n\\tldy #>+\\n\\tjmp pushya\\n+\\n!word vl_%i\\n\", variableLabel);\n undefinedVariables.insert(variableLabel);\n variableLabels[it->stringData] = variableLabel;\n ++variableLabel;\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n case Store:\n if (!state) {\n int variableLabel = stack.back();\n stack.pop_back();\n int value = stack.back();\n stack.pop_back();\n fprintf(f, \"vl_%i = %i\\n\", variableLabel, value);\n undefinedVariables.erase(variableLabel);\n break;\n } else {\n compileCall(f, \"!\", tokens, &it, &state, dictionary);\n }\n break;\n case WordName:\n \/\/ printf(\"WordName %s\\n\", it->stringData);\n assert(it->stringData);\n if (state) {\n char* wordName = it->stringData;\n compileCall(f, wordName, tokens, &it, &state, dictionary);\n free(wordName);\n } else {\n char* wordName = it->stringData;\n if (variableLabels.find(wordName) != variableLabels.end()) {\n stack.push_back(variableLabels[wordName]);\n free(it->stringData);\n } else {\n fprintf(stderr, \"Variable '%s' not defined\\n\", wordName);\n exit(1);\n }\n }\n break;\n case Number:\n \/\/ puts(\"Number\");\n if (state) {\n dictionary->markAsUsed(\"lit\");\n fprintf(f, \"\\tjsr lit\\n\\t!word %i\\n\", it->intData);\n } else {\n stack.push_back(it->intData);\n }\n break;\n case Code:\n \/\/ puts(\"Code\");\n {\n char* p = it->stringData;\n std::string wordName;\n while (!isspace(*p)) {\n wordName.push_back(*p);\n ++p;\n }\n dictionary->addWord(wordName.c_str());\n if (*p == '\\n') {\n ++p;\n }\n if (label(wordName.c_str()) != wordName) {\n fprintf(f, \"%s:\\t; %s\\n%s\\n\", label(wordName.c_str()).c_str(),\n wordName.c_str(), p);\n } else {\n fprintf(f, \"%s:\\n%s\\n\", wordName.c_str(), p);\n }\n }\n free(it->stringData);\n break;\n case Colon:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \": must be followed by a word name! (is type %i)\\n\", it->type);\n exit(1);\n }\n fprintf(f, \"\\n%s:\", label(it->stringData).c_str());\n \/\/ printf(\"Colon %s\\n\", it->stringData);\n dictionary->addWord(it->stringData);\n if (it->stringData != label(it->stringData)) {\n fprintf(f, \"\\t; %s\", it->stringData);\n }\n fprintf(f, \"\\n\");\n free(it->stringData);\n state = true;\n break;\n case Drop:\n fputs(\"\\tinx\\t; drop\\n\", f);\n break;\n case SemiColon:\n fputs(\"\\trts\\n\", f);\n state = false;\n break;\n case If:\n fprintf(f, \"\\tjsr ifcmp\\n\\tbeq .l%i\\n\", localLabel);\n dictionary->markAsUsed(\"ifcmp\");\n stack.push_back(localLabel++);\n break;\n case Else:\n fprintf(f, \"\\tjmp .l%i\\n.l%i:\\n\", localLabel, stack.back());\n stack.pop_back();\n stack.push_back(localLabel++);\n break;\n case Then:\n fprintf(f, \".l%i:\\n\", stack.back());\n stack.pop_back();\n break;\n case Begin:\n stack.push_back(localLabel);\n fprintf(f, \".l%i:\\n\", localLabel++);\n break;\n case Again:\n fprintf(f, \"\\tjmp .l%i\\n\", stack.back());\n stack.pop_back();\n break;\n case Value:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"value must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #%i\\n\", stack.back() & 0xff);\n fprintf(f, \"\\tldy #%i\\n\", stack.back() >> 8);\n fprintf(f, \"\\tjmp pushya\\n\");\n stack.pop_back();\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r\n\/\/\r\n\/\/ By downloading, copying, installing or using the software you agree to this license.\r\n\/\/ If you do not agree to this license, do not download, install,\r\n\/\/ copy or use the software.\r\n\/\/\r\n\/\/\r\n\/\/ License Agreement\r\n\/\/ For Open Source Computer Vision Library\r\n\/\/\r\n\/\/ Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\r\n\/\/ Copyright (C) 2009, Willow Garage Inc., all rights reserved.\r\n\/\/ Third party copyrights are property of their respective owners.\r\n\/\/\r\n\/\/ Redistribution and use in source and binary forms, with or without modification,\r\n\/\/ are permitted provided that the following conditions are met:\r\n\/\/\r\n\/\/ * Redistribution's of source code must retain the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer.\r\n\/\/\r\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution.\r\n\/\/\r\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\r\n\/\/ derived from this software without specific prior written permission.\r\n\/\/\r\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\r\n\/\/ any express or implied warranties, including, but not limited to, the implied\r\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\r\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\r\n\/\/ indirect, incidental, special, exemplary, or consequential damages\r\n\/\/ (including, but not limited to, procurement of substitute goods or services;\r\n\/\/ loss of use, data, or profits; or business interruption) however caused\r\n\/\/ and on any theory of liability, whether in contract, strict liability,\r\n\/\/ or tort (including negligence or otherwise) arising in any way out of\r\n\/\/ the use of this software, even if advised of the possibility of such damage.\r\n\/\/\r\n\/\/M*\/\r\n\r\n#include \"cxcoretest.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\nclass CV_MatrOpTest : public CvTest\r\n{\r\npublic:\r\n CV_MatrOpTest();\r\n ~CV_MatrOpTest(); \r\nprotected:\r\n void run(int); \r\n\r\n bool TestMat();\r\n bool TestMatND();\r\n bool TestSparseMat();\r\n\r\n\r\n bool checkMatSetError(const Mat& m1, const Mat& m2);\r\n bool checkMatSetError(const MatND& m1, const MatND& m2); \r\n};\r\n\r\nCV_MatrOpTest::CV_MatrOpTest(): CvTest( \"matrix-operations\", \"?\" )\r\n{\r\n support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE;\r\n}\r\nCV_MatrOpTest::~CV_MatrOpTest() {}\r\n\r\nbool CV_MatrOpTest::checkMatSetError(const Mat& m1, const Mat& m2)\r\n{\r\n if (norm(m1, m2, NORM_INF) == 0)\r\n return true;\r\n \r\n ts->set_failed_test_info(CvTS::FAIL_MISMATCH);\r\n return false; \r\n}\r\n\r\nbool CV_MatrOpTest::checkMatSetError(const MatND& m1, const MatND& m2)\r\n{\r\n if (norm(m1, m2, NORM_INF) == 0)\r\n return true;\r\n \r\n ts->set_failed_test_info(CvTS::FAIL_MISMATCH);\r\n return false; \r\n}\r\n\r\nbool CV_MatrOpTest::TestMat()\r\n{\r\n Mat one_3x1(3, 1, CV_32F, Scalar(1.0));\r\n Mat shi_3x1(3, 1, CV_32F, Scalar(1.2));\r\n Mat shi_2x1(2, 1, CV_32F, Scalar(-1));\r\n Scalar shift = Scalar::all(15);\r\n\r\n float data[] = { sqrt(2.f)\/2, -sqrt(2.f)\/2, 1.f, sqrt(2.f)\/2, sqrt(2.f)\/2, 10.f };\r\n Mat rot_2x3(2, 3, CV_32F, data);\r\n \r\n Mat res = rot_2x3 * (one_3x1 + shi_3x1 + shi_3x1 + shi_3x1) - shi_2x1 + shift;\r\n\r\n Mat tmp, res2;\r\n add(one_3x1, shi_3x1, tmp);\r\n add(tmp, shi_3x1, tmp);\r\n add(tmp, shi_3x1, tmp);\r\n gemm(rot_2x3, tmp, 1, shi_2x1, -1, res2, 0);\r\n add(res2, Mat(2, 1, CV_32F, shift), res2);\r\n \r\n if (!checkMatSetError(res, res2))\r\n return false;\r\n \r\n Mat mat4x4(4, 4, CV_32F);\r\n randu(mat4x4, Scalar(0), Scalar(10));\r\n\r\n Mat roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2)));\r\n Mat roi2 = mat4x4(Range(1, 3), Range(1, 3));\r\n\r\n if (!checkMatSetError(roi1, roi2))\r\n return false;\r\n\r\n if (!checkMatSetError(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size()))))\r\n return false;\r\n\r\n \r\n return true;\r\n}\r\n\r\nbool CV_MatrOpTest::TestMatND()\r\n{ \r\n int sizes[] = { 3, 3, 3};\r\n cv::MatND nd(3, sizes, CV_32F);\r\n\r\n \/* MatND res = nd * nd + nd; \r\n MatND res2;\r\n cv::gemm(nd, nd, 1, nd, 1, res2);\r\n \r\n if (!checkMatSetError(res1, res2))\r\n return false;*\/\r\n\r\n return true;\r\n}\r\n\r\nbool CV_MatrOpTest::TestSparseMat()\r\n{ \r\n int sizes[] = { 10, 10, 10};\r\n SparseMat mat(sizeof(sizes)\/sizeof(sizes[0]), sizes, CV_32F);\r\n\r\n return true;\r\n}\r\n\r\n\r\n\r\nvoid CV_MatrOpTest::run( int \/* start_from *\/)\r\n{\r\n if (!TestMat())\r\n return;\r\n\r\n if (!TestMatND())\r\n return;\r\n\r\n if (!TestSparseMat())\r\n return;\r\n \r\n ts->set_failed_test_info(CvTS::OK);\r\n}\r\n\r\nCV_MatrOpTest cv_MatrOp_test;\r\n\r\n\r\nunited cv::Mat and cv::MatND\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r\n\/\/\r\n\/\/ By downloading, copying, installing or using the software you agree to this license.\r\n\/\/ If you do not agree to this license, do not download, install,\r\n\/\/ copy or use the software.\r\n\/\/\r\n\/\/\r\n\/\/ License Agreement\r\n\/\/ For Open Source Computer Vision Library\r\n\/\/\r\n\/\/ Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\r\n\/\/ Copyright (C) 2009, Willow Garage Inc., all rights reserved.\r\n\/\/ Third party copyrights are property of their respective owners.\r\n\/\/\r\n\/\/ Redistribution and use in source and binary forms, with or without modification,\r\n\/\/ are permitted provided that the following conditions are met:\r\n\/\/\r\n\/\/ * Redistribution's of source code must retain the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer.\r\n\/\/\r\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution.\r\n\/\/\r\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\r\n\/\/ derived from this software without specific prior written permission.\r\n\/\/\r\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\r\n\/\/ any express or implied warranties, including, but not limited to, the implied\r\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\r\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\r\n\/\/ indirect, incidental, special, exemplary, or consequential damages\r\n\/\/ (including, but not limited to, procurement of substitute goods or services;\r\n\/\/ loss of use, data, or profits; or business interruption) however caused\r\n\/\/ and on any theory of liability, whether in contract, strict liability,\r\n\/\/ or tort (including negligence or otherwise) arising in any way out of\r\n\/\/ the use of this software, even if advised of the possibility of such damage.\r\n\/\/\r\n\/\/M*\/\r\n\r\n#include \"cxcoretest.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\nclass CV_MatrOpTest : public CvTest\r\n{\r\npublic:\r\n CV_MatrOpTest();\r\n ~CV_MatrOpTest(); \r\nprotected:\r\n void run(int); \r\n\r\n bool TestMat();\r\n bool TestMatND();\r\n bool TestSparseMat();\r\n\r\n\r\n bool checkMatSetError(const Mat& m1, const Mat& m2);\r\n};\r\n\r\nCV_MatrOpTest::CV_MatrOpTest(): CvTest( \"matrix-operations\", \"?\" )\r\n{\r\n support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE;\r\n}\r\nCV_MatrOpTest::~CV_MatrOpTest() {}\r\n\r\nbool CV_MatrOpTest::checkMatSetError(const Mat& m1, const Mat& m2)\r\n{\r\n if (norm(m1, m2, NORM_INF) == 0)\r\n return true;\r\n \r\n ts->set_failed_test_info(CvTS::FAIL_MISMATCH);\r\n return false; \r\n}\r\n\r\nbool CV_MatrOpTest::TestMat()\r\n{\r\n Mat one_3x1(3, 1, CV_32F, Scalar(1.0));\r\n Mat shi_3x1(3, 1, CV_32F, Scalar(1.2));\r\n Mat shi_2x1(2, 1, CV_32F, Scalar(-1));\r\n Scalar shift = Scalar::all(15);\r\n\r\n float data[] = { sqrt(2.f)\/2, -sqrt(2.f)\/2, 1.f, sqrt(2.f)\/2, sqrt(2.f)\/2, 10.f };\r\n Mat rot_2x3(2, 3, CV_32F, data);\r\n \r\n Mat res = rot_2x3 * (one_3x1 + shi_3x1 + shi_3x1 + shi_3x1) - shi_2x1 + shift;\r\n\r\n Mat tmp, res2;\r\n add(one_3x1, shi_3x1, tmp);\r\n add(tmp, shi_3x1, tmp);\r\n add(tmp, shi_3x1, tmp);\r\n gemm(rot_2x3, tmp, 1, shi_2x1, -1, res2, 0);\r\n add(res2, Mat(2, 1, CV_32F, shift), res2);\r\n \r\n if (!checkMatSetError(res, res2))\r\n return false;\r\n \r\n Mat mat4x4(4, 4, CV_32F);\r\n randu(mat4x4, Scalar(0), Scalar(10));\r\n\r\n Mat roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2)));\r\n Mat roi2 = mat4x4(Range(1, 3), Range(1, 3));\r\n\r\n if (!checkMatSetError(roi1, roi2))\r\n return false;\r\n\r\n if (!checkMatSetError(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size()))))\r\n return false;\r\n\r\n \r\n return true;\r\n}\r\n\r\nbool CV_MatrOpTest::TestMatND()\r\n{ \r\n int sizes[] = { 3, 3, 3};\r\n cv::MatND nd(3, sizes, CV_32F);\r\n\r\n \/* MatND res = nd * nd + nd; \r\n MatND res2;\r\n cv::gemm(nd, nd, 1, nd, 1, res2);\r\n \r\n if (!checkMatSetError(res1, res2))\r\n return false;*\/\r\n\r\n return true;\r\n}\r\n\r\nbool CV_MatrOpTest::TestSparseMat()\r\n{ \r\n int sizes[] = { 10, 10, 10};\r\n SparseMat mat(sizeof(sizes)\/sizeof(sizes[0]), sizes, CV_32F);\r\n\r\n return true;\r\n}\r\n\r\n\r\n\r\nvoid CV_MatrOpTest::run( int \/* start_from *\/)\r\n{\r\n if (!TestMat())\r\n return;\r\n\r\n if (!TestMatND())\r\n return;\r\n\r\n if (!TestSparseMat())\r\n return;\r\n \r\n ts->set_failed_test_info(CvTS::OK);\r\n}\r\n\r\nCV_MatrOpTest cv_MatrOp_test;\r\n\r\n\r\n<|endoftext|>"} {"text":"#include \"markov.h\"\n#include \"random.h\"\n#include \"rodrigues.h\"\n#include \"compiler.h\"\n\n\/\/ The procedure below gives rise to roughly the following relative polyhedron abundancies.\n\n\/\/ 8.10 % tetrahedron\n\/\/ 8.66 % octahedron\n\/\/ 4.68 % cube\n\/\/ 7.70 % icosahedron\n\/\/ 4.62 % dodecahedron\n\/\/ 5.81 % truncated tetrahedron\n\/\/ 9.55 % truncated octahedron\n\/\/ 3.48 % truncated cube\n\/\/ 3.46 % truncated icosahedron\n\/\/ 3.47 % truncated dodecahedron\n\/\/ 7.78 % cuboctahedron\n\/\/ 4.62 % icosidodecahedron\n\/\/ 3.53 % rhombicuboctahedron\n\/\/ 3.46 % rhombicosidodecahedron\n\/\/ 7.23 % rhombitruncated cuboctahedron\n\/\/ 6.93 % rhombitruncated icosidodecahedron\n\/\/ 3.44 % snub cube\n\/\/ 3.46 % snub dodecahedron\n\ninline bool operator == (const polyhedron_select_t & x, const polyhedron_select_t & y)\n{\n return x.system == y.system && x.point == y.point;\n}\n\nnamespace\n{\n const unsigned probability_max = 1u << 31u;\n const unsigned probability_mask = probability_max - 1u;\n const struct replacement_t {\n polyhedron_select_t before, after;\n unsigned probability;\n } replacements [] = {\n \/\/ The fixups in maybe_perform_replacement assume this ordering.\n { { tetrahedral, 0, }, { octahedral, 1, }, unsigned (0.375 * probability_max), },\n { { tetrahedral, 6, }, { octahedral, 5, }, unsigned (0.375 * probability_max), },\n { { tetrahedral, 3, }, { octahedral, 0, }, unsigned (0.375 * probability_max), },\n { { octahedral, 1, }, { tetrahedral, 0, }, unsigned (0.375 * probability_max), },\n { { octahedral, 5, }, { tetrahedral, 6, }, unsigned (0.375 * probability_max), },\n { { octahedral, 0, }, { tetrahedral, 3, }, unsigned (0.375 * probability_max), },\n { { icosahedral, 1, }, { tetrahedral, 7, }, unsigned (0.400 * probability_max), },\n { { tetrahedral, 7, }, { icosahedral, 1, }, unsigned (0.600 * probability_max), },\n \/\/ The snub tetrahedron is not chiral (it is the icosahedron).\n \/\/ Not doing this replacement makes some snub-desnub combos impossible.\n { { tetrahedral, 7, }, { dual_tetrahedral, 7, }, probability_max \/ 2, },\n };\n const unsigned replacement_count = sizeof replacements \/ sizeof * replacements;\n ALIGNED16 const float rotations [3] [4] = {\n \/\/ Rotate about an X-node through angle pi\/4.\n { -0x1.921fb4P-1f, 0.0f, 0.0f, 0.0f, }, \/\/ I1 -> T7\n { +0x1.921fb4P-1f, 0.0f, 0.0f, 0.0f, }, \/\/ T7 -> I1\n \/\/ Rotate about a Z-node through angle approximately 0.2471 pi.\n { +0x1.caf0fcP-2f, +0x1.448542P-1f, 0.0f, 0.0f, }, \/\/ T7 -> T7*\n };\n\n inline bool bernoulli_trial (rng_t & rng, unsigned probability)\n {\n return (rng.get () & probability_mask) < probability;\n }\n\n inline void maybe_perform_replacement (rng_t & rng, float (& u) [4], polyhedron_select_t & current, unsigned & starting_point)\n {\n \/\/ Replacements are in terms of the primary representation so mask out the dual bit for now.\n unsigned duality = current.system & 1;\n current.system = system_select_t (current.system & ~1);\n \/\/ If non-snub, maybe switch between dual representations, to permit either\n \/\/ variety of any snub or desnub operation that follows. Not doing it now,\n \/\/ before the replacements, makes some double-desnub combos impossible.\n unsigned entropy = (unsigned) rng.get (); \/\/ Seems a shame to waste it.\n duality ^= entropy & (current.point != 7);\n\n unsigned m = 0;\n while (m != replacement_count && ! (replacements [m].before == current && bernoulli_trial (rng, replacements [m].probability))) ++ m;\n if (m != replacement_count) {\n current = replacements [m].after;\n \/\/ Fixups after the replacement: avoid backtracking transitions\n \/\/ by updating starting_point, and maybe appply a rotation.\n if (m < 6) {\n \/\/ Tetrahedral <-> octahedral; if the starting polyhedron exists in both\n \/\/ tilings, forbid backtracking to it; otherwise, no transition is forbidden.\n \/\/ The fundamental triangles of the tetrahedral and octahedral tilings\n \/\/ are chosen so that no rotation is needed after these replacements.\n unsigned j = 0;\n while (j != 3 && starting_point != replacements [m \/ 3 + j].before.point) ++ j;\n starting_point = j == 3 ? current.point : replacements [m \/ 3 + j].after.point;\n }\n else {\n \/\/ Apply a rotation in object co-ordinates.\n v4f rotation = load4f (rotations [m - 6]);\n if (duality) rotation = - rotation;\n store4f (u, rotate (load4f (u), rotation));\n \/\/ Tetrahedral <-> icosahedral: no Markov transition is forbidden after these replacements.\n \/\/ Tetrahedral -> dual tetrahedral (both snub): keep the starting_point we already have.\n if (m < 8) starting_point = current.point;\n }\n }\n\n \/\/ If non-snub, maybe switch between dual representations (again).\n \/\/ Not doing this now, after the replacement, makes some double-snub combos impossible.\n duality ^= (entropy >> 1) & (current.point != 7);\n \/\/ Restore the dual bit.\n current.system = system_select_t (current.system ^ duality);\n }\n}\n\nvoid transition (rng_t & rng, float (& u) [4], polyhedron_select_t & current, unsigned & starting_point)\n{\n maybe_perform_replacement (rng, u, current, starting_point);\n\n \/\/ Perform a Markov transition.\n unsigned next;\n do next = rng.get () & 7; \/* PLEASE *\/\n\n \/\/ Certain transitions are not allowed:\n while (next == starting_point || 1 & current.point [\"\\017\\027\\047\\271\\272\\274\\300\\370\"] >> next);\n\n starting_point = current.point;\n current.point = next;\n}\nmarkov.cpp: fix 1-ulp error in hexfloat constant.#include \"markov.h\"\n#include \"random.h\"\n#include \"rodrigues.h\"\n#include \"compiler.h\"\n\n\/\/ The procedure below gives rise to roughly the following relative polyhedron abundancies.\n\n\/\/ 8.10 % tetrahedron\n\/\/ 8.66 % octahedron\n\/\/ 4.68 % cube\n\/\/ 7.70 % icosahedron\n\/\/ 4.62 % dodecahedron\n\/\/ 5.81 % truncated tetrahedron\n\/\/ 9.55 % truncated octahedron\n\/\/ 3.48 % truncated cube\n\/\/ 3.46 % truncated icosahedron\n\/\/ 3.47 % truncated dodecahedron\n\/\/ 7.78 % cuboctahedron\n\/\/ 4.62 % icosidodecahedron\n\/\/ 3.53 % rhombicuboctahedron\n\/\/ 3.46 % rhombicosidodecahedron\n\/\/ 7.23 % rhombitruncated cuboctahedron\n\/\/ 6.93 % rhombitruncated icosidodecahedron\n\/\/ 3.44 % snub cube\n\/\/ 3.46 % snub dodecahedron\n\ninline bool operator == (const polyhedron_select_t & x, const polyhedron_select_t & y)\n{\n return x.system == y.system && x.point == y.point;\n}\n\nnamespace\n{\n const unsigned probability_max = 1u << 31u;\n const unsigned probability_mask = probability_max - 1u;\n const struct replacement_t {\n polyhedron_select_t before, after;\n unsigned probability;\n } replacements [] = {\n \/\/ The fixups in maybe_perform_replacement assume this ordering.\n { { tetrahedral, 0, }, { octahedral, 1, }, unsigned (0.375 * probability_max), },\n { { tetrahedral, 6, }, { octahedral, 5, }, unsigned (0.375 * probability_max), },\n { { tetrahedral, 3, }, { octahedral, 0, }, unsigned (0.375 * probability_max), },\n { { octahedral, 1, }, { tetrahedral, 0, }, unsigned (0.375 * probability_max), },\n { { octahedral, 5, }, { tetrahedral, 6, }, unsigned (0.375 * probability_max), },\n { { octahedral, 0, }, { tetrahedral, 3, }, unsigned (0.375 * probability_max), },\n { { icosahedral, 1, }, { tetrahedral, 7, }, unsigned (0.400 * probability_max), },\n { { tetrahedral, 7, }, { icosahedral, 1, }, unsigned (0.600 * probability_max), },\n \/\/ The snub tetrahedron is not chiral (it is the icosahedron).\n \/\/ Not doing this replacement makes some snub-desnub combos impossible.\n { { tetrahedral, 7, }, { dual_tetrahedral, 7, }, probability_max \/ 2, },\n };\n const unsigned replacement_count = sizeof replacements \/ sizeof * replacements;\n ALIGNED16 const float rotations [3] [4] = {\n \/\/ Rotate about an X-node through angle pi\/4.\n { -0x1.921fb6P-1f, 0.0f, 0.0f, 0.0f, }, \/\/ I1 -> T7\n { +0x1.921fb6P-1f, 0.0f, 0.0f, 0.0f, }, \/\/ T7 -> I1\n \/\/ Rotate about a Z-node through angle approximately 0.2471 pi.\n { +0x1.caf0fcP-2f, +0x1.448542P-1f, 0.0f, 0.0f, }, \/\/ T7 -> T7*\n };\n\n inline bool bernoulli_trial (rng_t & rng, unsigned probability)\n {\n return (rng.get () & probability_mask) < probability;\n }\n\n inline void maybe_perform_replacement (rng_t & rng, float (& u) [4], polyhedron_select_t & current, unsigned & starting_point)\n {\n \/\/ Replacements are in terms of the primary representation so mask out the dual bit for now.\n unsigned duality = current.system & 1;\n current.system = system_select_t (current.system & ~1);\n \/\/ If non-snub, maybe switch between dual representations, to permit either\n \/\/ variety of any snub or desnub operation that follows. Not doing it now,\n \/\/ before the replacements, makes some double-desnub combos impossible.\n unsigned entropy = (unsigned) rng.get (); \/\/ Seems a shame to waste it.\n duality ^= entropy & (current.point != 7);\n\n unsigned m = 0;\n while (m != replacement_count && ! (replacements [m].before == current && bernoulli_trial (rng, replacements [m].probability))) ++ m;\n if (m != replacement_count) {\n current = replacements [m].after;\n \/\/ Fixups after the replacement: avoid backtracking transitions\n \/\/ by updating starting_point, and maybe appply a rotation.\n if (m < 6) {\n \/\/ Tetrahedral <-> octahedral; if the starting polyhedron exists in both\n \/\/ tilings, forbid backtracking to it; otherwise, no transition is forbidden.\n \/\/ The fundamental triangles of the tetrahedral and octahedral tilings\n \/\/ are chosen so that no rotation is needed after these replacements.\n unsigned j = 0;\n while (j != 3 && starting_point != replacements [m \/ 3 + j].before.point) ++ j;\n starting_point = j == 3 ? current.point : replacements [m \/ 3 + j].after.point;\n }\n else {\n \/\/ Apply a rotation in object co-ordinates.\n v4f rotation = load4f (rotations [m - 6]);\n if (duality) rotation = - rotation;\n store4f (u, rotate (load4f (u), rotation));\n \/\/ Tetrahedral <-> icosahedral: no Markov transition is forbidden after these replacements.\n \/\/ Tetrahedral -> dual tetrahedral (both snub): keep the starting_point we already have.\n if (m < 8) starting_point = current.point;\n }\n }\n\n \/\/ If non-snub, maybe switch between dual representations (again).\n \/\/ Not doing this now, after the replacement, makes some double-snub combos impossible.\n duality ^= (entropy >> 1) & (current.point != 7);\n \/\/ Restore the dual bit.\n current.system = system_select_t (current.system ^ duality);\n }\n}\n\nvoid transition (rng_t & rng, float (& u) [4], polyhedron_select_t & current, unsigned & starting_point)\n{\n maybe_perform_replacement (rng, u, current, starting_point);\n\n \/\/ Perform a Markov transition.\n unsigned next;\n do next = rng.get () & 7; \/* PLEASE *\/\n\n \/\/ Certain transitions are not allowed:\n while (next == starting_point || 1 & current.point [\"\\017\\027\\047\\271\\272\\274\\300\\370\"] >> next);\n\n starting_point = current.point;\n current.point = next;\n}\n<|endoftext|>"} {"text":"\/\/===-- ParameterAttributes.cpp - Implement ParamAttrsList ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ParamAttrsList class and ParamAttr utilities.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ParamAttrsList.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \n\nusing namespace llvm;\n\nstatic ManagedStatic > ParamAttrsLists;\n\nParamAttrsList::ParamAttrsList(const ParamAttrsVector &attrVec) \n : attrs(attrVec), refCount(0) {\n}\n\nParamAttrsList::~ParamAttrsList() {\n ParamAttrsLists->RemoveNode(this);\n}\n\nParameterAttributes\nParamAttrsList::getParamAttrs(uint16_t Index) const {\n unsigned limit = attrs.size();\n for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)\n if (attrs[i].index == Index)\n return attrs[i].attrs;\n return ParamAttr::None;\n}\n\nbool ParamAttrsList::hasAttrSomewhere(ParameterAttributes attr) const {\n for (unsigned i = 0, e = attrs.size(); i < e; ++i)\n if (attrs[i].attrs & attr)\n return true;\n return false;\n}\n\nstd::string \nParamAttrsList::getParamAttrsText(ParameterAttributes Attrs) {\n std::string Result;\n if (Attrs & ParamAttr::ZExt)\n Result += \"zeroext \";\n if (Attrs & ParamAttr::SExt)\n Result += \"signext \";\n if (Attrs & ParamAttr::NoReturn)\n Result += \"noreturn \";\n if (Attrs & ParamAttr::NoUnwind)\n Result += \"nounwind \";\n if (Attrs & ParamAttr::InReg)\n Result += \"inreg \";\n if (Attrs & ParamAttr::NoAlias)\n Result += \"noalias \";\n if (Attrs & ParamAttr::StructRet)\n Result += \"sret \"; \n if (Attrs & ParamAttr::ByVal)\n Result += \"byval \";\n if (Attrs & ParamAttr::Nest)\n Result += \"nest \";\n if (Attrs & ParamAttr::ReadNone)\n Result += \"readnone \";\n if (Attrs & ParamAttr::ReadOnly)\n Result += \"readonly \";\n if (Attrs & ParamAttr::Alignment) {\n std::stringstream s;\n s << ((Attrs & ParamAttr::Alignment) >> 16);\n Result += \"align \";\n Result += s.str();\n Result += \" \";\n }\n return Result;\n}\n\nvoid ParamAttrsList::Profile(FoldingSetNodeID &ID,\n const ParamAttrsVector &Attrs) {\n for (unsigned i = 0; i < Attrs.size(); ++i)\n ID.AddInteger(uint64_t(Attrs[i].attrs) << 16 | unsigned(Attrs[i].index));\n}\n\nconst ParamAttrsList *\nParamAttrsList::get(const ParamAttrsVector &attrVec) {\n \/\/ If there are no attributes then return a null ParamAttrsList pointer.\n if (attrVec.empty())\n return 0;\n\n#ifndef NDEBUG\n for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {\n assert(attrVec[i].attrs != ParamAttr::None\n && \"Pointless parameter attribute!\");\n assert((!i || attrVec[i-1].index < attrVec[i].index)\n && \"Misordered ParamAttrsList!\");\n }\n#endif\n\n \/\/ Otherwise, build a key to look up the existing attributes.\n FoldingSetNodeID ID;\n ParamAttrsList::Profile(ID, attrVec);\n void *InsertPos;\n ParamAttrsList *PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);\n\n \/\/ If we didn't find any existing attributes of the same shape then\n \/\/ create a new one and insert it.\n if (!PAL) {\n PAL = new ParamAttrsList(attrVec);\n ParamAttrsLists->InsertNode(PAL, InsertPos);\n }\n\n \/\/ Return the ParamAttrsList that we found or created.\n return PAL;\n}\n\nconst ParamAttrsList *\nParamAttrsList::getModified(const ParamAttrsList *PAL,\n const ParamAttrsVector &modVec) {\n if (modVec.empty())\n return PAL;\n\n#ifndef NDEBUG\n for (unsigned i = 0, e = modVec.size(); i < e; ++i)\n assert((!i || modVec[i-1].index < modVec[i].index)\n && \"Misordered ParamAttrsList!\");\n#endif\n\n if (!PAL) {\n \/\/ Strip any instances of ParamAttr::None from modVec before calling 'get'.\n ParamAttrsVector newVec;\n newVec.reserve(modVec.size());\n for (unsigned i = 0, e = modVec.size(); i < e; ++i)\n if (modVec[i].attrs != ParamAttr::None)\n newVec.push_back(modVec[i]);\n return get(newVec);\n }\n\n const ParamAttrsVector &oldVec = PAL->attrs;\n\n ParamAttrsVector newVec;\n unsigned oldI = 0;\n unsigned modI = 0;\n unsigned oldE = oldVec.size();\n unsigned modE = modVec.size();\n\n while (oldI < oldE && modI < modE) {\n uint16_t oldIndex = oldVec[oldI].index;\n uint16_t modIndex = modVec[modI].index;\n\n if (oldIndex < modIndex) {\n newVec.push_back(oldVec[oldI]);\n ++oldI;\n } else if (modIndex < oldIndex) {\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n ++modI;\n } else {\n \/\/ Same index - overwrite or delete existing attributes.\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n ++oldI;\n ++modI;\n }\n }\n\n for (; oldI < oldE; ++oldI)\n newVec.push_back(oldVec[oldI]);\n for (; modI < modE; ++modI)\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n\n return get(newVec);\n}\n\nconst ParamAttrsList *\nParamAttrsList::includeAttrs(const ParamAttrsList *PAL,\n uint16_t idx, ParameterAttributes attrs) {\n ParameterAttributes OldAttrs = PAL ? PAL->getParamAttrs(idx) : \n ParamAttr::None;\n#ifndef NDEBUG\n \/\/ FIXME it is not obvious how this should work for alignment.\n \/\/ For now, say we can't change a known alignment.\n ParameterAttributes OldAlign = OldAttrs & ParamAttr::Alignment;\n ParameterAttributes NewAlign = attrs & ParamAttr::Alignment;\n assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&\n \"Attempt to change alignment!\");\n#endif\n\n ParameterAttributes NewAttrs = OldAttrs | attrs;\n if (NewAttrs == OldAttrs)\n return PAL;\n\n ParamAttrsVector modVec(1);\n modVec[0] = ParamAttrsWithIndex::get(idx, NewAttrs);\n return getModified(PAL, modVec);\n}\n\nconst ParamAttrsList *\nParamAttrsList::excludeAttrs(const ParamAttrsList *PAL,\n uint16_t idx, ParameterAttributes attrs) {\n#ifndef NDEBUG\n \/\/ FIXME it is not obvious how this should work for alignment.\n \/\/ For now, say we can't pass in alignment, which no current use does.\n assert(!(attrs & ParamAttr::Alignment) && \"Attempt to exclude alignment!\");\n#endif\n ParameterAttributes OldAttrs = PAL ? PAL->getParamAttrs(idx) : \n ParamAttr::None;\n ParameterAttributes NewAttrs = OldAttrs & ~attrs;\n if (NewAttrs == OldAttrs)\n return PAL;\n\n ParamAttrsVector modVec(1);\n modVec[0] = ParamAttrsWithIndex::get(idx, NewAttrs);\n return getModified(PAL, modVec);\n}\n\nParameterAttributes ParamAttr::typeIncompatible (const Type *Ty) {\n ParameterAttributes Incompatible = None;\n\n if (!Ty->isInteger())\n \/\/ Attributes that only apply to integers.\n Incompatible |= SExt | ZExt;\n\n if (!isa(Ty))\n \/\/ Attributes that only apply to pointers.\n Incompatible |= ByVal | Nest | NoAlias | StructRet;\n\n return Incompatible;\n}\nUse utostr instead of a stringstream.\/\/===-- ParameterAttributes.cpp - Implement ParamAttrsList ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ParamAttrsList class and ParamAttr utilities.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ParamAttrsList.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\nusing namespace llvm;\n\nstatic ManagedStatic > ParamAttrsLists;\n\nParamAttrsList::ParamAttrsList(const ParamAttrsVector &attrVec) \n : attrs(attrVec), refCount(0) {\n}\n\nParamAttrsList::~ParamAttrsList() {\n ParamAttrsLists->RemoveNode(this);\n}\n\nParameterAttributes\nParamAttrsList::getParamAttrs(uint16_t Index) const {\n unsigned limit = attrs.size();\n for (unsigned i = 0; i < limit && attrs[i].index <= Index; ++i)\n if (attrs[i].index == Index)\n return attrs[i].attrs;\n return ParamAttr::None;\n}\n\nbool ParamAttrsList::hasAttrSomewhere(ParameterAttributes attr) const {\n for (unsigned i = 0, e = attrs.size(); i < e; ++i)\n if (attrs[i].attrs & attr)\n return true;\n return false;\n}\n\nstd::string \nParamAttrsList::getParamAttrsText(ParameterAttributes Attrs) {\n std::string Result;\n if (Attrs & ParamAttr::ZExt)\n Result += \"zeroext \";\n if (Attrs & ParamAttr::SExt)\n Result += \"signext \";\n if (Attrs & ParamAttr::NoReturn)\n Result += \"noreturn \";\n if (Attrs & ParamAttr::NoUnwind)\n Result += \"nounwind \";\n if (Attrs & ParamAttr::InReg)\n Result += \"inreg \";\n if (Attrs & ParamAttr::NoAlias)\n Result += \"noalias \";\n if (Attrs & ParamAttr::StructRet)\n Result += \"sret \"; \n if (Attrs & ParamAttr::ByVal)\n Result += \"byval \";\n if (Attrs & ParamAttr::Nest)\n Result += \"nest \";\n if (Attrs & ParamAttr::ReadNone)\n Result += \"readnone \";\n if (Attrs & ParamAttr::ReadOnly)\n Result += \"readonly \";\n if (Attrs & ParamAttr::Alignment) {\n Result += \"align \";\n Result += utostr((Attrs & ParamAttr::Alignment) >> 16);\n Result += \" \";\n }\n return Result;\n}\n\nvoid ParamAttrsList::Profile(FoldingSetNodeID &ID,\n const ParamAttrsVector &Attrs) {\n for (unsigned i = 0; i < Attrs.size(); ++i)\n ID.AddInteger(uint64_t(Attrs[i].attrs) << 16 | unsigned(Attrs[i].index));\n}\n\nconst ParamAttrsList *\nParamAttrsList::get(const ParamAttrsVector &attrVec) {\n \/\/ If there are no attributes then return a null ParamAttrsList pointer.\n if (attrVec.empty())\n return 0;\n\n#ifndef NDEBUG\n for (unsigned i = 0, e = attrVec.size(); i < e; ++i) {\n assert(attrVec[i].attrs != ParamAttr::None\n && \"Pointless parameter attribute!\");\n assert((!i || attrVec[i-1].index < attrVec[i].index)\n && \"Misordered ParamAttrsList!\");\n }\n#endif\n\n \/\/ Otherwise, build a key to look up the existing attributes.\n FoldingSetNodeID ID;\n ParamAttrsList::Profile(ID, attrVec);\n void *InsertPos;\n ParamAttrsList *PAL = ParamAttrsLists->FindNodeOrInsertPos(ID, InsertPos);\n\n \/\/ If we didn't find any existing attributes of the same shape then\n \/\/ create a new one and insert it.\n if (!PAL) {\n PAL = new ParamAttrsList(attrVec);\n ParamAttrsLists->InsertNode(PAL, InsertPos);\n }\n\n \/\/ Return the ParamAttrsList that we found or created.\n return PAL;\n}\n\nconst ParamAttrsList *\nParamAttrsList::getModified(const ParamAttrsList *PAL,\n const ParamAttrsVector &modVec) {\n if (modVec.empty())\n return PAL;\n\n#ifndef NDEBUG\n for (unsigned i = 0, e = modVec.size(); i < e; ++i)\n assert((!i || modVec[i-1].index < modVec[i].index)\n && \"Misordered ParamAttrsList!\");\n#endif\n\n if (!PAL) {\n \/\/ Strip any instances of ParamAttr::None from modVec before calling 'get'.\n ParamAttrsVector newVec;\n newVec.reserve(modVec.size());\n for (unsigned i = 0, e = modVec.size(); i < e; ++i)\n if (modVec[i].attrs != ParamAttr::None)\n newVec.push_back(modVec[i]);\n return get(newVec);\n }\n\n const ParamAttrsVector &oldVec = PAL->attrs;\n\n ParamAttrsVector newVec;\n unsigned oldI = 0;\n unsigned modI = 0;\n unsigned oldE = oldVec.size();\n unsigned modE = modVec.size();\n\n while (oldI < oldE && modI < modE) {\n uint16_t oldIndex = oldVec[oldI].index;\n uint16_t modIndex = modVec[modI].index;\n\n if (oldIndex < modIndex) {\n newVec.push_back(oldVec[oldI]);\n ++oldI;\n } else if (modIndex < oldIndex) {\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n ++modI;\n } else {\n \/\/ Same index - overwrite or delete existing attributes.\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n ++oldI;\n ++modI;\n }\n }\n\n for (; oldI < oldE; ++oldI)\n newVec.push_back(oldVec[oldI]);\n for (; modI < modE; ++modI)\n if (modVec[modI].attrs != ParamAttr::None)\n newVec.push_back(modVec[modI]);\n\n return get(newVec);\n}\n\nconst ParamAttrsList *\nParamAttrsList::includeAttrs(const ParamAttrsList *PAL,\n uint16_t idx, ParameterAttributes attrs) {\n ParameterAttributes OldAttrs = PAL ? PAL->getParamAttrs(idx) : \n ParamAttr::None;\n#ifndef NDEBUG\n \/\/ FIXME it is not obvious how this should work for alignment.\n \/\/ For now, say we can't change a known alignment.\n ParameterAttributes OldAlign = OldAttrs & ParamAttr::Alignment;\n ParameterAttributes NewAlign = attrs & ParamAttr::Alignment;\n assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&\n \"Attempt to change alignment!\");\n#endif\n\n ParameterAttributes NewAttrs = OldAttrs | attrs;\n if (NewAttrs == OldAttrs)\n return PAL;\n\n ParamAttrsVector modVec(1);\n modVec[0] = ParamAttrsWithIndex::get(idx, NewAttrs);\n return getModified(PAL, modVec);\n}\n\nconst ParamAttrsList *\nParamAttrsList::excludeAttrs(const ParamAttrsList *PAL,\n uint16_t idx, ParameterAttributes attrs) {\n#ifndef NDEBUG\n \/\/ FIXME it is not obvious how this should work for alignment.\n \/\/ For now, say we can't pass in alignment, which no current use does.\n assert(!(attrs & ParamAttr::Alignment) && \"Attempt to exclude alignment!\");\n#endif\n ParameterAttributes OldAttrs = PAL ? PAL->getParamAttrs(idx) : \n ParamAttr::None;\n ParameterAttributes NewAttrs = OldAttrs & ~attrs;\n if (NewAttrs == OldAttrs)\n return PAL;\n\n ParamAttrsVector modVec(1);\n modVec[0] = ParamAttrsWithIndex::get(idx, NewAttrs);\n return getModified(PAL, modVec);\n}\n\nParameterAttributes ParamAttr::typeIncompatible (const Type *Ty) {\n ParameterAttributes Incompatible = None;\n\n if (!Ty->isInteger())\n \/\/ Attributes that only apply to integers.\n Incompatible |= SExt | ZExt;\n\n if (!isa(Ty))\n \/\/ Attributes that only apply to pointers.\n Incompatible |= ByVal | Nest | NoAlias | StructRet;\n\n return Incompatible;\n}\n<|endoftext|>"} {"text":"\/\/===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer --------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ The AMDGPUAsmPrinter is used to print both assembly string and also binary\n\/\/\/ code. When passed an MCAsmStreamer it prints assembly and when passed\n\/\/\/ an MCObjectStreamer it outputs binary code.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\n\n#include \"AMDGPUAsmPrinter.h\"\n#include \"AMDGPU.h\"\n#include \"R600Defines.h\"\n#include \"R600MachineFunctionInfo.h\"\n#include \"R600RegisterInfo.h\"\n#include \"SIDefines.h\"\n#include \"SIMachineFunctionInfo.h\"\n#include \"SIRegisterInfo.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCSectionELF.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n\nusing namespace llvm;\n\n\nstatic AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm,\n MCStreamer &Streamer) {\n return new AMDGPUAsmPrinter(tm, Streamer);\n}\n\nextern \"C\" void LLVMInitializeR600AsmPrinter() {\n TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);\n}\n\nAMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)\n : AsmPrinter(TM, Streamer)\n{\n DisasmEnabled = TM.getSubtarget().dumpCode() &&\n ! Streamer.hasRawTextSupport();\n}\n\n\/\/\/ We need to override this function so we can avoid\n\/\/\/ the call to EmitFunctionHeader(), which the MCPureStreamer can't handle.\nbool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n SetupMachineFunction(MF);\n if (OutStreamer.hasRawTextSupport()) {\n OutStreamer.EmitRawText(\"@\" + MF.getName() + \":\");\n }\n\n MCContext &Context = getObjFileLowering().getContext();\n const MCSectionELF *ConfigSection = Context.getELFSection(\".AMDGPU.config\",\n ELF::SHT_PROGBITS, 0,\n SectionKind::getReadOnly());\n OutStreamer.SwitchSection(ConfigSection);\n const AMDGPUSubtarget &STM = TM.getSubtarget();\n if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {\n EmitProgramInfoSI(MF);\n } else {\n EmitProgramInfoR600(MF);\n }\n\n DisasmLines.clear();\n HexLines.clear();\n DisasmLineMaxLen = 0;\n\n OutStreamer.SwitchSection(getObjFileLowering().getTextSection());\n EmitFunctionBody();\n\n if (STM.dumpCode()) {\n#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n MF.dump();\n#endif\n\n if (DisasmEnabled) {\n OutStreamer.SwitchSection(Context.getELFSection(\".AMDGPU.disasm\",\n ELF::SHT_NOTE, 0,\n SectionKind::getReadOnly()));\n\n for (size_t i = 0; i < DisasmLines.size(); ++i) {\n std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');\n Comment += \" ; \" + HexLines[i] + \"\\n\";\n\n OutStreamer.EmitBytes(StringRef(DisasmLines[i]));\n OutStreamer.EmitBytes(StringRef(Comment));\n }\n }\n }\n\n return false;\n}\n\nvoid AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) {\n unsigned MaxGPR = 0;\n bool killPixel = false;\n const R600RegisterInfo * RI =\n static_cast(TM.getRegisterInfo());\n R600MachineFunctionInfo *MFI = MF.getInfo();\n const AMDGPUSubtarget &STM = TM.getSubtarget();\n\n for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();\n BB != BB_E; ++BB) {\n MachineBasicBlock &MBB = *BB;\n for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();\n I != E; ++I) {\n MachineInstr &MI = *I;\n if (MI.getOpcode() == AMDGPU::KILLGT)\n killPixel = true;\n unsigned numOperands = MI.getNumOperands();\n for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {\n MachineOperand & MO = MI.getOperand(op_idx);\n if (!MO.isReg())\n continue;\n unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;\n\n \/\/ Register with value > 127 aren't GPR\n if (HWReg > 127)\n continue;\n MaxGPR = std::max(MaxGPR, HWReg);\n }\n }\n }\n\n unsigned RsrcReg;\n if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) {\n \/\/ Evergreen \/ Northern Islands\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::COMPUTE: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;\n case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;\n case ShaderType::PIXEL: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;\n case ShaderType::VERTEX: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;\n }\n } else {\n \/\/ R600 \/ R700\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::GEOMETRY: \/\/ Fall through\n case ShaderType::COMPUTE: \/\/ Fall through\n case ShaderType::VERTEX: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;\n case ShaderType::PIXEL: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;\n }\n }\n\n OutStreamer.EmitIntValue(RsrcReg, 4);\n OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |\n S_STACK_SIZE(MFI->StackSize), 4);\n OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);\n OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);\n\n if (MFI->ShaderType == ShaderType::COMPUTE) {\n OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);\n OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4);\n }\n}\n\nvoid AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF) {\n unsigned MaxSGPR = 0;\n unsigned MaxVGPR = 0;\n bool VCCUsed = false;\n const SIRegisterInfo * RI =\n static_cast(TM.getRegisterInfo());\n\n for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();\n BB != BB_E; ++BB) {\n MachineBasicBlock &MBB = *BB;\n for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();\n I != E; ++I) {\n MachineInstr &MI = *I;\n\n unsigned numOperands = MI.getNumOperands();\n for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {\n MachineOperand & MO = MI.getOperand(op_idx);\n unsigned maxUsed;\n unsigned width = 0;\n bool isSGPR = false;\n unsigned reg;\n unsigned hwReg;\n if (!MO.isReg()) {\n continue;\n }\n reg = MO.getReg();\n if (reg == AMDGPU::VCC) {\n VCCUsed = true;\n continue;\n }\n switch (reg) {\n default: break;\n case AMDGPU::EXEC:\n case AMDGPU::M0:\n continue;\n }\n\n if (AMDGPU::SReg_32RegClass.contains(reg)) {\n isSGPR = true;\n width = 1;\n } else if (AMDGPU::VReg_32RegClass.contains(reg)) {\n isSGPR = false;\n width = 1;\n } else if (AMDGPU::SReg_64RegClass.contains(reg)) {\n isSGPR = true;\n width = 2;\n } else if (AMDGPU::VReg_64RegClass.contains(reg)) {\n isSGPR = false;\n width = 2;\n } else if (AMDGPU::VReg_96RegClass.contains(reg)) {\n isSGPR = false;\n width = 3;\n } else if (AMDGPU::SReg_128RegClass.contains(reg)) {\n isSGPR = true;\n width = 4;\n } else if (AMDGPU::VReg_128RegClass.contains(reg)) {\n isSGPR = false;\n width = 4;\n } else if (AMDGPU::SReg_256RegClass.contains(reg)) {\n isSGPR = true;\n width = 8;\n } else if (AMDGPU::VReg_256RegClass.contains(reg)) {\n isSGPR = false;\n width = 8;\n } else if (AMDGPU::VReg_512RegClass.contains(reg)) {\n isSGPR = false;\n width = 16;\n } else {\n assert(!\"Unknown register class\");\n }\n hwReg = RI->getEncodingValue(reg) & 0xff;\n maxUsed = hwReg + width - 1;\n if (isSGPR) {\n MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;\n } else {\n MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;\n }\n }\n }\n }\n if (VCCUsed) {\n MaxSGPR += 2;\n }\n SIMachineFunctionInfo * MFI = MF.getInfo();\n unsigned RsrcReg;\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::COMPUTE: RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break;\n case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break;\n case ShaderType::PIXEL: RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break;\n case ShaderType::VERTEX: RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break;\n }\n\n OutStreamer.EmitIntValue(RsrcReg, 4);\n OutStreamer.EmitIntValue(S_00B028_VGPRS(MaxVGPR \/ 4) | S_00B028_SGPRS(MaxSGPR \/ 8), 4);\n\n if (MFI->ShaderType == ShaderType::COMPUTE) {\n OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);\n OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(RoundUpToAlignment(MFI->LDSSize, 256) >> 8), 4);\n }\n if (MFI->ShaderType == ShaderType::PIXEL) {\n OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);\n OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(RoundUpToAlignment(MFI->LDSSize, 256) >> 8), 4);\n OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);\n OutStreamer.EmitIntValue(MFI->PSInputAddr, 4);\n }\n}\nR600\/SI: Don't assert on SCC usage\/\/===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer --------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ The AMDGPUAsmPrinter is used to print both assembly string and also binary\n\/\/\/ code. When passed an MCAsmStreamer it prints assembly and when passed\n\/\/\/ an MCObjectStreamer it outputs binary code.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\n\n#include \"AMDGPUAsmPrinter.h\"\n#include \"AMDGPU.h\"\n#include \"R600Defines.h\"\n#include \"R600MachineFunctionInfo.h\"\n#include \"R600RegisterInfo.h\"\n#include \"SIDefines.h\"\n#include \"SIMachineFunctionInfo.h\"\n#include \"SIRegisterInfo.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCSectionELF.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n\nusing namespace llvm;\n\n\nstatic AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm,\n MCStreamer &Streamer) {\n return new AMDGPUAsmPrinter(tm, Streamer);\n}\n\nextern \"C\" void LLVMInitializeR600AsmPrinter() {\n TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);\n}\n\nAMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)\n : AsmPrinter(TM, Streamer)\n{\n DisasmEnabled = TM.getSubtarget().dumpCode() &&\n ! Streamer.hasRawTextSupport();\n}\n\n\/\/\/ We need to override this function so we can avoid\n\/\/\/ the call to EmitFunctionHeader(), which the MCPureStreamer can't handle.\nbool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n SetupMachineFunction(MF);\n if (OutStreamer.hasRawTextSupport()) {\n OutStreamer.EmitRawText(\"@\" + MF.getName() + \":\");\n }\n\n MCContext &Context = getObjFileLowering().getContext();\n const MCSectionELF *ConfigSection = Context.getELFSection(\".AMDGPU.config\",\n ELF::SHT_PROGBITS, 0,\n SectionKind::getReadOnly());\n OutStreamer.SwitchSection(ConfigSection);\n const AMDGPUSubtarget &STM = TM.getSubtarget();\n if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {\n EmitProgramInfoSI(MF);\n } else {\n EmitProgramInfoR600(MF);\n }\n\n DisasmLines.clear();\n HexLines.clear();\n DisasmLineMaxLen = 0;\n\n OutStreamer.SwitchSection(getObjFileLowering().getTextSection());\n EmitFunctionBody();\n\n if (STM.dumpCode()) {\n#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n MF.dump();\n#endif\n\n if (DisasmEnabled) {\n OutStreamer.SwitchSection(Context.getELFSection(\".AMDGPU.disasm\",\n ELF::SHT_NOTE, 0,\n SectionKind::getReadOnly()));\n\n for (size_t i = 0; i < DisasmLines.size(); ++i) {\n std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');\n Comment += \" ; \" + HexLines[i] + \"\\n\";\n\n OutStreamer.EmitBytes(StringRef(DisasmLines[i]));\n OutStreamer.EmitBytes(StringRef(Comment));\n }\n }\n }\n\n return false;\n}\n\nvoid AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) {\n unsigned MaxGPR = 0;\n bool killPixel = false;\n const R600RegisterInfo * RI =\n static_cast(TM.getRegisterInfo());\n R600MachineFunctionInfo *MFI = MF.getInfo();\n const AMDGPUSubtarget &STM = TM.getSubtarget();\n\n for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();\n BB != BB_E; ++BB) {\n MachineBasicBlock &MBB = *BB;\n for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();\n I != E; ++I) {\n MachineInstr &MI = *I;\n if (MI.getOpcode() == AMDGPU::KILLGT)\n killPixel = true;\n unsigned numOperands = MI.getNumOperands();\n for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {\n MachineOperand & MO = MI.getOperand(op_idx);\n if (!MO.isReg())\n continue;\n unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;\n\n \/\/ Register with value > 127 aren't GPR\n if (HWReg > 127)\n continue;\n MaxGPR = std::max(MaxGPR, HWReg);\n }\n }\n }\n\n unsigned RsrcReg;\n if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) {\n \/\/ Evergreen \/ Northern Islands\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::COMPUTE: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;\n case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;\n case ShaderType::PIXEL: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;\n case ShaderType::VERTEX: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;\n }\n } else {\n \/\/ R600 \/ R700\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::GEOMETRY: \/\/ Fall through\n case ShaderType::COMPUTE: \/\/ Fall through\n case ShaderType::VERTEX: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;\n case ShaderType::PIXEL: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;\n }\n }\n\n OutStreamer.EmitIntValue(RsrcReg, 4);\n OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |\n S_STACK_SIZE(MFI->StackSize), 4);\n OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);\n OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);\n\n if (MFI->ShaderType == ShaderType::COMPUTE) {\n OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);\n OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4);\n }\n}\n\nvoid AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF) {\n unsigned MaxSGPR = 0;\n unsigned MaxVGPR = 0;\n bool VCCUsed = false;\n const SIRegisterInfo * RI =\n static_cast(TM.getRegisterInfo());\n\n for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();\n BB != BB_E; ++BB) {\n MachineBasicBlock &MBB = *BB;\n for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();\n I != E; ++I) {\n MachineInstr &MI = *I;\n\n unsigned numOperands = MI.getNumOperands();\n for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {\n MachineOperand & MO = MI.getOperand(op_idx);\n unsigned maxUsed;\n unsigned width = 0;\n bool isSGPR = false;\n unsigned reg;\n unsigned hwReg;\n if (!MO.isReg()) {\n continue;\n }\n reg = MO.getReg();\n if (reg == AMDGPU::VCC) {\n VCCUsed = true;\n continue;\n }\n\n switch (reg) {\n default: break;\n case AMDGPU::SCC:\n case AMDGPU::EXEC:\n case AMDGPU::M0:\n continue;\n }\n\n if (AMDGPU::SReg_32RegClass.contains(reg)) {\n isSGPR = true;\n width = 1;\n } else if (AMDGPU::VReg_32RegClass.contains(reg)) {\n isSGPR = false;\n width = 1;\n } else if (AMDGPU::SReg_64RegClass.contains(reg)) {\n isSGPR = true;\n width = 2;\n } else if (AMDGPU::VReg_64RegClass.contains(reg)) {\n isSGPR = false;\n width = 2;\n } else if (AMDGPU::VReg_96RegClass.contains(reg)) {\n isSGPR = false;\n width = 3;\n } else if (AMDGPU::SReg_128RegClass.contains(reg)) {\n isSGPR = true;\n width = 4;\n } else if (AMDGPU::VReg_128RegClass.contains(reg)) {\n isSGPR = false;\n width = 4;\n } else if (AMDGPU::SReg_256RegClass.contains(reg)) {\n isSGPR = true;\n width = 8;\n } else if (AMDGPU::VReg_256RegClass.contains(reg)) {\n isSGPR = false;\n width = 8;\n } else if (AMDGPU::VReg_512RegClass.contains(reg)) {\n isSGPR = false;\n width = 16;\n } else {\n assert(!\"Unknown register class\");\n }\n hwReg = RI->getEncodingValue(reg) & 0xff;\n maxUsed = hwReg + width - 1;\n if (isSGPR) {\n MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;\n } else {\n MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;\n }\n }\n }\n }\n if (VCCUsed) {\n MaxSGPR += 2;\n }\n SIMachineFunctionInfo * MFI = MF.getInfo();\n unsigned RsrcReg;\n switch (MFI->ShaderType) {\n default: \/\/ Fall through\n case ShaderType::COMPUTE: RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break;\n case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break;\n case ShaderType::PIXEL: RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break;\n case ShaderType::VERTEX: RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break;\n }\n\n OutStreamer.EmitIntValue(RsrcReg, 4);\n OutStreamer.EmitIntValue(S_00B028_VGPRS(MaxVGPR \/ 4) | S_00B028_SGPRS(MaxSGPR \/ 8), 4);\n\n if (MFI->ShaderType == ShaderType::COMPUTE) {\n OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);\n OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(RoundUpToAlignment(MFI->LDSSize, 256) >> 8), 4);\n }\n if (MFI->ShaderType == ShaderType::PIXEL) {\n OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);\n OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(RoundUpToAlignment(MFI->LDSSize, 256) >> 8), 4);\n OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);\n OutStreamer.EmitIntValue(MFI->PSInputAddr, 4);\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Name:\t canvas.cpp\n\/\/ Purpose:\t Implements the canvas class for the wxWindows application.\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n\/\/ For compilers that support precompilation, includes \"wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/TimeEngines.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n#include \"..\/Enviro.h\"\t\t\t\/\/ for g_App, GetTerrainScene\n#include \"canvas.h\"\n#include \"frame.h\"\n#include \"app.h\"\n\nDECLARE_APP(vtApp)\n\n\/*\n * vtGLCanvas implementation\n *\/\nBEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)\n\tEVT_CLOSE(vtGLCanvas::OnClose)\n\tEVT_SIZE(vtGLCanvas::OnSize)\n\tEVT_PAINT(vtGLCanvas::OnPaint)\n\tEVT_CHAR(vtGLCanvas::OnChar)\n\tEVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)\n\tEVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)\nEND_EVENT_TABLE()\n\nstatic vtGLCanvas *s_canvas = NULL;\n\n\nvtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,\n\tconst wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):\n wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)\n{\n\tparent->Show(TRUE);\n\tSetCurrent();\n\n\tm_StatusTimer.SetFrame((wxFrame *)parent);\n\tm_StatusTimer.Start(1000);\n\n\tm_bPainting = false;\n\tm_bRunning = true;\n\tm_bShowFrameRateChart = true;\n\n\ts_canvas = this;\n}\n\n\nvtGLCanvas::~vtGLCanvas(void)\n{\n}\n\nvoid EnableContinuousRendering(bool bTrue)\n{\n\tif (s_canvas)\n\t\ts_canvas->m_bRunning = bTrue;\n}\n\nvoid vtGLCanvas::QueueRefresh(bool eraseBackground)\n\t\/\/ A Refresh routine we can call from inside OnPaint.\n\t\/\/ (queues the events rather than dispatching them immediately).\n{\n\t\/\/ With wxGTK, you can't do a Refresh() in OnPaint because it doesn't\n\t\/\/ queue (post) a Refresh event for later. Rather it dispatches\n\t\/\/ (processes) the underlying events immediately via ProcessEvent\n\t\/\/ (read, recursive call). See the wxPostEvent docs and Refresh code\n\t\/\/ for more details.\n\tif ( eraseBackground ) \n\t{\n\t\twxEraseEvent eevent( GetId() );\n\t\teevent.SetEventObject( this );\n\t\twxPostEvent( GetEventHandler(), eevent );\n\t}\n\n\twxPaintEvent event( GetId() );\n\tevent.SetEventObject( this );\n\twxPostEvent( GetEventHandler(), event );\n}\n\nvoid StatusTimer::Notify()\n{\n\tif (!m_pFrame || !m_pFrame->GetStatusBar()) return;\n\n\tvtScene *scene = vtGetScene();\n\tif (!scene) return;\n\n\t\/\/ get framerate\n\tfloat fps = scene->GetFrameRate();\n\n\t\/\/ get time of day\n\tint hr, min, sec;\n\tGetTerrainScene()->m_pTime->GetTime(hr, min, sec);\n\n\tvtString str, str2;\n\tstr.Format(\"fps %3.1f, time %02d:%02d:%02d, \", fps, hr, min, sec);\n\n\tg_App.DescribeCoordinates(str2);\n\tstr += str2;\n\n\t\/\/ get CLOD triangle counts, if appropriate\n\tg_App.DescribeCLOD(str2);\n\tstr += str2;\n\n\tstr += g_App.m_strMessage;\n\n\tm_pFrame->SetStatusText((const char *)str);\n}\n\n\nvoid vtGLCanvas::OnPaint( wxPaintEvent& event )\n{\n\t\/\/ place the dc inside a scope, to delete it before the end of function\n\tif (1)\n\t{\n\t\t\/\/ This is a dummy, to avoid an endless succession of paint messages.\n\t\t\/\/ OnPaint handlers must always create a wxPaintDC.\n\t\twxPaintDC dc(this);\n#ifdef __WXMSW__\n\t\tif (!GetContext()) return;\n#endif\n\n\t\tif (m_bPainting || !m_bRunning) return;\n\n\t\tm_bPainting = true;\n\n\t\t\/\/ Render the Scene Graph\n\t\tvtGetScene()->DoUpdate();\n\n\t\tif (m_bShowFrameRateChart)\n\t\t\tvtGetScene()->DrawFrameRateChart();\n\n\t\tSwapBuffers();\n\n#ifdef WIN32\n\t\t\/\/ Call Refresh again for continuous rendering,\n\t\tif (m_bRunning)\n\t\t\tRefresh(FALSE);\n#else\n\t\t\/\/ Queue another refresh for continuous rendering.\n\t\t\/\/ (Yield first so we don't starve out keyboard & mouse events.)\n\t\t\/\/\n\t\t\/\/ FIXME: We may want to use a frame timer instead of immediate-\n\t\t\/\/ redraw so we don't eat so much CPU on machines that can\n\t\t\/\/ easily handle the frame rate.\n\t\twxYield();\n\t\tQueueRefresh(FALSE);\n#endif\n\n\t\t\/\/ update the status bar every 1\/10 of a second\n\t\tstatic float last_stat = 0.0f;\n\t\tfloat cur = vtGetTime();\n\t\tif (cur - last_stat > 0.1f)\n\t\t{\n\t\t\tlast_stat = cur;\n\t\t\tm_StatusTimer.Notify();\n\t\t}\n\n\t\tm_bPainting = false;\n\t}\n\n\t\/\/ Must allow some idle processing to occur - or the toolbars will not\n\t\/\/ update, and the close box will not respond!\n\twxGetApp().ProcessIdle();\n}\n\nvoid vtGLCanvas::OnClose(wxCloseEvent& event)\n{\n\tm_bRunning = false;\n}\n\nvoid vtGLCanvas::OnSize(wxSizeEvent& event)\n{\n \/\/ Presumably this is a wxMSWism. \n \/\/ For wxGTK & wxMotif, all canvas resize events occur before the context\n \/\/ is set. So ignore this context check and grab the window width\/height\n \/\/ when we get it so it (and derived values such as aspect ratio and\n \/\/ viewport parms) are computed correctly.\n#ifdef __WXMSW__\n\tif (!GetContext()) return;\n#endif\n\n\tSetCurrent();\n\tint width, height;\n\tGetClientSize(& width, & height);\n\n\tvtGetScene()->SetWindowSize(width, height);\n\n\twxGLCanvas::OnSize(event);\n}\n\nvoid vtGLCanvas::OnChar(wxKeyEvent& event)\n{\n\tlong key = event.KeyCode();\n\n\t\/\/ pass the char to the frame for it to do \"accelerator\" shortcuts\n\tvtFrame *frame = (vtFrame*) GetParent();\n\tframe->OnChar(event);\n\n\tint flags = 0;\n\n\tif (event.ControlDown())\n\t\tflags |= VT_CONTROL;\n\n\tif (event.ShiftDown())\n\t\tflags |= VT_SHIFT;\n\n\tif (event.AltDown())\n\t\tflags |= VT_ALT;\n\n\t\/\/ pass the char to the vtlib Scene\n\tvtGetScene()->OnKey(key, flags);\n}\n\nvoid vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)\n{\n\t\/\/ turn WX mouse event into a VT mouse event\n\tvtMouseEvent event;\n\twxEventType ev = event1.GetEventType();\n\tif (ev == wxEVT_LEFT_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_LEFT;\n\t} else if (ev == wxEVT_LEFT_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_LEFT;\n\t} else if (ev == wxEVT_MIDDLE_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_MIDDLE;\n\t} else if (ev == wxEVT_MIDDLE_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_MIDDLE;\n\t} else if (ev == wxEVT_RIGHT_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_RIGHT;\n\t} else if (ev == wxEVT_RIGHT_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_RIGHT;\n\t} else if (ev == wxEVT_MOTION) {\n\t\tevent.type = VT_MOVE;\n\t\tevent.button = VT_NONE;\n\t} else {\n\t\t\/\/ ignored mouse events, such as wxEVT_LEAVE_WINDOW\n\t\treturn;\n\t}\n\n\tif (ev == wxEVT_LEFT_DOWN || ev == wxEVT_MIDDLE_DOWN || ev == wxEVT_RIGHT_DOWN)\n\t\tCaptureMouse();\n\tif (ev == wxEVT_LEFT_UP || ev == wxEVT_MIDDLE_UP || ev == wxEVT_RIGHT_UP)\n\t\tReleaseMouse();\n\n\tevent.flags = 0;\n\twxCoord xpos, ypos;\n event1.GetPosition(&xpos, &ypos);\n\tevent.pos.Set(xpos, ypos);\n\n\tif (event1.ControlDown())\n\t\tevent.flags |= VT_CONTROL;\n\n\tif (event1.ShiftDown())\n\t\tevent.flags |= VT_SHIFT;\n\n\tif (event1.AltDown())\n\t\tevent.flags |= VT_ALT;\n\n\t\/\/ inform Enviro app\n\tg_App.OnMouse(event);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid vtGLCanvas::OnEraseBackground(wxEraseEvent& event)\n{\n\t\/\/ Do nothing, to avoid flashing.\n}\n\nset significant digits of framerate shown to 3 show time only if time is on\/\/\n\/\/ Name:\t canvas.cpp\n\/\/ Purpose:\t Implements the canvas class for the wxWindows application.\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n\/\/ For compilers that support precompilation, includes \"wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/TimeEngines.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n#include \"..\/Enviro.h\"\t\t\t\/\/ for g_App, GetTerrainScene\n#include \"canvas.h\"\n#include \"frame.h\"\n#include \"app.h\"\n\nDECLARE_APP(vtApp)\n\n\/*\n * vtGLCanvas implementation\n *\/\nBEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)\n\tEVT_CLOSE(vtGLCanvas::OnClose)\n\tEVT_SIZE(vtGLCanvas::OnSize)\n\tEVT_PAINT(vtGLCanvas::OnPaint)\n\tEVT_CHAR(vtGLCanvas::OnChar)\n\tEVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)\n\tEVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)\nEND_EVENT_TABLE()\n\nstatic vtGLCanvas *s_canvas = NULL;\n\n\nvtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,\n\tconst wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):\n wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)\n{\n\tparent->Show(TRUE);\n\tSetCurrent();\n\n\tm_StatusTimer.SetFrame((wxFrame *)parent);\n\tm_StatusTimer.Start(1000);\n\n\tm_bPainting = false;\n\tm_bRunning = true;\n\tm_bShowFrameRateChart = true;\n\n\ts_canvas = this;\n}\n\n\nvtGLCanvas::~vtGLCanvas(void)\n{\n}\n\nvoid EnableContinuousRendering(bool bTrue)\n{\n\tif (s_canvas)\n\t\ts_canvas->m_bRunning = bTrue;\n}\n\nvoid vtGLCanvas::QueueRefresh(bool eraseBackground)\n\t\/\/ A Refresh routine we can call from inside OnPaint.\n\t\/\/ (queues the events rather than dispatching them immediately).\n{\n\t\/\/ With wxGTK, you can't do a Refresh() in OnPaint because it doesn't\n\t\/\/ queue (post) a Refresh event for later. Rather it dispatches\n\t\/\/ (processes) the underlying events immediately via ProcessEvent\n\t\/\/ (read, recursive call). See the wxPostEvent docs and Refresh code\n\t\/\/ for more details.\n\tif ( eraseBackground ) \n\t{\n\t\twxEraseEvent eevent( GetId() );\n\t\teevent.SetEventObject( this );\n\t\twxPostEvent( GetEventHandler(), eevent );\n\t}\n\n\twxPaintEvent event( GetId() );\n\tevent.SetEventObject( this );\n\twxPostEvent( GetEventHandler(), event );\n}\n\nvoid StatusTimer::Notify()\n{\n\tif (!m_pFrame || !m_pFrame->GetStatusBar()) return;\n\n\tvtScene *scene = vtGetScene();\n\tif (!scene) return;\n\n\tvtString str, str2;\n\n\t\/\/ get framerate\n\tfloat fps = scene->GetFrameRate();\n\n\t\/\/ only show 3 significant digits\n\tif (fps < 10)\n\t\tstr.Format(\"fps %1.2f, \", fps);\n\telse if (fps < 80)\n\t\tstr.Format(\"fps %2.1f, \", fps);\n\telse\n\t\tstr.Format(\"fps %3.0f, \", fps);\n\n\t\/\/ get time of day\n\tTimeEngine *te = GetTerrainScene()->m_pTime;\n\tif (te->GetEnabled())\n\t{\n\t\tint hr, min, sec;\n\t\tte->GetTime(hr, min, sec);\n\n\t\tstr2.Format(\"time %02d:%02d:%02d, \", hr, min, sec);\n\t\tstr += str2;\n\t}\n\n\tg_App.DescribeCoordinates(str2);\n\tstr += str2;\n\n\t\/\/ get CLOD triangle counts, if appropriate\n\tg_App.DescribeCLOD(str2);\n\tstr += str2;\n\n\tstr += g_App.m_strMessage;\n\n\tm_pFrame->SetStatusText((const char *)str);\n}\n\n\nvoid vtGLCanvas::OnPaint( wxPaintEvent& event )\n{\n\t\/\/ place the dc inside a scope, to delete it before the end of function\n\tif (1)\n\t{\n\t\t\/\/ This is a dummy, to avoid an endless succession of paint messages.\n\t\t\/\/ OnPaint handlers must always create a wxPaintDC.\n\t\twxPaintDC dc(this);\n#ifdef __WXMSW__\n\t\tif (!GetContext()) return;\n#endif\n\n\t\tif (m_bPainting || !m_bRunning) return;\n\n\t\tm_bPainting = true;\n\n\t\t\/\/ Render the Scene Graph\n\t\tvtGetScene()->DoUpdate();\n\n\t\tif (m_bShowFrameRateChart)\n\t\t\tvtGetScene()->DrawFrameRateChart();\n\n\t\tSwapBuffers();\n\n#ifdef WIN32\n\t\t\/\/ Call Refresh again for continuous rendering,\n\t\tif (m_bRunning)\n\t\t\tRefresh(FALSE);\n#else\n\t\t\/\/ Queue another refresh for continuous rendering.\n\t\t\/\/ (Yield first so we don't starve out keyboard & mouse events.)\n\t\t\/\/\n\t\t\/\/ FIXME: We may want to use a frame timer instead of immediate-\n\t\t\/\/ redraw so we don't eat so much CPU on machines that can\n\t\t\/\/ easily handle the frame rate.\n\t\twxYield();\n\t\tQueueRefresh(FALSE);\n#endif\n\n\t\t\/\/ update the status bar every 1\/10 of a second\n\t\tstatic float last_stat = 0.0f;\n\t\tfloat cur = vtGetTime();\n\t\tif (cur - last_stat > 0.1f)\n\t\t{\n\t\t\tlast_stat = cur;\n\t\t\tm_StatusTimer.Notify();\n\t\t}\n\n\t\tm_bPainting = false;\n\t}\n\n\t\/\/ Must allow some idle processing to occur - or the toolbars will not\n\t\/\/ update, and the close box will not respond!\n\twxGetApp().ProcessIdle();\n}\n\nvoid vtGLCanvas::OnClose(wxCloseEvent& event)\n{\n\tm_bRunning = false;\n}\n\nvoid vtGLCanvas::OnSize(wxSizeEvent& event)\n{\n \/\/ Presumably this is a wxMSWism. \n \/\/ For wxGTK & wxMotif, all canvas resize events occur before the context\n \/\/ is set. So ignore this context check and grab the window width\/height\n \/\/ when we get it so it (and derived values such as aspect ratio and\n \/\/ viewport parms) are computed correctly.\n#ifdef __WXMSW__\n\tif (!GetContext()) return;\n#endif\n\n\tSetCurrent();\n\tint width, height;\n\tGetClientSize(& width, & height);\n\n\tvtGetScene()->SetWindowSize(width, height);\n\n\twxGLCanvas::OnSize(event);\n}\n\nvoid vtGLCanvas::OnChar(wxKeyEvent& event)\n{\n\tlong key = event.KeyCode();\n\n\t\/\/ pass the char to the frame for it to do \"accelerator\" shortcuts\n\tvtFrame *frame = (vtFrame*) GetParent();\n\tframe->OnChar(event);\n\n\tint flags = 0;\n\n\tif (event.ControlDown())\n\t\tflags |= VT_CONTROL;\n\n\tif (event.ShiftDown())\n\t\tflags |= VT_SHIFT;\n\n\tif (event.AltDown())\n\t\tflags |= VT_ALT;\n\n\t\/\/ pass the char to the vtlib Scene\n\tvtGetScene()->OnKey(key, flags);\n}\n\nvoid vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)\n{\n\t\/\/ turn WX mouse event into a VT mouse event\n\tvtMouseEvent event;\n\twxEventType ev = event1.GetEventType();\n\tif (ev == wxEVT_LEFT_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_LEFT;\n\t} else if (ev == wxEVT_LEFT_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_LEFT;\n\t} else if (ev == wxEVT_MIDDLE_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_MIDDLE;\n\t} else if (ev == wxEVT_MIDDLE_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_MIDDLE;\n\t} else if (ev == wxEVT_RIGHT_DOWN) {\n\t\tevent.type = VT_DOWN;\n\t\tevent.button = VT_RIGHT;\n\t} else if (ev == wxEVT_RIGHT_UP) {\n\t\tevent.type = VT_UP;\n\t\tevent.button = VT_RIGHT;\n\t} else if (ev == wxEVT_MOTION) {\n\t\tevent.type = VT_MOVE;\n\t\tevent.button = VT_NONE;\n\t} else {\n\t\t\/\/ ignored mouse events, such as wxEVT_LEAVE_WINDOW\n\t\treturn;\n\t}\n\n\tif (ev == wxEVT_LEFT_DOWN || ev == wxEVT_MIDDLE_DOWN || ev == wxEVT_RIGHT_DOWN)\n\t\tCaptureMouse();\n\tif (ev == wxEVT_LEFT_UP || ev == wxEVT_MIDDLE_UP || ev == wxEVT_RIGHT_UP)\n\t\tReleaseMouse();\n\n\tevent.flags = 0;\n\twxCoord xpos, ypos;\n event1.GetPosition(&xpos, &ypos);\n\tevent.pos.Set(xpos, ypos);\n\n\tif (event1.ControlDown())\n\t\tevent.flags |= VT_CONTROL;\n\n\tif (event1.ShiftDown())\n\t\tevent.flags |= VT_SHIFT;\n\n\tif (event1.AltDown())\n\t\tevent.flags |= VT_ALT;\n\n\t\/\/ inform Enviro app\n\tg_App.OnMouse(event);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid vtGLCanvas::OnEraseBackground(wxEraseEvent& event)\n{\n\t\/\/ Do nothing, to avoid flashing.\n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ this file defines the otbCommonTest for the test driver\n\/\/ and all it expects is that you have a function called RegisterTests\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n#include \"otbTestMain.h\" \n\n\nvoid RegisterTests()\n{\nREGISTER_TEST(otbRADImageIOTestCanRead);\nREGISTER_TEST(otbALOSImageIOTestCanRead);\nREGISTER_TEST(otbImageFileReaderTest);\n}\nBUG. ALOS data aren t yet coded\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ this file defines the otbCommonTest for the test driver\n\/\/ and all it expects is that you have a function called RegisterTests\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n#include \"otbTestMain.h\" \n\n\nvoid RegisterTests()\n{\nREGISTER_TEST(otbRADImageIOTestCanRead);\n\/\/REGISTER_TEST(otbALOSImageIOTestCanRead);\nREGISTER_TEST(otbImageFileReaderTest);\n}\n<|endoftext|>"} {"text":"#include \"UaParser.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n\ntypedef std::map i2tuple;\n\nstruct GenericStore {\n std::string replacement;\n i2tuple replacementMap;\n boost::regex regExpr;\n};\n\nstruct DeviceStore : GenericStore {\n std::string brandReplacement;\n std::string modelReplacement;\n i2tuple brandReplacementMap;\n i2tuple modelReplacementMap;\n};\n\nstruct AgentStore : GenericStore {\n std::string majorVersionReplacement;\n std::string minorVersionReplacement;\n std::string patchVersionReplacement;\n std::string patchMinorVersionReplacement;\n};\n\nvoid mark_placeholders(i2tuple& replacement_map, const std::string& device_property) {\n auto loc = device_property.rfind(\"$\");\n while (loc != std::string::npos) {\n replacement_map[loc] = std::stoi(device_property.substr(loc + 1, 1));\n\n if (loc < 2)\n break;\n\n loc = device_property.rfind(\"$\", loc - 2);\n }\n return;\n}\n\nAgentStore fill_agent_store(const YAML::Node& node,\n const std::string& repl,\n const std::string& major_repl,\n const std::string& minor_repl,\n const std::string& patch_repl) {\n AgentStore agent_store;\n assert(node.Type() == YAML::NodeType::Map);\n for (auto it = node.begin(); it != node.end(); ++it) {\n const auto key = it->first.as();\n const auto value = it->second.as();\n if (key == \"regex\") {\n agent_store.regExpr.assign(value, boost::regex::optimize | boost::regex::normal);\n } else if (key == repl) {\n agent_store.replacement = value;\n mark_placeholders(agent_store.replacementMap, agent_store.replacement);\n } else if (key == major_repl && !value.empty()) {\n agent_store.majorVersionReplacement = value;\n } else if (key == minor_repl && !value.empty()) {\n agent_store.minorVersionReplacement = value;\n } else if (key == patch_repl && !value.empty()) {\n agent_store.patchVersionReplacement = value;\n } else {\n assert(false);\n }\n }\n return agent_store;\n}\n\nstruct UAStore {\n explicit UAStore(const std::string& regexes_file_path) {\n auto regexes = YAML::LoadFile(regexes_file_path);\n\n const auto& user_agent_parsers = regexes[\"user_agent_parsers\"];\n for (const auto& user_agent : user_agent_parsers) {\n const auto browser =\n fill_agent_store(user_agent, \"family_replacement\", \"v1_replacement\", \"v2_replacement\", \"v3_replacement\");\n browserStore.push_back(browser);\n }\n\n const auto& os_parsers = regexes[\"os_parsers\"];\n for (const auto& o : os_parsers) {\n const auto os =\n fill_agent_store(o, \"os_replacement\", \"os_v1_replacement\", \"os_v2_replacement\", \"os_v3_replacement\");\n osStore.push_back(os);\n }\n\n const auto& device_parsers = regexes[\"device_parsers\"];\n for (const auto& d : device_parsers) {\n DeviceStore device;\n bool regex_flag = false;\n for (auto it = d.begin(); it != d.end(); ++it) {\n const auto key = it->first.as();\n const auto value = it->second.as();\n if (key == \"regex\") {\n device.regExpr.assign(value, boost::regex::optimize | boost::regex::normal);\n } else if (key == \"regex_flag\" && value == \"i\") {\n regex_flag = true;\n } else if (key == \"device_replacement\") {\n device.replacement = value;\n mark_placeholders(device.replacementMap, device.replacement);\n } else if (key == \"model_replacement\") {\n device.modelReplacement = value;\n mark_placeholders(device.modelReplacementMap, device.modelReplacement);\n } else if (key == \"brand_replacement\") {\n device.brandReplacement = value;\n mark_placeholders(device.brandReplacementMap, device.brandReplacement);\n } else {\n assert(false);\n }\n }\n if (regex_flag == true) {\n device.regExpr.assign(device.regExpr.str(),\n boost::regex::optimize | boost::regex::icase | boost::regex::normal);\n }\n deviceStore.push_back(device);\n }\n }\n\n std::vector deviceStore;\n std::vector osStore;\n std::vector browserStore;\n};\n\ntemplate \nvoid fill_agent(AGENT& agent, const AGENT_STORE& store, const boost::smatch& m, const bool os) {\n if (m.size() > 1) {\n agent.family =\n !store.replacement.empty() ? boost::regex_replace(store.replacement, boost::regex(\"\\\\$1\"), m[1].str()) : m[1];\n } else {\n agent.family =\n !store.replacement.empty() ? boost::regex_replace(store.replacement, boost::regex(\"\\\\$1\"), m[0].str()) : m[0];\n }\n boost::algorithm::trim(agent.family);\n\n \/\/ The chunk above is slightly faster than the one below.\n \/\/ if ( store.replacement.empty() && m.size() > 1) {\n \/\/ agent.family = m[1].str();\n \/\/ } else {\n \/\/ agent.family = store.replacement;\n \/\/ if ( ! store.replacementMap.empty()) {\n \/\/ replace_all_placeholders(agent.family,m,store.replacementMap);\n \/\/ }\n \/\/ }\n\n if (!store.majorVersionReplacement.empty()) {\n agent.major = store.majorVersionReplacement;\n } else if (m.size() > 2) {\n agent.major = m[2].str();\n }\n if (!store.minorVersionReplacement.empty()) {\n agent.minor = store.minorVersionReplacement;\n } else if (m.size() > 3) {\n agent.minor = m[3].str();\n }\n if (!store.patchVersionReplacement.empty()) {\n agent.patch = store.patchVersionReplacement;\n } else if (m.size() > 4) {\n agent.patch = m[4].str();\n }\n if (os && m.size() > 5) {\n agent.patch_minor = m[5].str();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ HELPERS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid replace_all_placeholders(std::string& ua_property, const boost::smatch& result, const i2tuple& replacement_map) {\n for (auto iter = replacement_map.rbegin(); iter != replacement_map.rend(); ++iter) {\n ua_property.replace(iter->first, 2, result[iter->second].str());\n }\n boost::algorithm::trim(ua_property);\n return;\n}\n\nUserAgent parse_impl(const std::string& ua, const UAStore* ua_store) {\n UserAgent uagent;\n\n for (const auto& b : ua_store->browserStore) {\n auto& browser = uagent.browser;\n boost::smatch m;\n if (boost::regex_search(ua, m, b.regExpr)) {\n fill_agent(browser, b, m, false);\n break;\n } else {\n browser.family = \"Other\";\n }\n }\n\n for (const auto& o : ua_store->osStore) {\n auto& os = uagent.os;\n boost::smatch m;\n if (boost::regex_search(ua, m, o.regExpr)) {\n fill_agent(os, o, m, true);\n break;\n } else {\n os.family = \"Other\";\n }\n }\n\n for (const auto& d : ua_store->deviceStore) {\n auto& device = uagent.device;\n boost::smatch m;\n\n if (boost::regex_search(ua, m, d.regExpr)) {\n if (d.replacement.empty() && m.size() > 1) {\n device.family = m[1].str();\n } else {\n device.family = d.replacement;\n if (!d.replacementMap.empty()) {\n replace_all_placeholders(device.family, m, d.replacementMap);\n }\n }\n\n if (!d.brandReplacement.empty()) {\n device.brand = d.brandReplacement;\n if (!d.brandReplacementMap.empty()) {\n replace_all_placeholders(device.brand, m, d.brandReplacementMap);\n }\n }\n if (d.modelReplacement.empty() && m.size() > 1) {\n device.model = m[1].str();\n } else {\n device.model = d.modelReplacement;\n if (!d.modelReplacementMap.empty()) {\n replace_all_placeholders(device.model, m, d.modelReplacementMap);\n }\n }\n break;\n } else {\n device.family = \"Other\";\n }\n }\n return uagent;\n}\n\n} \/\/ namespace\n\nUserAgentParser::UserAgentParser(const std::string& regexes_file_path) : regexes_file_path_{regexes_file_path} {\n ua_store_ = new UAStore(regexes_file_path);\n}\n\nUserAgentParser::~UserAgentParser() {\n delete static_cast(ua_store_);\n}\n\nUserAgent UserAgentParser::parse(const std::string& ua) const {\n return parse_impl(ua, static_cast(ua_store_));\n}\nSplit parse_impl#include \"UaParser.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n\ntypedef std::map i2tuple;\n\nstruct GenericStore {\n std::string replacement;\n i2tuple replacementMap;\n boost::regex regExpr;\n};\n\nstruct DeviceStore : GenericStore {\n std::string brandReplacement;\n std::string modelReplacement;\n i2tuple brandReplacementMap;\n i2tuple modelReplacementMap;\n};\n\nstruct AgentStore : GenericStore {\n std::string majorVersionReplacement;\n std::string minorVersionReplacement;\n std::string patchVersionReplacement;\n std::string patchMinorVersionReplacement;\n};\n\nvoid mark_placeholders(i2tuple& replacement_map, const std::string& device_property) {\n auto loc = device_property.rfind(\"$\");\n while (loc != std::string::npos) {\n replacement_map[loc] = std::stoi(device_property.substr(loc + 1, 1));\n\n if (loc < 2)\n break;\n\n loc = device_property.rfind(\"$\", loc - 2);\n }\n return;\n}\n\nAgentStore fill_agent_store(const YAML::Node& node,\n const std::string& repl,\n const std::string& major_repl,\n const std::string& minor_repl,\n const std::string& patch_repl) {\n AgentStore agent_store;\n assert(node.Type() == YAML::NodeType::Map);\n for (auto it = node.begin(); it != node.end(); ++it) {\n const auto key = it->first.as();\n const auto value = it->second.as();\n if (key == \"regex\") {\n agent_store.regExpr.assign(value, boost::regex::optimize | boost::regex::normal);\n } else if (key == repl) {\n agent_store.replacement = value;\n mark_placeholders(agent_store.replacementMap, agent_store.replacement);\n } else if (key == major_repl && !value.empty()) {\n agent_store.majorVersionReplacement = value;\n } else if (key == minor_repl && !value.empty()) {\n agent_store.minorVersionReplacement = value;\n } else if (key == patch_repl && !value.empty()) {\n agent_store.patchVersionReplacement = value;\n } else {\n assert(false);\n }\n }\n return agent_store;\n}\n\nstruct UAStore {\n explicit UAStore(const std::string& regexes_file_path) {\n auto regexes = YAML::LoadFile(regexes_file_path);\n\n const auto& user_agent_parsers = regexes[\"user_agent_parsers\"];\n for (const auto& user_agent : user_agent_parsers) {\n const auto browser =\n fill_agent_store(user_agent, \"family_replacement\", \"v1_replacement\", \"v2_replacement\", \"v3_replacement\");\n browserStore.push_back(browser);\n }\n\n const auto& os_parsers = regexes[\"os_parsers\"];\n for (const auto& o : os_parsers) {\n const auto os =\n fill_agent_store(o, \"os_replacement\", \"os_v1_replacement\", \"os_v2_replacement\", \"os_v3_replacement\");\n osStore.push_back(os);\n }\n\n const auto& device_parsers = regexes[\"device_parsers\"];\n for (const auto& d : device_parsers) {\n DeviceStore device;\n bool regex_flag = false;\n for (auto it = d.begin(); it != d.end(); ++it) {\n const auto key = it->first.as();\n const auto value = it->second.as();\n if (key == \"regex\") {\n device.regExpr.assign(value, boost::regex::optimize | boost::regex::normal);\n } else if (key == \"regex_flag\" && value == \"i\") {\n regex_flag = true;\n } else if (key == \"device_replacement\") {\n device.replacement = value;\n mark_placeholders(device.replacementMap, device.replacement);\n } else if (key == \"model_replacement\") {\n device.modelReplacement = value;\n mark_placeholders(device.modelReplacementMap, device.modelReplacement);\n } else if (key == \"brand_replacement\") {\n device.brandReplacement = value;\n mark_placeholders(device.brandReplacementMap, device.brandReplacement);\n } else {\n assert(false);\n }\n }\n if (regex_flag == true) {\n device.regExpr.assign(device.regExpr.str(),\n boost::regex::optimize | boost::regex::icase | boost::regex::normal);\n }\n deviceStore.push_back(device);\n }\n }\n\n std::vector deviceStore;\n std::vector osStore;\n std::vector browserStore;\n};\n\ntemplate \nvoid fill_agent(AGENT& agent, const AGENT_STORE& store, const boost::smatch& m, const bool os) {\n if (m.size() > 1) {\n agent.family =\n !store.replacement.empty() ? boost::regex_replace(store.replacement, boost::regex(\"\\\\$1\"), m[1].str()) : m[1];\n } else {\n agent.family =\n !store.replacement.empty() ? boost::regex_replace(store.replacement, boost::regex(\"\\\\$1\"), m[0].str()) : m[0];\n }\n boost::algorithm::trim(agent.family);\n\n \/\/ The chunk above is slightly faster than the one below.\n \/\/ if ( store.replacement.empty() && m.size() > 1) {\n \/\/ agent.family = m[1].str();\n \/\/ } else {\n \/\/ agent.family = store.replacement;\n \/\/ if ( ! store.replacementMap.empty()) {\n \/\/ replace_all_placeholders(agent.family,m,store.replacementMap);\n \/\/ }\n \/\/ }\n\n if (!store.majorVersionReplacement.empty()) {\n agent.major = store.majorVersionReplacement;\n } else if (m.size() > 2) {\n agent.major = m[2].str();\n }\n if (!store.minorVersionReplacement.empty()) {\n agent.minor = store.minorVersionReplacement;\n } else if (m.size() > 3) {\n agent.minor = m[3].str();\n }\n if (!store.patchVersionReplacement.empty()) {\n agent.patch = store.patchVersionReplacement;\n } else if (m.size() > 4) {\n agent.patch = m[4].str();\n }\n if (os && m.size() > 5) {\n agent.patch_minor = m[5].str();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ HELPERS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid replace_all_placeholders(std::string& ua_property, const boost::smatch& result, const i2tuple& replacement_map) {\n for (auto iter = replacement_map.rbegin(); iter != replacement_map.rend(); ++iter) {\n ua_property.replace(iter->first, 2, result[iter->second].str());\n }\n boost::algorithm::trim(ua_property);\n return;\n}\n\nDevice parse_device_impl(const std::string& ua, const UAStore* ua_store) {\n Device device;\n\n for (const auto& d : ua_store->deviceStore) {\n boost::smatch m;\n\n if (boost::regex_search(ua, m, d.regExpr)) {\n if (d.replacement.empty() && m.size() > 1) {\n device.family = m[1].str();\n } else {\n device.family = d.replacement;\n if (!d.replacementMap.empty()) {\n replace_all_placeholders(device.family, m, d.replacementMap);\n }\n }\n\n if (!d.brandReplacement.empty()) {\n device.brand = d.brandReplacement;\n if (!d.brandReplacementMap.empty()) {\n replace_all_placeholders(device.brand, m, d.brandReplacementMap);\n }\n }\n if (d.modelReplacement.empty() && m.size() > 1) {\n device.model = m[1].str();\n } else {\n device.model = d.modelReplacement;\n if (!d.modelReplacementMap.empty()) {\n replace_all_placeholders(device.model, m, d.modelReplacementMap);\n }\n }\n break;\n } else {\n device.family = \"Other\";\n }\n }\n\n return device;\n}\n\nAgent parse_browser_impl(const std::string& ua, const UAStore* ua_store) {\n Agent browser;\n\n for (const auto& b : ua_store->browserStore) {\n boost::smatch m;\n if (boost::regex_search(ua, m, b.regExpr)) {\n fill_agent(browser, b, m, false);\n break;\n } else {\n browser.family = \"Other\";\n }\n }\n\n return browser;\n}\n\nAgent parse_os_impl(const std::string& ua, const UAStore* ua_store) {\n Agent os;\n\n for (const auto& o : ua_store->osStore) {\n boost::smatch m;\n if (boost::regex_search(ua, m, o.regExpr)) {\n fill_agent(os, o, m, true);\n break;\n } else {\n os.family = \"Other\";\n }\n }\n\n return os;\n}\n\n} \/\/ namespace\n\nUserAgentParser::UserAgentParser(const std::string& regexes_file_path) : regexes_file_path_{regexes_file_path} {\n ua_store_ = new UAStore(regexes_file_path);\n}\n\nUserAgentParser::~UserAgentParser() {\n delete static_cast(ua_store_);\n}\n\nUserAgent UserAgentParser::parse(const std::string& ua) const {\n const auto ua_store = static_cast(ua_store_);\n\n const auto device = parse_device_impl(ua, ua_store);\n const auto os = parse_os_impl(ua, ua_store);\n const auto browser = parse_browser_impl(ua, ua_store);\n\n return {device, os, browser};\n}\n<|endoftext|>"} {"text":"\/*\r\n * Copyright 2009 Odbayar Nyamtseren \r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"Resource.h\"\r\n#include \"Globals.h\"\r\n#include \"InputContext.h\"\r\n#include \"CompString.h\"\r\n#include \"UiWindow.h\"\r\n\r\nnamespace \/* unnamed *\/\r\n{\r\n inline HIMC getImc(HWND hWnd)\r\n {\r\n return reinterpret_cast(GetWindowLongPtr(hWnd, IMMGWLP_IMC));\r\n }\r\n\r\n inline UiWindow* getUiWindowObject(HWND hWnd)\r\n {\r\n return reinterpret_cast(GetWindowLongPtr(hWnd, IMMGWLP_PRIVATE));\r\n }\r\n\r\n inline void setUiWindowObject(HWND hWnd, UiWindow* uiWnd)\r\n {\r\n SetWindowLongPtr(hWnd, IMMGWLP_PRIVATE, reinterpret_cast(uiWnd));\r\n }\r\n\r\n} \/\/ unnamed namespace\r\n\r\n\r\nUiWindow::UiWindow()\r\n{\r\n}\r\n\r\nUiWindow::~UiWindow()\r\n{\r\n}\r\n\r\nLRESULT UiWindow::imeSetContext(HWND wnd, WPARAM activate, LPARAM iscBits)\r\n{\r\n if (activate) {\r\n InputContext imc(getImc(wnd));\r\n\r\n if (imc.lock()) {\r\n if (iscBits & ISC_SHOWUICOMPOSITIONWINDOW) {\r\n CompString cs(imc);\r\n if (cs.lock() && cs.compStr.size() != 0) {\r\n compWnd.create(wnd);\r\n compWnd.update();\r\n compWnd.show();\r\n }\r\n }\r\n if (iscBits & ISC_SHOWUIGUIDELINE) {\r\n \/\/ TODO\r\n }\r\n }\r\n } else {\r\n if (iscBits & ISC_SHOWUICOMPOSITIONWINDOW) {\r\n if (compWnd.isOn()) {\r\n compWnd.hide();\r\n }\r\n }\r\n if (iscBits & ISC_SHOWUIGUIDELINE) {\r\n \/\/ TODO\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nLRESULT UiWindow::imeControl(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n InputContext imc(getImc(wnd));\r\n\r\n switch (wParam) {\r\n case IMC_GETCOMPOSITIONWINDOW:\r\n if (imc.lock()) {\r\n *(COMPOSITIONFORM*)lParam = imc->cfCompForm;\r\n return 0;\r\n }\r\n return 1;\r\n\r\n default:\r\n return 1;\r\n }\r\n}\r\n\r\nvoid UiWindow::imeSelect(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n}\r\n\r\nvoid UiWindow::imeNotify(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n InputContext imc(getImc(wnd));\r\n\r\n switch (wParam) {\r\n case IMN_SETOPENSTATUS:\r\n \/\/ TODO\r\n break;\r\n case IMN_SETCOMPOSITIONFONT:\r\n if (imc.lock()) {\r\n compWnd.setFont((LOGFONT*)&imc->lfFont);\r\n if (compWnd.isOn())\r\n compWnd.update();\r\n }\r\n break;\r\n case IMN_SETCOMPOSITIONWINDOW:\r\n if (compWnd.isOn())\r\n compWnd.update();\r\n break;\r\n case IMN_GUIDELINE:\r\n \/\/ TODO\r\n break;\r\n\r\n \/\/ No private notification messages yet\r\n case IMN_PRIVATE:\r\n break;\r\n\r\n \/\/ What should I do with these?\r\n case IMN_SETCONVERSIONMODE:\r\n case IMN_SETSENTENCEMODE:\r\n break;\r\n\r\n \/\/ We don't have a candidate window\r\n case IMN_CHANGECANDIDATE:\r\n case IMN_OPENCANDIDATE:\r\n case IMN_CLOSECANDIDATE:\r\n case IMN_SETCANDIDATEPOS:\r\n break;\r\n\r\n \/\/ We don't have a status window\r\n case IMN_CLOSESTATUSWINDOW:\r\n case IMN_OPENSTATUSWINDOW:\r\n case IMN_SETSTATUSWINDOWPOS:\r\n break;\r\n\r\n \/\/ We don't have a soft keyboard\r\n case IMN_SOFTKBDDESTROYED:\r\n break;\r\n }\r\n}\r\n\r\nvoid UiWindow::imeStartComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n compWnd.create(wnd);\r\n}\r\n\r\nvoid UiWindow::imeComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n if (compWnd.isOn()) {\r\n compWnd.update();\r\n compWnd.show();\r\n }\r\n}\r\n\r\nvoid UiWindow::imeEndComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n if (compWnd.isOn())\r\n compWnd.hide();\r\n}\r\n\r\nLRESULT CALLBACK UiWindow::windowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n UiWindow* uiWnd;\r\n\r\n switch (msg) {\r\n case WM_IME_SETCONTEXT:\r\n case WM_IME_CONTROL:\r\n case WM_IME_SELECT:\r\n case WM_IME_NOTIFY:\r\n case WM_IME_STARTCOMPOSITION:\r\n case WM_IME_COMPOSITION:\r\n case WM_IME_ENDCOMPOSITION:\r\n case WM_IME_COMPOSITIONFULL:\r\n uiWnd = getUiWindowObject(wnd);\r\n if (!uiWnd)\r\n return 0;\r\n break;\r\n }\r\n\r\n switch (msg) {\r\n case WM_CREATE:\r\n setUiWindowObject(wnd, new UiWindow());\r\n return 0;\r\n\r\n case WM_DESTROY:\r\n delete getUiWindowObject(wnd);\r\n return 0;\r\n\r\n case WM_IME_SETCONTEXT:\r\n return uiWnd->imeSetContext(wnd, wParam, lParam);\r\n\r\n case WM_IME_CONTROL:\r\n return uiWnd->imeControl(wnd, wParam, lParam);\r\n\r\n case WM_IME_SELECT:\r\n uiWnd->imeSelect(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_NOTIFY:\r\n uiWnd->imeNotify(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_STARTCOMPOSITION:\r\n uiWnd->imeStartComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_COMPOSITION:\r\n uiWnd->imeComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_ENDCOMPOSITION:\r\n uiWnd->imeEndComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_COMPOSITIONFULL:\r\n \/\/ How did this message get here?!\r\n return 0;\r\n\r\n default:\r\n return DefWindowProc(wnd, msg, wParam, lParam);\r\n }\r\n}\r\n\r\nvoid UiWindow::registerClass()\r\n{\r\n WNDCLASSEX wcex;\r\n\r\n wcex.cbSize = sizeof(WNDCLASSEX);\r\n wcex.style = CS_IME;\r\n wcex.lpfnWndProc = windowProc;\r\n wcex.cbClsExtra = 0;\r\n wcex.cbWndExtra = sizeof(LONG_PTR) * 2;\r\n wcex.hInstance = moduleInstance;\r\n wcex.hIcon = NULL;\r\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\r\n wcex.hbrBackground = NULL;\r\n wcex.lpszMenuName = NULL;\r\n wcex.lpszClassName = uiClassName;\r\n wcex.hIconSm = NULL;\r\n\r\n RegisterClassEx(&wcex);\r\n}\r\n\r\nvoid UiWindow::unregisterClass()\r\n{\r\n UnregisterClass(uiClassName, moduleInstance);\r\n}\r\nSome code cleanup.\/*\r\n * Copyright 2009 Odbayar Nyamtseren \r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"Resource.h\"\r\n#include \"Globals.h\"\r\n#include \"InputContext.h\"\r\n#include \"CompString.h\"\r\n#include \"UiWindow.h\"\r\n\r\nnamespace \/* unnamed *\/\r\n{\r\n inline HIMC getImc(HWND hWnd)\r\n {\r\n return reinterpret_cast(GetWindowLongPtr(hWnd, IMMGWLP_IMC));\r\n }\r\n\r\n inline UiWindow* getUiWindowObject(HWND hWnd)\r\n {\r\n return reinterpret_cast(GetWindowLongPtr(hWnd, IMMGWLP_PRIVATE));\r\n }\r\n\r\n inline void setUiWindowObject(HWND hWnd, UiWindow* uiWnd)\r\n {\r\n SetWindowLongPtr(hWnd, IMMGWLP_PRIVATE, reinterpret_cast(uiWnd));\r\n }\r\n\r\n} \/\/ unnamed namespace\r\n\r\n\r\nUiWindow::UiWindow()\r\n{\r\n}\r\n\r\nUiWindow::~UiWindow()\r\n{\r\n}\r\n\r\nLRESULT UiWindow::imeSetContext(HWND wnd, WPARAM activate, LPARAM iscBits)\r\n{\r\n if (activate) {\r\n InputContext imc(getImc(wnd));\r\n\r\n if (imc.lock()) {\r\n if (iscBits & ISC_SHOWUICOMPOSITIONWINDOW) {\r\n CompString cs(imc);\r\n if (cs.lock() && cs.compStr.size() != 0) {\r\n compWnd.create(wnd);\r\n compWnd.update();\r\n compWnd.show();\r\n }\r\n }\r\n }\r\n } else {\r\n if (iscBits & ISC_SHOWUICOMPOSITIONWINDOW) {\r\n if (compWnd.isOn()) {\r\n compWnd.hide();\r\n }\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nLRESULT UiWindow::imeControl(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n InputContext imc(getImc(wnd));\r\n LRESULT retValue = 1;\r\n\r\n switch (wParam) {\r\n case IMC_GETCOMPOSITIONWINDOW:\r\n if (imc.lock()) {\r\n *(COMPOSITIONFORM*)lParam = imc->cfCompForm;\r\n retValue = 0;\r\n }\r\n break;\r\n }\r\n\r\n return retValue;\r\n}\r\n\r\nvoid UiWindow::imeSelect(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n}\r\n\r\nvoid UiWindow::imeNotify(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n InputContext imc(getImc(wnd));\r\n\r\n switch (wParam) {\r\n case IMN_SETOPENSTATUS:\r\n \/\/ TODO\r\n break;\r\n case IMN_SETCOMPOSITIONFONT:\r\n if (imc.lock()) {\r\n compWnd.setFont((LOGFONT*)&imc->lfFont);\r\n if (compWnd.isOn())\r\n compWnd.update();\r\n }\r\n break;\r\n case IMN_SETCOMPOSITIONWINDOW:\r\n if (compWnd.isOn())\r\n compWnd.update();\r\n break;\r\n case IMN_GUIDELINE:\r\n \/\/ TODO\r\n break;\r\n\r\n \/\/ No private notification messages yet\r\n case IMN_PRIVATE:\r\n break;\r\n\r\n \/\/ What should I do with these?\r\n case IMN_SETCONVERSIONMODE:\r\n case IMN_SETSENTENCEMODE:\r\n break;\r\n\r\n \/\/ We don't have a candidate window\r\n case IMN_CHANGECANDIDATE:\r\n case IMN_OPENCANDIDATE:\r\n case IMN_CLOSECANDIDATE:\r\n case IMN_SETCANDIDATEPOS:\r\n break;\r\n\r\n \/\/ We don't have a status window\r\n case IMN_CLOSESTATUSWINDOW:\r\n case IMN_OPENSTATUSWINDOW:\r\n case IMN_SETSTATUSWINDOWPOS:\r\n break;\r\n\r\n \/\/ We don't have a soft keyboard\r\n case IMN_SOFTKBDDESTROYED:\r\n break;\r\n }\r\n}\r\n\r\nvoid UiWindow::imeStartComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n compWnd.create(wnd);\r\n}\r\n\r\nvoid UiWindow::imeComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n if (compWnd.isOn()) {\r\n compWnd.update();\r\n compWnd.show();\r\n }\r\n}\r\n\r\nvoid UiWindow::imeEndComposition(HWND wnd, WPARAM wParam, LPARAM lParam)\r\n{\r\n if (compWnd.isOn())\r\n compWnd.hide();\r\n}\r\n\r\nLRESULT CALLBACK UiWindow::windowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n UiWindow* uiWnd;\r\n\r\n switch (msg) {\r\n case WM_IME_SETCONTEXT:\r\n case WM_IME_CONTROL:\r\n case WM_IME_SELECT:\r\n case WM_IME_NOTIFY:\r\n case WM_IME_STARTCOMPOSITION:\r\n case WM_IME_COMPOSITION:\r\n case WM_IME_ENDCOMPOSITION:\r\n case WM_IME_COMPOSITIONFULL:\r\n uiWnd = getUiWindowObject(wnd);\r\n if (!uiWnd)\r\n return 0;\r\n break;\r\n }\r\n\r\n switch (msg) {\r\n case WM_CREATE:\r\n setUiWindowObject(wnd, new UiWindow());\r\n return 0;\r\n\r\n case WM_DESTROY:\r\n delete getUiWindowObject(wnd);\r\n return 0;\r\n\r\n case WM_IME_SETCONTEXT:\r\n return uiWnd->imeSetContext(wnd, wParam, lParam);\r\n\r\n case WM_IME_CONTROL:\r\n return uiWnd->imeControl(wnd, wParam, lParam);\r\n\r\n case WM_IME_SELECT:\r\n uiWnd->imeSelect(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_NOTIFY:\r\n uiWnd->imeNotify(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_STARTCOMPOSITION:\r\n uiWnd->imeStartComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_COMPOSITION:\r\n uiWnd->imeComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_ENDCOMPOSITION:\r\n uiWnd->imeEndComposition(wnd, wParam, lParam);\r\n return 0;\r\n\r\n case WM_IME_COMPOSITIONFULL:\r\n \/\/ How did this message get here?!\r\n return 0;\r\n\r\n default:\r\n return DefWindowProc(wnd, msg, wParam, lParam);\r\n }\r\n}\r\n\r\nvoid UiWindow::registerClass()\r\n{\r\n WNDCLASSEX wcex;\r\n\r\n wcex.cbSize = sizeof(WNDCLASSEX);\r\n wcex.style = CS_IME;\r\n wcex.lpfnWndProc = windowProc;\r\n wcex.cbClsExtra = 0;\r\n wcex.cbWndExtra = sizeof(LONG_PTR) * 2;\r\n wcex.hInstance = moduleInstance;\r\n wcex.hIcon = NULL;\r\n wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\r\n wcex.hbrBackground = NULL;\r\n wcex.lpszMenuName = NULL;\r\n wcex.lpszClassName = uiClassName;\r\n wcex.hIconSm = NULL;\r\n\r\n RegisterClassEx(&wcex);\r\n}\r\n\r\nvoid UiWindow::unregisterClass()\r\n{\r\n UnregisterClass(uiClassName, moduleInstance);\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Headcrash Industries LLC\n\n#include \"WindowsMessageHandlerExamplePrivatePCH.h\"\n#include \"ModuleInterface.h\"\n#include \"SlateApplication.h\"\n#include \"WindowsApplication.h\"\n#include \"WindowsMessageHelpers.h\"\n\n\n#define LOCTEXT_NAMESPACE \"FWindowsMessageHandlerExampleModule\"\n\n\n\/**\n * Example Windows message handler.\n *\/\nclass FExampleHandler\n\t: public IWindowsMessageHandler\n{\npublic:\n\n\t\/\/ IWindowsMessageHandler interface\n\n\tvirtual bool ProcessMessage(HWND Hwnd, uint32 Message, WPARAM WParam, LPARAM LParam, int32& OutResult) override\n\t{\n\t\t\/\/ log out some details for the received message\n\t\tGLog->Logf(TEXT(\"WindowsMessageHandlerExampleModule: hwnd = %i, msg = %s, wParam = %i, lParam = %i\"), Hwnd, *GetMessageName(Message), WParam, LParam);\n\n\t\t\/\/ we did not handle this message, so make sure it gets passed on to other handlers\n\t\treturn false;\n\t}\n};\n\n\n\/**\n * Implements the WindowsMessageHandlerExample module.\n *\/\nclass FWindowsMessageHandlerExampleModule\n\t: public IModuleInterface\n{\npublic:\n\n\t\/\/ IModuleInterface interface\n\n\tvirtual void FWindowsMessageHandlerExampleModule::StartupModule() override\n\t{\n\t\t\/\/ register our handler\n\t\tFWindowsApplication* Application = GetApplication();\n\n\t\tif (Application != nullptr)\n\t\t{\n\t\t\tApplication->AddMessageHandler(Handler);\n\t\t}\n\t}\n\n\n\tvirtual void FWindowsMessageHandlerExampleModule::ShutdownModule() override\n\t{\n\t\t\/\/ unregister our handler\n\t\tFWindowsApplication* Application = GetApplication();\n\n\t\tif (Application != nullptr)\n\t\t{\n\t\t\tApplication->RemoveMessageHandler(Handler);\n\t\t}\n\t}\n\nprotected:\n\n\tFWindowsApplication* GetApplication() const\n\t{\n\t\tif (!FSlateApplication::IsInitialized())\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn (FWindowsApplication*)FSlateApplication::Get().GetPlatformApplication().Get();\n\t}\n\nprivate:\n\n\tFExampleHandler Handler;\n};\n\n\n#undef LOCTEXT_NAMESPACE\n\t\nIMPLEMENT_MODULE(FWindowsMessageHandlerExampleModule, WindowsMessageHandlerExample)\nAdded support for 4.11\/\/ Copyright 2016 Headcrash Industries LLC\n\n#include \"WindowsMessageHandlerExamplePrivatePCH.h\"\n#include \"ModuleInterface.h\"\n#include \"SlateBasics.h\"\n#include \"WindowsApplication.h\"\n#include \"WindowsMessageHelpers.h\"\n\n\n#define LOCTEXT_NAMESPACE \"FWindowsMessageHandlerExampleModule\"\n\n\n\/**\n * Example Windows message handler.\n *\/\nclass FExampleHandler\n\t: public IWindowsMessageHandler\n{\npublic:\n\n\t\/\/ IWindowsMessageHandler interface\n\n\tvirtual bool ProcessMessage(HWND Hwnd, uint32 Message, WPARAM WParam, LPARAM LParam, int32& OutResult) override\n\t{\n\t\t\/\/ log out some details for the received message\n\t\tGLog->Logf(TEXT(\"WindowsMessageHandlerExampleModule: hwnd = %i, msg = %s, wParam = %i, lParam = %i\"), Hwnd, *GetMessageName(Message), WParam, LParam);\n\n\t\t\/\/ we did not handle this message, so make sure it gets passed on to other handlers\n\t\treturn false;\n\t}\n};\n\n\n\/**\n * Implements the WindowsMessageHandlerExample module.\n *\/\nclass FWindowsMessageHandlerExampleModule\n\t: public IModuleInterface\n{\npublic:\n\n\t\/\/ IModuleInterface interface\n\n\tvirtual void FWindowsMessageHandlerExampleModule::StartupModule() override\n\t{\n\t\t\/\/ register our handler\n\t\tFWindowsApplication* Application = GetApplication();\n\n\t\tif (Application != nullptr)\n\t\t{\n\t\t\tApplication->AddMessageHandler(Handler);\n\t\t}\n\t}\n\n\n\tvirtual void FWindowsMessageHandlerExampleModule::ShutdownModule() override\n\t{\n\t\t\/\/ unregister our handler\n\t\tFWindowsApplication* Application = GetApplication();\n\n\t\tif (Application != nullptr)\n\t\t{\n\t\t\tApplication->RemoveMessageHandler(Handler);\n\t\t}\n\t}\n\nprotected:\n\n\tFWindowsApplication* GetApplication() const\n\t{\n\t\tif (!FSlateApplication::IsInitialized())\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn (FWindowsApplication*)FSlateApplication::Get().GetPlatformApplication().Get();\n\t}\n\nprivate:\n\n\tFExampleHandler Handler;\n};\n\n\n#undef LOCTEXT_NAMESPACE\n\t\nIMPLEMENT_MODULE(FWindowsMessageHandlerExampleModule, WindowsMessageHandlerExample)\n<|endoftext|>"} {"text":"\/\/===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===\/\/\n\/\/\n\/\/ The LowerSwitch transformation rewrites switch statements with a sequence of\n\/\/ branches, which allows targets to get away with not implementing the switch\n\/\/ statement until it is convenient.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOperators.h\"\n#include \"llvm\/iPHINode.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/Statistic.h\"\n\nnamespace {\n Statistic<> NumLowered(\"lowerswitch\", \"Number of SwitchInst's replaced\");\n\n \/\/\/ LowerSwitch Pass - Replace all SwitchInst instructions with chained branch\n \/\/\/ instructions. Note that this cannot be a BasicBlock pass because it\n \/\/\/ modifies the CFG!\n struct LowerSwitch : public FunctionPass {\n bool runOnFunction(Function &F);\n void processSwitchInst(SwitchInst *SI);\n };\n\n RegisterOpt\n X(\"lowerswitch\", \"Lower SwitchInst's to branches\");\n}\n\n\/\/ createLowerSwitchPass - Interface to this file...\nFunctionPass *createLowerSwitchPass() {\n return new LowerSwitch();\n}\n\nbool LowerSwitch::runOnFunction(Function &F) {\n bool Changed = false;\n\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {\n BasicBlock *Cur = I++; \/\/ Advance over block so we don't traverse new blocks\n\n if (SwitchInst *SI = dyn_cast(Cur->getTerminator())) {\n Changed = true;\n processSwitchInst(SI);\n }\n }\n\n return Changed;\n}\n\n\/\/ processSwitchInst - Replace the specified switch instruction with a sequence\n\/\/ of chained basic blocks. Right now we just insert an incredibly stupid\n\/\/ linear sequence of branches. It would be better to do a balanced binary\n\/\/ search eventually. FIXME\n\/\/\nvoid LowerSwitch::processSwitchInst(SwitchInst *SI) {\n BasicBlock *CurBlock = SI->getParent();\n BasicBlock *OrigBlock = CurBlock;\n Function *F = CurBlock->getParent();\n Value *Val = SI->getOperand(0); \/\/ The value we are switching on...\n\n \/\/ Unlink the switch instruction from it's block.\n CurBlock->getInstList().remove(SI);\n\n \/\/ If there is only the default destination, don't bother with the code below.\n if (SI->getNumOperands() == 2) {\n CurBlock->getInstList().push_back(new BranchInst(SI->getDefaultDest()));\n delete SI;\n return;\n }\n\n \/\/ Expand comparisons for all of the non-default cases...\n for (unsigned i = 2, e = SI->getNumOperands(); i != e; i += 2) {\n \/\/ Insert a new basic block after the current one...\n BasicBlock *NextBlock;\n if (i != e-2) {\n NextBlock = new BasicBlock(\"switchblock\");\n F->getBasicBlockList().insert(CurBlock->getNext(), NextBlock);\n } else { \/\/ Last case, if it's not the value, go to default block.\n NextBlock = cast(SI->getDefaultDest());\n }\n\n \/\/ Make the seteq instruction...\n Instruction *Comp = new SetCondInst(Instruction::SetEQ, Val,\n SI->getOperand(i), \"switchcase\");\n CurBlock->getInstList().push_back(Comp);\n\n \/\/ Make the conditional branch...\n BasicBlock *Succ = cast(SI->getOperand(i+1));\n Instruction *Br = new BranchInst(Succ, NextBlock, Comp);\n CurBlock->getInstList().push_back(Br);\n\n \/\/ If there were any PHI nodes in this successor, rewrite one entry from\n \/\/ OrigBlock to come from CurBlock.\n for (BasicBlock::iterator I = Succ->begin();\n PHINode *PN = dyn_cast(I); ++I) {\n int BlockIdx = PN->getBasicBlockIndex(OrigBlock);\n assert(BlockIdx != -1 && \"Switch didn't go to this successor??\");\n PN->setIncomingBlock((unsigned)BlockIdx, CurBlock);\n }\n\n if (i == e-2) { \/\/ Is this looking at the default destination?\n \/\/ If there is an entry in any PHI nodes for the default edge, make sure\n \/\/ to update them as well.\n for (BasicBlock::iterator I = NextBlock->begin();\n PHINode *PN = dyn_cast(I); ++I) {\n int BlockIdx = PN->getBasicBlockIndex(OrigBlock);\n assert(BlockIdx != -1 && \"Switch didn't go to this successor??\");\n PN->setIncomingBlock((unsigned)BlockIdx, CurBlock);\n }\n }\n\n CurBlock = NextBlock; \/\/ Move on to the next condition\n }\n\n \/\/ We are now done with the switch instruction, delete it.\n delete SI;\n}\nBill contributed this major rewrite of the -lowerswitch pass to make it generate logarithmic conditional branch sequences instead of linear sequences. Thanks Bill!\/\/===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===\/\/\n\/\/\n\/\/ The LowerSwitch transformation rewrites switch statements with a sequence of\n\/\/ branches, which allows targets to get away with not implementing the switch\n\/\/ statement until it is convenient.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOperators.h\"\n#include \"llvm\/iPHINode.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/Statistic.h\"\n\nnamespace {\n Statistic<> NumLowered(\"lowerswitch\", \"Number of SwitchInst's replaced\");\n\n \/\/\/ LowerSwitch Pass - Replace all SwitchInst instructions with chained branch\n \/\/\/ instructions. Note that this cannot be a BasicBlock pass because it\n \/\/\/ modifies the CFG!\n class LowerSwitch : public FunctionPass {\n public:\n bool runOnFunction(Function &F);\n typedef std::pair Case;\n typedef std::vector::iterator CaseItr;\n private:\n void processSwitchInst(SwitchInst *SI);\n\n BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,\n BasicBlock* OrigBlock, BasicBlock* Default);\n BasicBlock* newLeafBlock(Case& Leaf, Value* Val,\n BasicBlock* OrigBlock, BasicBlock* Default);\n };\n\n \/\/\/ The comparison function for sorting the switch case values in the vector.\n struct CaseCmp {\n bool operator () (const LowerSwitch::Case& C1,\n const LowerSwitch::Case& C2) {\n if (const ConstantUInt* U1 = dyn_cast(C1.first))\n return U1->getValue() < cast(C2.first)->getValue();\n\n const ConstantSInt* S1 = dyn_cast(C1.first);\n return S1->getValue() < cast(C2.first)->getValue();\n }\n };\n\n RegisterOpt\n X(\"lowerswitch\", \"Lower SwitchInst's to branches\");\n}\n\n\/\/ createLowerSwitchPass - Interface to this file...\nFunctionPass *createLowerSwitchPass() {\n return new LowerSwitch();\n}\n\nbool LowerSwitch::runOnFunction(Function &F) {\n bool Changed = false;\n\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {\n BasicBlock *Cur = I++; \/\/ Advance over block so we don't traverse new blocks\n\n if (SwitchInst *SI = dyn_cast(Cur->getTerminator())) {\n Changed = true;\n processSwitchInst(SI);\n }\n }\n\n return Changed;\n}\n\n\/\/ operator<< - Used for debugging purposes.\n\/\/\nstd::ostream& operator << (std::ostream& O, std::vector& C)\n{\n O << \"[\";\n\n for (std::vector::iterator B = C.begin(), E = C.end();\n B != E; ) {\n O << *B->first;\n if (++B != E) O << \", \";\n }\n\n return O << \"]\";\n}\n\n\/\/ switchConvert - Convert the switch statement into a binary lookup of\n\/\/ the case values. The function recursively builds this tree.\n\/\/\nBasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,\n Value* Val, BasicBlock* OrigBlock,\n BasicBlock* Default)\n{\n unsigned Size = End - Begin;\n\n if (Size == 1)\n return newLeafBlock(*Begin, Val, OrigBlock, Default);\n\n unsigned Mid = Size \/ 2;\n std::vector LHS(Begin, Begin + Mid);\n DEBUG(std::cerr << \"LHS: \" << LHS << \"\\n\");\n std::vector RHS(Begin + Mid, End);\n DEBUG(std::cerr << \"RHS: \" << RHS << \"\\n\");\n\n Case& Pivot = *(Begin + Mid);\n DEBUG(std::cerr << \"Pivot ==> \"\n << cast(Pivot.first)->getValue() << \"\\n\");\n\n BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,\n OrigBlock, Default);\n BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,\n OrigBlock, Default);\n\n \/\/ Create a new node that checks if the value is < pivot. Go to the\n \/\/ left branch if it is and right branch if not.\n Function* F = OrigBlock->getParent();\n BasicBlock* NewNode = new BasicBlock(\"NodeBlock\");\n F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);\n\n SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,\n \"Pivot\");\n NewNode->getInstList().push_back(Comp);\n BranchInst* Br = new BranchInst(LBranch, RBranch, Comp);\n NewNode->getInstList().push_back(Br);\n return NewNode;\n}\n\n\/\/ newLeafBlock - Create a new leaf block for the binary lookup tree. It\n\/\/ checks if the switch's value == the case's value. If not, then it\n\/\/ jumps to the default branch. At this point in the tree, the value\n\/\/ can't be another valid case value, so the jump to the \"default\" branch\n\/\/ is warranted.\n\/\/\nBasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,\n BasicBlock* OrigBlock,\n BasicBlock* Default)\n{\n Function* F = OrigBlock->getParent();\n BasicBlock* NewLeaf = new BasicBlock(\"LeafBlock\");\n F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);\n\n \/\/ Make the seteq instruction...\n SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,\n Leaf.first, \"SwitchLeaf\");\n NewLeaf->getInstList().push_back(Comp);\n\n \/\/ Make the conditional branch...\n BasicBlock* Succ = Leaf.second;\n Instruction* Br = new BranchInst(Succ, Default, Comp);\n NewLeaf->getInstList().push_back(Br);\n\n \/\/ If there were any PHI nodes in this successor, rewrite one entry\n \/\/ from OrigBlock to come from NewLeaf.\n for (BasicBlock::iterator I = Succ->begin();\n PHINode* PN = dyn_cast(I); ++I) {\n int BlockIdx = PN->getBasicBlockIndex(OrigBlock);\n assert(BlockIdx != -1 && \"Switch didn't go to this successor??\");\n PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);\n }\n\n return NewLeaf;\n}\n\n\/\/ processSwitchInst - Replace the specified switch instruction with a sequence\n\/\/ of chained if-then insts in a balanced binary search.\n\/\/\nvoid LowerSwitch::processSwitchInst(SwitchInst *SI) {\n BasicBlock *CurBlock = SI->getParent();\n BasicBlock *OrigBlock = CurBlock;\n Function *F = CurBlock->getParent();\n Value *Val = SI->getOperand(0); \/\/ The value we are switching on...\n BasicBlock* Default = SI->getDefaultDest();\n\n \/\/ Unlink the switch instruction from it's block.\n CurBlock->getInstList().remove(SI);\n\n \/\/ If there is only the default destination, don't bother with the code below.\n if (SI->getNumOperands() == 2) {\n CurBlock->getInstList().push_back(new BranchInst(SI->getDefaultDest()));\n delete SI;\n return;\n }\n\n \/\/ Create a new, empty default block so that the new hierarchy of\n \/\/ if-then statements go to this and the PHI nodes are happy.\n BasicBlock* NewDefault = new BasicBlock(\"NewDefault\");\n F->getBasicBlockList().insert(Default, NewDefault);\n\n NewDefault->getInstList().push_back(new BranchInst(Default));\n\n \/\/ If there is an entry in any PHI nodes for the default edge, make sure\n \/\/ to update them as well.\n for (BasicBlock::iterator I = Default->begin();\n PHINode *PN = dyn_cast(I); ++I) {\n int BlockIdx = PN->getBasicBlockIndex(OrigBlock);\n assert(BlockIdx != -1 && \"Switch didn't go to this successor??\");\n PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);\n }\n\n std::vector Cases;\n\n \/\/ Expand comparisons for all of the non-default cases...\n for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)\n Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));\n\n std::sort(Cases.begin(), Cases.end(), CaseCmp());\n DEBUG(std::cerr << \"Cases: \" << Cases << \"\\n\");\n BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,\n OrigBlock, NewDefault);\n\n \/\/ Branch to our shiny new if-then stuff...\n OrigBlock->getInstList().push_back(new BranchInst(SwitchBlock));\n\n \/\/ We are now done with the switch instruction, delete it.\n delete SI;\n}\n<|endoftext|>"} {"text":"\/\/===- ValueMapper.cpp - Interface shared by lib\/Transforms\/Utils ---------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the MapValue function, which is shared by various parts of\n\/\/ the lib\/Transforms\/Utils library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/ValueMapper.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/InlineAsm.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Metadata.h\"\nusing namespace llvm;\n\n\/\/ Out of line method to get vtable etc for class.\nvoid ValueMapTypeRemapper::anchor() {}\nvoid ValueMaterializer::anchor() {}\n\nValue *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n ValueToValueMapTy::iterator I = VM.find(V);\n \n \/\/ If the value already exists in the map, use it.\n if (I != VM.end() && I->second) return I->second;\n \n \/\/ If we have a materializer and it can materialize a value, use that.\n if (Materializer) {\n if (Value *NewV = Materializer->materializeValueFor(const_cast(V)))\n return VM[V] = NewV;\n }\n\n \/\/ Global values do not need to be seeded into the VM if they\n \/\/ are using the identity mapping.\n if (isa(V))\n return VM[V] = const_cast(V);\n \n if (const InlineAsm *IA = dyn_cast(V)) {\n \/\/ Inline asm may need *type* remapping.\n FunctionType *NewTy = IA->getFunctionType();\n if (TypeMapper) {\n NewTy = cast(TypeMapper->remapType(NewTy));\n\n if (NewTy != IA->getFunctionType())\n V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),\n IA->hasSideEffects(), IA->isAlignStack());\n }\n \n return VM[V] = const_cast(V);\n }\n\n if (const auto *MDV = dyn_cast(V)) {\n const Metadata *MD = MDV->getMetadata();\n \/\/ If this is a module-level metadata and we know that nothing at the module\n \/\/ level is changing, then use an identity mapping.\n if (!isa(MD) && (Flags & RF_NoModuleLevelChanges))\n return VM[V] = const_cast(V);\n\n auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);\n if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))\n return VM[V] = const_cast(V);\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ assert(MappedMD && \"Referenced metadata value not in value map\");\n return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);\n }\n\n \/\/ Okay, this either must be a constant (which may or may not be mappable) or\n \/\/ is something that is not in the mapping table.\n Constant *C = const_cast(dyn_cast(V));\n if (!C)\n return nullptr;\n \n if (BlockAddress *BA = dyn_cast(C)) {\n Function *F = \n cast(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));\n BasicBlock *BB = cast_or_null(MapValue(BA->getBasicBlock(), VM,\n Flags, TypeMapper, Materializer));\n return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());\n }\n \n \/\/ Otherwise, we have some other constant to remap. Start by checking to see\n \/\/ if all operands have an identity remapping.\n unsigned OpNo = 0, NumOperands = C->getNumOperands();\n Value *Mapped = nullptr;\n for (; OpNo != NumOperands; ++OpNo) {\n Value *Op = C->getOperand(OpNo);\n Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);\n if (Mapped != C) break;\n }\n \n \/\/ See if the type mapper wants to remap the type as well.\n Type *NewTy = C->getType();\n if (TypeMapper)\n NewTy = TypeMapper->remapType(NewTy);\n\n \/\/ If the result type and all operands match up, then just insert an identity\n \/\/ mapping.\n if (OpNo == NumOperands && NewTy == C->getType())\n return VM[V] = C;\n \n \/\/ Okay, we need to create a new constant. We've already processed some or\n \/\/ all of the operands, set them all up now.\n SmallVector Ops;\n Ops.reserve(NumOperands);\n for (unsigned j = 0; j != OpNo; ++j)\n Ops.push_back(cast(C->getOperand(j)));\n \n \/\/ If one of the operands mismatch, push it and the other mapped operands.\n if (OpNo != NumOperands) {\n Ops.push_back(cast(Mapped));\n \n \/\/ Map the rest of the operands that aren't processed yet.\n for (++OpNo; OpNo != NumOperands; ++OpNo)\n Ops.push_back(MapValue(cast(C->getOperand(OpNo)), VM,\n Flags, TypeMapper, Materializer));\n }\n \n if (ConstantExpr *CE = dyn_cast(C))\n return VM[V] = CE->getWithOperands(Ops, NewTy);\n if (isa(C))\n return VM[V] = ConstantArray::get(cast(NewTy), Ops);\n if (isa(C))\n return VM[V] = ConstantStruct::get(cast(NewTy), Ops);\n if (isa(C))\n return VM[V] = ConstantVector::get(Ops);\n \/\/ If this is a no-operand constant, it must be because the type was remapped.\n if (isa(C))\n return VM[V] = UndefValue::get(NewTy);\n if (isa(C))\n return VM[V] = ConstantAggregateZero::get(NewTy);\n assert(isa(C));\n return VM[V] = ConstantPointerNull::get(cast(NewTy));\n}\n\nstatic Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,\n Metadata *Val) {\n VM.MD()[Key].reset(Val);\n return Val;\n}\n\nstatic Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {\n return mapToMetadata(VM, MD, const_cast(MD));\n}\n\nstatic Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer);\n\nstatic Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n if (!Op)\n return nullptr;\n if (Metadata *MappedOp =\n MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))\n return MappedOp;\n \/\/ Use identity map if MappedOp is null and we can ignore missing entries.\n if (Flags & RF_IgnoreMissingEntries)\n return Op;\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ llvm_unreachable(\"Referenced metadata not in value map!\");\n return nullptr;\n}\n\n\/\/\/ \\brief Map a distinct MDNode.\n\/\/\/\n\/\/\/ Distinct nodes are not uniqued, so they must always recreated.\nstatic Metadata *mapDistinctNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n assert(Node->isDistinct() && \"Expected distinct node\");\n\n \/\/ Create the node first so it's available for cyclical references.\n SmallVector EmptyOps(Node->getNumOperands());\n MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);\n mapToMetadata(VM, Node, NewMD);\n\n \/\/ Fix the operands.\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)\n NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,\n TypeMapper, Materializer));\n\n return NewMD;\n}\n\n\/\/\/ \\brief Check whether a uniqued node needs to be remapped.\n\/\/\/\n\/\/\/ Check whether a uniqued node needs to be remapped (due to any operands\n\/\/\/ changing).\nstatic bool shouldRemapUniquedNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n \/\/ Check all operands to see if any need to be remapped.\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {\n Metadata *Op = Node->getOperand(I);\n if (Op != mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer))\n return true;\n }\n return false;\n}\n\n\/\/\/ \\brief Map a uniqued MDNode.\n\/\/\/\n\/\/\/ Uniqued nodes may not need to be recreated (they may map to themselves).\nstatic Metadata *mapUniquedNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n assert(!Node->isDistinct() && \"Expected uniqued node\");\n\n \/\/ Create a dummy node in case we have a metadata cycle.\n MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);\n mapToMetadata(VM, Node, Dummy);\n\n \/\/ Check all operands to see if any need to be remapped.\n if (!shouldRemapUniquedNode(Node, VM, Flags, TypeMapper, Materializer)) {\n \/\/ Use an identity mapping.\n mapToSelf(VM, Node);\n MDNode::deleteTemporary(Dummy);\n return const_cast(static_cast(Node));\n }\n\n \/\/ At least one operand needs remapping.\n SmallVector Elts;\n Elts.reserve(Node->getNumOperands());\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)\n Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,\n Materializer));\n\n MDNode *NewMD = MDTuple::get(Node->getContext(), Elts);\n Dummy->replaceAllUsesWith(NewMD);\n MDNode::deleteTemporary(Dummy);\n return mapToMetadata(VM, Node, NewMD);\n}\n\nstatic Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n \/\/ If the value already exists in the map, use it.\n if (Metadata *NewMD = VM.MD().lookup(MD).get())\n return NewMD;\n\n if (isa(MD))\n return mapToSelf(VM, MD);\n\n if (isa(MD))\n if ((Flags & RF_NoModuleLevelChanges))\n return mapToSelf(VM, MD);\n\n if (const auto *VMD = dyn_cast(MD)) {\n Value *MappedV =\n MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);\n if (VMD->getValue() == MappedV ||\n (!MappedV && (Flags & RF_IgnoreMissingEntries)))\n return mapToSelf(VM, MD);\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ assert(MappedV && \"Referenced metadata not in value map!\");\n if (MappedV)\n return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));\n return nullptr;\n }\n\n const UniquableMDNode *Node = cast(MD);\n assert(Node->isResolved() && \"Unexpected unresolved node\");\n\n \/\/ If this is a module-level metadata and we know that nothing at the\n \/\/ module level is changing, then use an identity mapping.\n if (Flags & RF_NoModuleLevelChanges)\n return mapToSelf(VM, MD);\n\n if (Node->isDistinct())\n return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);\n\n return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);\n}\n\nMetadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);\n if (NewMD && NewMD != MD)\n if (auto *N = dyn_cast(NewMD))\n N->resolveCycles();\n return NewMD;\n}\n\nMDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n return cast(MapMetadata(static_cast(MD), VM, Flags,\n TypeMapper, Materializer));\n}\n\n\/\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/\/ current values into those specified by VMap.\n\/\/\/\nvoid llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer){\n \/\/ Remap operands.\n for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {\n Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);\n \/\/ If we aren't ignoring missing entries, assert that something happened.\n if (V)\n *op = V;\n else\n assert((Flags & RF_IgnoreMissingEntries) &&\n \"Referenced value not in value map!\");\n }\n\n \/\/ Remap phi nodes' incoming blocks.\n if (PHINode *PN = dyn_cast(I)) {\n for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {\n Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);\n \/\/ If we aren't ignoring missing entries, assert that something happened.\n if (V)\n PN->setIncomingBlock(i, cast(V));\n else\n assert((Flags & RF_IgnoreMissingEntries) &&\n \"Referenced block not in value map!\");\n }\n }\n\n \/\/ Remap attached metadata.\n SmallVector, 4> MDs;\n I->getAllMetadata(MDs);\n for (SmallVectorImpl>::iterator\n MI = MDs.begin(),\n ME = MDs.end();\n MI != ME; ++MI) {\n MDNode *Old = MI->second;\n MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);\n if (New != Old)\n I->setMetadata(MI->first, New);\n }\n \n \/\/ If the instruction's type is being remapped, do so now.\n if (TypeMapper)\n I->mutateType(TypeMapper->remapType(I->getType()));\n}\nUtils: Extract cloneMDTuple(), NFC\/\/===- ValueMapper.cpp - Interface shared by lib\/Transforms\/Utils ---------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the MapValue function, which is shared by various parts of\n\/\/ the lib\/Transforms\/Utils library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/ValueMapper.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/InlineAsm.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Metadata.h\"\nusing namespace llvm;\n\n\/\/ Out of line method to get vtable etc for class.\nvoid ValueMapTypeRemapper::anchor() {}\nvoid ValueMaterializer::anchor() {}\n\nValue *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n ValueToValueMapTy::iterator I = VM.find(V);\n \n \/\/ If the value already exists in the map, use it.\n if (I != VM.end() && I->second) return I->second;\n \n \/\/ If we have a materializer and it can materialize a value, use that.\n if (Materializer) {\n if (Value *NewV = Materializer->materializeValueFor(const_cast(V)))\n return VM[V] = NewV;\n }\n\n \/\/ Global values do not need to be seeded into the VM if they\n \/\/ are using the identity mapping.\n if (isa(V))\n return VM[V] = const_cast(V);\n \n if (const InlineAsm *IA = dyn_cast(V)) {\n \/\/ Inline asm may need *type* remapping.\n FunctionType *NewTy = IA->getFunctionType();\n if (TypeMapper) {\n NewTy = cast(TypeMapper->remapType(NewTy));\n\n if (NewTy != IA->getFunctionType())\n V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),\n IA->hasSideEffects(), IA->isAlignStack());\n }\n \n return VM[V] = const_cast(V);\n }\n\n if (const auto *MDV = dyn_cast(V)) {\n const Metadata *MD = MDV->getMetadata();\n \/\/ If this is a module-level metadata and we know that nothing at the module\n \/\/ level is changing, then use an identity mapping.\n if (!isa(MD) && (Flags & RF_NoModuleLevelChanges))\n return VM[V] = const_cast(V);\n\n auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);\n if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))\n return VM[V] = const_cast(V);\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ assert(MappedMD && \"Referenced metadata value not in value map\");\n return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);\n }\n\n \/\/ Okay, this either must be a constant (which may or may not be mappable) or\n \/\/ is something that is not in the mapping table.\n Constant *C = const_cast(dyn_cast(V));\n if (!C)\n return nullptr;\n \n if (BlockAddress *BA = dyn_cast(C)) {\n Function *F = \n cast(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));\n BasicBlock *BB = cast_or_null(MapValue(BA->getBasicBlock(), VM,\n Flags, TypeMapper, Materializer));\n return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());\n }\n \n \/\/ Otherwise, we have some other constant to remap. Start by checking to see\n \/\/ if all operands have an identity remapping.\n unsigned OpNo = 0, NumOperands = C->getNumOperands();\n Value *Mapped = nullptr;\n for (; OpNo != NumOperands; ++OpNo) {\n Value *Op = C->getOperand(OpNo);\n Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);\n if (Mapped != C) break;\n }\n \n \/\/ See if the type mapper wants to remap the type as well.\n Type *NewTy = C->getType();\n if (TypeMapper)\n NewTy = TypeMapper->remapType(NewTy);\n\n \/\/ If the result type and all operands match up, then just insert an identity\n \/\/ mapping.\n if (OpNo == NumOperands && NewTy == C->getType())\n return VM[V] = C;\n \n \/\/ Okay, we need to create a new constant. We've already processed some or\n \/\/ all of the operands, set them all up now.\n SmallVector Ops;\n Ops.reserve(NumOperands);\n for (unsigned j = 0; j != OpNo; ++j)\n Ops.push_back(cast(C->getOperand(j)));\n \n \/\/ If one of the operands mismatch, push it and the other mapped operands.\n if (OpNo != NumOperands) {\n Ops.push_back(cast(Mapped));\n \n \/\/ Map the rest of the operands that aren't processed yet.\n for (++OpNo; OpNo != NumOperands; ++OpNo)\n Ops.push_back(MapValue(cast(C->getOperand(OpNo)), VM,\n Flags, TypeMapper, Materializer));\n }\n \n if (ConstantExpr *CE = dyn_cast(C))\n return VM[V] = CE->getWithOperands(Ops, NewTy);\n if (isa(C))\n return VM[V] = ConstantArray::get(cast(NewTy), Ops);\n if (isa(C))\n return VM[V] = ConstantStruct::get(cast(NewTy), Ops);\n if (isa(C))\n return VM[V] = ConstantVector::get(Ops);\n \/\/ If this is a no-operand constant, it must be because the type was remapped.\n if (isa(C))\n return VM[V] = UndefValue::get(NewTy);\n if (isa(C))\n return VM[V] = ConstantAggregateZero::get(NewTy);\n assert(isa(C));\n return VM[V] = ConstantPointerNull::get(cast(NewTy));\n}\n\nstatic Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,\n Metadata *Val) {\n VM.MD()[Key].reset(Val);\n return Val;\n}\n\nstatic Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {\n return mapToMetadata(VM, MD, const_cast(MD));\n}\n\nstatic Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer);\n\nstatic Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n if (!Op)\n return nullptr;\n if (Metadata *MappedOp =\n MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))\n return MappedOp;\n \/\/ Use identity map if MappedOp is null and we can ignore missing entries.\n if (Flags & RF_IgnoreMissingEntries)\n return Op;\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ llvm_unreachable(\"Referenced metadata not in value map!\");\n return nullptr;\n}\n\n\/\/\/ \\brief Map a distinct MDNode.\n\/\/\/\n\/\/\/ Distinct nodes are not uniqued, so they must always recreated.\nstatic Metadata *mapDistinctNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n assert(Node->isDistinct() && \"Expected distinct node\");\n\n \/\/ Create the node first so it's available for cyclical references.\n SmallVector EmptyOps(Node->getNumOperands());\n MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);\n mapToMetadata(VM, Node, NewMD);\n\n \/\/ Fix the operands.\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)\n NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,\n TypeMapper, Materializer));\n\n return NewMD;\n}\n\n\/\/\/ \\brief Check whether a uniqued node needs to be remapped.\n\/\/\/\n\/\/\/ Check whether a uniqued node needs to be remapped (due to any operands\n\/\/\/ changing).\nstatic bool shouldRemapUniquedNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n \/\/ Check all operands to see if any need to be remapped.\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {\n Metadata *Op = Node->getOperand(I);\n if (Op != mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer))\n return true;\n }\n return false;\n}\n\nstatic Metadata *cloneMDTuple(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n SmallVector Elts;\n Elts.reserve(Node->getNumOperands());\n for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)\n Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,\n Materializer));\n\n return MDTuple::get(Node->getContext(), Elts);\n}\n\n\/\/\/ \\brief Map a uniqued MDNode.\n\/\/\/\n\/\/\/ Uniqued nodes may not need to be recreated (they may map to themselves).\nstatic Metadata *mapUniquedNode(const UniquableMDNode *Node,\n ValueToValueMapTy &VM, RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n assert(!Node->isDistinct() && \"Expected uniqued node\");\n\n \/\/ Create a dummy node in case we have a metadata cycle.\n MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);\n mapToMetadata(VM, Node, Dummy);\n\n \/\/ Check all operands to see if any need to be remapped.\n if (!shouldRemapUniquedNode(Node, VM, Flags, TypeMapper, Materializer)) {\n \/\/ Use an identity mapping.\n mapToSelf(VM, Node);\n MDNode::deleteTemporary(Dummy);\n return const_cast(static_cast(Node));\n }\n\n \/\/ At least one operand needs remapping.\n Metadata *NewMD = cloneMDTuple(Node, VM, Flags, TypeMapper, Materializer);\n Dummy->replaceAllUsesWith(NewMD);\n MDNode::deleteTemporary(Dummy);\n return mapToMetadata(VM, Node, NewMD);\n}\n\nstatic Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags,\n ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n \/\/ If the value already exists in the map, use it.\n if (Metadata *NewMD = VM.MD().lookup(MD).get())\n return NewMD;\n\n if (isa(MD))\n return mapToSelf(VM, MD);\n\n if (isa(MD))\n if ((Flags & RF_NoModuleLevelChanges))\n return mapToSelf(VM, MD);\n\n if (const auto *VMD = dyn_cast(MD)) {\n Value *MappedV =\n MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);\n if (VMD->getValue() == MappedV ||\n (!MappedV && (Flags & RF_IgnoreMissingEntries)))\n return mapToSelf(VM, MD);\n\n \/\/ FIXME: This assert crashes during bootstrap, but I think it should be\n \/\/ correct. For now, just match behaviour from before the metadata\/value\n \/\/ split.\n \/\/\n \/\/ assert(MappedV && \"Referenced metadata not in value map!\");\n if (MappedV)\n return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));\n return nullptr;\n }\n\n const UniquableMDNode *Node = cast(MD);\n assert(Node->isResolved() && \"Unexpected unresolved node\");\n\n \/\/ If this is a module-level metadata and we know that nothing at the\n \/\/ module level is changing, then use an identity mapping.\n if (Flags & RF_NoModuleLevelChanges)\n return mapToSelf(VM, MD);\n\n if (Node->isDistinct())\n return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);\n\n return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);\n}\n\nMetadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);\n if (NewMD && NewMD != MD)\n if (auto *N = dyn_cast(NewMD))\n N->resolveCycles();\n return NewMD;\n}\n\nMDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer) {\n return cast(MapMetadata(static_cast(MD), VM, Flags,\n TypeMapper, Materializer));\n}\n\n\/\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/\/ current values into those specified by VMap.\n\/\/\/\nvoid llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,\n RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,\n ValueMaterializer *Materializer){\n \/\/ Remap operands.\n for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {\n Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);\n \/\/ If we aren't ignoring missing entries, assert that something happened.\n if (V)\n *op = V;\n else\n assert((Flags & RF_IgnoreMissingEntries) &&\n \"Referenced value not in value map!\");\n }\n\n \/\/ Remap phi nodes' incoming blocks.\n if (PHINode *PN = dyn_cast(I)) {\n for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {\n Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);\n \/\/ If we aren't ignoring missing entries, assert that something happened.\n if (V)\n PN->setIncomingBlock(i, cast(V));\n else\n assert((Flags & RF_IgnoreMissingEntries) &&\n \"Referenced block not in value map!\");\n }\n }\n\n \/\/ Remap attached metadata.\n SmallVector, 4> MDs;\n I->getAllMetadata(MDs);\n for (SmallVectorImpl>::iterator\n MI = MDs.begin(),\n ME = MDs.end();\n MI != ME; ++MI) {\n MDNode *Old = MI->second;\n MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);\n if (New != Old)\n I->setMetadata(MI->first, New);\n }\n \n \/\/ If the instruction's type is being remapped, do so now.\n if (TypeMapper)\n I->mutateType(TypeMapper->remapType(I->getType()));\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\/\/ Wrappers\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbWrapperChoiceParameter.h\"\n#include \"otbWrapperElevationParametersHandler.h\"\n#include \"otbWrapperMapProjectionParametersHandler.h\"\n#include \"otbSensorModelAdapter.h\"\n#include \"itkPoint.h\"\n#include \"itkEuclideanDistanceMetric.h\"\n#include \"otbGenericRSTransform.h\"\n#include \"otbOGRDataSourceWrapper.h\"\n#include \"ogrsf_frmts.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass RefineSensorModel : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef RefineSensorModel Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n typedef itk::Point PointType;\n typedef itk::Statistics::EuclideanDistanceMetric DistanceType;\n\n typedef std::pair TiePointType;\n typedef std::vector TiePointsType;\n\n typedef otb::GenericRSTransform RSTransformType;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n itkTypeMacro(RefineSensorModel, otb::Application);\n\nprivate:\n void DoInit()\n {\n SetName(\"RefineSensorModel\");\n SetDescription(\"Perform least-square fit of a sensor model to a set of tie points\");\n\n SetDocName(\"Refine Sensor Model\");\n SetDocLongDescription(\"This application reads a geom file containing a sensor model and a text file containing a list of ground control point, and performs a least-square fit of the sensor model adjustable parameters to these tie points. It produces an updated geom file as output, as well as an optional ground control points based statistics file and a vector file containing residues. The output geom file can then be used to ortho-rectify the data more accurately. Plaease note that for a proper use of the application, elevation must be correctly set (including DEM and geoid file). The map parameters allows one to choose a map projection in which the accuracy will be estimated in meters.\");\n\n AddDocTag(Tags::Geometry);\n\n SetDocLimitations(\"None\");\n SetDocSeeAlso(\"OrthoRectification,HomologousPointsExtraction\");\n SetDocAuthors(\"OTB-Team\");\n\n AddParameter(ParameterType_InputFilename,\"ingeom\",\"Input geom file\");\n SetParameterDescription(\"ingeom\",\"Geom file containing the sensor model to refine\");\n\n AddParameter(ParameterType_OutputFilename,\"outgeom\",\"Output geom file\");\n SetParameterDescription(\"outgeom\",\"Geom file containing the refined sensor model\");\n\n AddParameter(ParameterType_InputFilename,\"inpoints\",\"Input file containing tie points\");\n SetParameterDescription(\"inpoints\",\"Input file containing tie points. Points are stored in following format: row col lon lat. Line beginning with # are ignored.\");\n\n AddParameter(ParameterType_OutputFilename,\"outstat\",\"Output file containing output precision statistics\");\n SetParameterDescription(\"outstat\",\"Output file containing the following info: ref_lon ref_lat elevation predicted_lon predicted_lat x_error_ref(meters) y_error_ref(meters) global_error_ref(meters) x_error(meters) y_error(meters) overall_error(meters)\");\n MandatoryOff(\"outstat\");\n DisableParameter(\"outstat\");\n\n AddParameter(ParameterType_OutputFilename,\"outvector\",\"Output vector file with residues\");\n SetParameterDescription(\"outvector\",\"File containing segments representing residues\");\n MandatoryOff(\"outvector\");\n DisableParameter(\"outvector\");\n\n \/\/ Build the Output Map Projection\n MapProjectionParametersHandler::AddMapProjectionParameters(this, \"map\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"ingeom\", \"input.geom\");\n SetDocExampleParameterValue(\"outgeom\",\"output.geom\");\n SetDocExampleParameterValue(\"inpoints\",\"points.txt\");\n SetDocExampleParameterValue(\"map\",\"epsg\");\n SetDocExampleParameterValue(\"map.epsg.code\",\"32631\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n OGRMultiLineString mls;\n\n otb::SensorModelAdapter::Pointer sm = otb::SensorModelAdapter::New();\n otb::SensorModelAdapter::Pointer sm_ref = otb::SensorModelAdapter::New();\n\n \/\/ Read the geom file\n sm->ReadGeomFile(GetParameterString(\"ingeom\"));\n sm_ref->ReadGeomFile(GetParameterString(\"ingeom\"));\n\n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n\n \/\/ Parse the input file for ground control points\n std::ifstream ifs;\n ifs.open(GetParameterString(\"inpoints\").c_str());\n\n TiePointsType tiepoints;\n\n while(!ifs.eof())\n {\n std::string line;\n std::getline(ifs,line);\n\n double x,y,z,lat,lon;\n\n \/\/ Avoid commented lines or too short ones\n if (!line.empty() && line[0] != '#')\n {\n \/\/ retrieve the x component\n std::string::size_type pos = 0;\n std::string::size_type nextpos = line.find_first_of(\"\\t\", pos);\n x = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n y = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n lon = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n lat = atof(line.substr(pos, nextpos).c_str());\n\n z = otb::DEMHandler::Instance()->GetHeightAboveEllipsoid(lon,lat);\n\n otbAppLogINFO(\"Adding tie point x=\"<AddTiePoint(x,y,z,lon,lat);\n\n PointType p1,p2;\n p1[0]=x;\n p1[1]=y;\n p1[2]=z;\n p2[0]=lon;\n p2[1]=lat;\n p2[2]=z;\n\n tiepoints.push_back(std::make_pair(p1,p2));\n\n }\n }\n ifs.close();\n\n otbAppLogINFO(\"Optimization in progress ...\");\n sm->Optimize();\n otbAppLogINFO(\"Done.\\n\");\n\n sm->WriteGeomFile(GetParameterString(\"outgeom\"));\n\n double rmse = 0;\n double rmsex = 0;\n double rmsey = 0;\n\n double meanx = 0;\n double meany = 0;\n\n double rmse_ref = 0;\n double rmsex_ref = 0;\n double rmsey_ref = 0;\n\n double meanx_ref = 0;\n double meany_ref = 0;\n\n\n DistanceType::Pointer distance = DistanceType::New();\n\n RSTransformType::Pointer rsTransform = RSTransformType::New();\n rsTransform->SetOutputProjectionRef(MapProjectionParametersHandler::GetProjectionRefFromChoice(this, \"map\"));\n rsTransform->InstanciateTransform();\n\n std::ofstream ofs;\n ofs<ForwardTransformPoint(it->first[0],it->first[1],it->first[2],tmpPoint[0],tmpPoint[1],tmpPoint[2]);\n sm_ref->ForwardTransformPoint(it->first[0],it->first[1],it->first[2],tmpPoint_ref[0],tmpPoint_ref[1],tmpPoint_ref[2]);\n\n tmpPoint = rsTransform->TransformPoint(tmpPoint);\n tmpPoint_ref = rsTransform->TransformPoint(tmpPoint_ref);\n\n ref[0] = it->second[0];\n ref[1] = it->second[1];\n ref[2] = it->second[2];\n\n ref = rsTransform->TransformPoint(ref);\n\n OGRLineString ls;\n ls.addPoint(tmpPoint[0],tmpPoint[1]);\n ls.addPoint(ref[0],ref[1]);\n mls.addGeometry(&ls);\n\n double gerror = distance->Evaluate(ref,tmpPoint);\n double xerror = ref[0]-tmpPoint[0];\n double yerror = ref[1]-tmpPoint[1];\n\n double gerror_ref = distance->Evaluate(ref,tmpPoint_ref);\n double xerror_ref = ref[0]-tmpPoint_ref[0];\n double yerror_ref = ref[1]-tmpPoint_ref[1];\n\n\n if(IsParameterEnabled(\"outstat\"))\n ofs<first[2]<<\"\\t\"<CreateLayer(\"matches\", &oSRS, wkbMultiLineString);\n OGRFeatureDefn & defn = layer.GetLayerDefn();\n ogr::Feature feature(defn);\n\n feature.SetGeometry(&mls);\n layer.CreateFeature(feature);\n }\n }\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::RefineSensorModel)\nBUG: Mantis-1158: missing field in output header of RefineSensorModel\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\/\/ Wrappers\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbWrapperChoiceParameter.h\"\n#include \"otbWrapperElevationParametersHandler.h\"\n#include \"otbWrapperMapProjectionParametersHandler.h\"\n#include \"otbSensorModelAdapter.h\"\n#include \"itkPoint.h\"\n#include \"itkEuclideanDistanceMetric.h\"\n#include \"otbGenericRSTransform.h\"\n#include \"otbOGRDataSourceWrapper.h\"\n#include \"ogrsf_frmts.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass RefineSensorModel : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef RefineSensorModel Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n typedef itk::Point PointType;\n typedef itk::Statistics::EuclideanDistanceMetric DistanceType;\n\n typedef std::pair TiePointType;\n typedef std::vector TiePointsType;\n\n typedef otb::GenericRSTransform RSTransformType;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n itkTypeMacro(RefineSensorModel, otb::Application);\n\nprivate:\n void DoInit()\n {\n SetName(\"RefineSensorModel\");\n SetDescription(\"Perform least-square fit of a sensor model to a set of tie points\");\n\n SetDocName(\"Refine Sensor Model\");\n SetDocLongDescription(\"This application reads a geom file containing a sensor model and a text file containing a list of ground control point, and performs a least-square fit of the sensor model adjustable parameters to these tie points. It produces an updated geom file as output, as well as an optional ground control points based statistics file and a vector file containing residues. The output geom file can then be used to ortho-rectify the data more accurately. Plaease note that for a proper use of the application, elevation must be correctly set (including DEM and geoid file). The map parameters allows one to choose a map projection in which the accuracy will be estimated in meters.\");\n\n AddDocTag(Tags::Geometry);\n\n SetDocLimitations(\"None\");\n SetDocSeeAlso(\"OrthoRectification,HomologousPointsExtraction\");\n SetDocAuthors(\"OTB-Team\");\n\n AddParameter(ParameterType_InputFilename,\"ingeom\",\"Input geom file\");\n SetParameterDescription(\"ingeom\",\"Geom file containing the sensor model to refine\");\n\n AddParameter(ParameterType_OutputFilename,\"outgeom\",\"Output geom file\");\n SetParameterDescription(\"outgeom\",\"Geom file containing the refined sensor model\");\n\n AddParameter(ParameterType_InputFilename,\"inpoints\",\"Input file containing tie points\");\n SetParameterDescription(\"inpoints\",\"Input file containing tie points. Points are stored in following format: row col lon lat. Line beginning with # are ignored.\");\n\n AddParameter(ParameterType_OutputFilename,\"outstat\",\"Output file containing output precision statistics\");\n SetParameterDescription(\"outstat\",\"Output file containing the following info: ref_lon ref_lat elevation predicted_lon predicted_lat x_error_ref(meters) y_error_ref(meters) global_error_ref(meters) x_error(meters) y_error(meters) overall_error(meters)\");\n MandatoryOff(\"outstat\");\n DisableParameter(\"outstat\");\n\n AddParameter(ParameterType_OutputFilename,\"outvector\",\"Output vector file with residues\");\n SetParameterDescription(\"outvector\",\"File containing segments representing residues\");\n MandatoryOff(\"outvector\");\n DisableParameter(\"outvector\");\n\n \/\/ Build the Output Map Projection\n MapProjectionParametersHandler::AddMapProjectionParameters(this, \"map\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"ingeom\", \"input.geom\");\n SetDocExampleParameterValue(\"outgeom\",\"output.geom\");\n SetDocExampleParameterValue(\"inpoints\",\"points.txt\");\n SetDocExampleParameterValue(\"map\",\"epsg\");\n SetDocExampleParameterValue(\"map.epsg.code\",\"32631\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n OGRMultiLineString mls;\n\n otb::SensorModelAdapter::Pointer sm = otb::SensorModelAdapter::New();\n otb::SensorModelAdapter::Pointer sm_ref = otb::SensorModelAdapter::New();\n\n \/\/ Read the geom file\n sm->ReadGeomFile(GetParameterString(\"ingeom\"));\n sm_ref->ReadGeomFile(GetParameterString(\"ingeom\"));\n\n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n\n \/\/ Parse the input file for ground control points\n std::ifstream ifs;\n ifs.open(GetParameterString(\"inpoints\").c_str());\n\n TiePointsType tiepoints;\n\n while(!ifs.eof())\n {\n std::string line;\n std::getline(ifs,line);\n\n double x,y,z,lat,lon;\n\n \/\/ Avoid commented lines or too short ones\n if (!line.empty() && line[0] != '#')\n {\n \/\/ retrieve the x component\n std::string::size_type pos = 0;\n std::string::size_type nextpos = line.find_first_of(\"\\t\", pos);\n x = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n y = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n lon = atof(line.substr(pos, nextpos).c_str());\n pos = nextpos + 1;\n nextpos = line.find_first_of(\"\\t\", pos);\n lat = atof(line.substr(pos, nextpos).c_str());\n\n z = otb::DEMHandler::Instance()->GetHeightAboveEllipsoid(lon,lat);\n\n otbAppLogINFO(\"Adding tie point x=\"<AddTiePoint(x,y,z,lon,lat);\n\n PointType p1,p2;\n p1[0]=x;\n p1[1]=y;\n p1[2]=z;\n p2[0]=lon;\n p2[1]=lat;\n p2[2]=z;\n\n tiepoints.push_back(std::make_pair(p1,p2));\n\n }\n }\n ifs.close();\n\n otbAppLogINFO(\"Optimization in progress ...\");\n sm->Optimize();\n otbAppLogINFO(\"Done.\\n\");\n\n sm->WriteGeomFile(GetParameterString(\"outgeom\"));\n\n double rmse = 0;\n double rmsex = 0;\n double rmsey = 0;\n\n double meanx = 0;\n double meany = 0;\n\n double rmse_ref = 0;\n double rmsex_ref = 0;\n double rmsey_ref = 0;\n\n double meanx_ref = 0;\n double meany_ref = 0;\n\n\n DistanceType::Pointer distance = DistanceType::New();\n\n RSTransformType::Pointer rsTransform = RSTransformType::New();\n rsTransform->SetOutputProjectionRef(MapProjectionParametersHandler::GetProjectionRefFromChoice(this, \"map\"));\n rsTransform->InstanciateTransform();\n\n std::ofstream ofs;\n ofs<ForwardTransformPoint(it->first[0],it->first[1],it->first[2],tmpPoint[0],tmpPoint[1],tmpPoint[2]);\n sm_ref->ForwardTransformPoint(it->first[0],it->first[1],it->first[2],tmpPoint_ref[0],tmpPoint_ref[1],tmpPoint_ref[2]);\n\n tmpPoint = rsTransform->TransformPoint(tmpPoint);\n tmpPoint_ref = rsTransform->TransformPoint(tmpPoint_ref);\n\n ref[0] = it->second[0];\n ref[1] = it->second[1];\n ref[2] = it->second[2];\n\n ref = rsTransform->TransformPoint(ref);\n\n OGRLineString ls;\n ls.addPoint(tmpPoint[0],tmpPoint[1]);\n ls.addPoint(ref[0],ref[1]);\n mls.addGeometry(&ls);\n\n double gerror = distance->Evaluate(ref,tmpPoint);\n double xerror = ref[0]-tmpPoint[0];\n double yerror = ref[1]-tmpPoint[1];\n\n double gerror_ref = distance->Evaluate(ref,tmpPoint_ref);\n double xerror_ref = ref[0]-tmpPoint_ref[0];\n double yerror_ref = ref[1]-tmpPoint_ref[1];\n\n\n if(IsParameterEnabled(\"outstat\"))\n ofs<first[2]<<\"\\t\"<CreateLayer(\"matches\", &oSRS, wkbMultiLineString);\n OGRFeatureDefn & defn = layer.GetLayerDefn();\n ogr::Feature feature(defn);\n\n feature.SetGeometry(&mls);\n layer.CreateFeature(feature);\n }\n }\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::RefineSensorModel)\n<|endoftext|>"} {"text":"\/*\n** Copyright (C) 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nqiLogCategory(\"py.async\");\n\nnamespace qi { namespace py {\n\n static void pyPeriodicCb(const PyThreadSafeObject& callable) {\n GILScopedLock _gil;\n PY_CATCH_ERROR(callable.object()());\n }\n\n class PyPeriodicTask : public qi::PeriodicTask {\n public:\n void setCallback(boost::python::object callable) {\n if (!PyCallable_Check(callable.ptr()))\n throw std::runtime_error(\"Not a callable\");\n qi::PeriodicTask::setCallback(boost::bind(pyPeriodicCb, PyThreadSafeObject(callable)));\n }\n\n void stop() {\n qi::py::GILScopedUnlock _unlock;\n \/\/unlock because stop wait for the callback to finish.\n qi::PeriodicTask::stop();\n }\n };\n\n static boost::python::object pyAsync(PyThreadSafeObject safeargs) {\n GILScopedLock _gil;\n\n boost::python::list args(safeargs.object());\n boost::python::object callable = args[0];\n\n args.pop(0);\n\n try {\n return callable(*boost::python::tuple(args));\n } catch (const boost::python::error_already_set &) {\n throw std::runtime_error(PyFormatError());\n }\n }\n\n static boost::python::object pyasyncParamShrinker(boost::python::tuple args, boost::python::dict kwargs) {\n \/\/arg0 always exists\n \/\/check args[0] is a callable\n boost::python::object callable = args[0];\n if (!PyCallable_Check(callable.ptr()))\n throw std::runtime_error(\"Not a callable\");\n\n qi::uint64_t delay = boost::python::extract(kwargs.get(\"delay\", 0));\n\n \/\/Does not use PyThreadSafeObject, because, setValue will be done under the lock\n \/\/and the the future will be a PyFuture, that will be destroyed and use in the python world\n \/\/under the lock too.\n boost::function f = boost::bind(&pyAsync, PyThreadSafeObject(args));\n\n qi::Future fut = qi::getEventLoop()->async(f, delay);\n\n return boost::python::object(qi::py::toPyFuture(fut));\n }\n\n\n void export_pyasync() {\n boost::python::object async = boost::python::raw_function(&pyasyncParamShrinker, 1);\n\n async.attr(\"__doc__\") = \"async(callback [, delay=usec] [, arg1, ..., argn]) -> future\\n\"\n \":param callback: the callback that will be called\\n\"\n \":param delay: an optional delay in microseconds\\n\"\n \":return: a future with the return value of the function\\n\"\n \"\\n\";\n\n boost::python::def(\"async\", async);\n\n boost::python::class_, boost::noncopyable >(\"PeriodicTask\")\n .def(boost::python::init<>())\n .def(\"setCallback\", &PyPeriodicTask::setCallback,\n \"setCallback(callable)\\n\"\n \":param callable: a python callable, could be a method or a function\\n\"\n \"\\n\"\n \"set the callback used by the periodictask, this function can only be called once\")\n .def(\"setUsPeriod\", &PyPeriodicTask::setUsPeriod,\n \"setUsPeriod(usPeriod)\\n\"\n \":param usPeriod: the period in microseconds\\n\"\n \"\\n\"\n \"Set the call interval in microseconds.\\n\"\n \"This call will wait until next callback invocation to apply the change.\\n\"\n \"To apply the change immediately, use: \\n\"\n \"\\n\"\n \".. code-block:: python\\n\"\n \"\\n\"\n \" task.stop()\\n\"\n \" task.setUsPeriod()\\n\"\n \" task.start()\\n\"\n \"\\n\")\n .def(\"start\", &PyPeriodicTask::start,\n \"start(immediate)\\n\"\n \":param immediate: immediate if true, first schedule of the task will happen with no delay.\\n\"\n \"\\n\"\n \"start the periodic task at specified period. No effect if already running\\n\"\n \"\\n\"\n \".. warning::\\n\"\n \" concurrent calls to start() and stop() will result in undefined behavior.\"\n \"\\n\")\n .def(\"stop\", &PyPeriodicTask::stop,\n \"stop()\\n\"\n \"Stop the periodic task. When this function returns, the callback will not be called anymore.\\n\"\n \"Can be called from within the callback function\\n\"\n \"\\n\"\n \".. warning::\\n\"\n \" concurrent calls to start() and stop() will result in undefined behavior.\"\n \"\\n\")\n .def(\"asyncStop\", &PyPeriodicTask::asyncStop,\n \"asyncStop()\\n\"\n \"Can be called from within the callback function\\n\"\n \"Request for periodic task to stop asynchronously\")\n .def(\"compensateCallbackTime\", &PyPeriodicTask::compensateCallbackTime,\n \"compensateCallbackTime(compensate)\\n\"\n \":param compensate: If true, call interval will take into account call duration to maintain the period.\")\n .def(\"setName\", &PyPeriodicTask::setName,\n \"setName(name)\\n\"\n \"Set name for debugging and tracking purpose\")\n .def(\"isRunning\", &PyPeriodicTask::isRunning,\n \"isRunning() -> bool\\n\"\n \":return: true is task is running\\n\")\n .def(\"isStopping\", &PyPeriodicTask::isStopping,\n \"isStopping() -> bool\\n\"\n \":return: whether state is stopping or stopped.\\n\"\n \"\\n\"\n \"Can be called from within the callback to know if stop() or asyncStop() was called.\")\n ;\n }\n\n }\n}\npython: periodictask: unlock start (which can call stop)\/*\n** Copyright (C) 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nqiLogCategory(\"py.async\");\n\nnamespace qi { namespace py {\n\n static void pyPeriodicCb(const PyThreadSafeObject& callable) {\n GILScopedLock _gil;\n PY_CATCH_ERROR(callable.object()());\n }\n\n class PyPeriodicTask : public qi::PeriodicTask {\n public:\n void setCallback(boost::python::object callable) {\n if (!PyCallable_Check(callable.ptr()))\n throw std::runtime_error(\"Not a callable\");\n qi::PeriodicTask::setCallback(boost::bind(pyPeriodicCb, PyThreadSafeObject(callable)));\n }\n\n void stop() {\n qi::py::GILScopedUnlock _unlock;\n \/\/unlock because stop wait for the callback to finish.\n qi::PeriodicTask::stop();\n }\n\n void start(bool immediate) {\n qi::py::GILScopedUnlock _unlock;\n \/\/unlock because stop wait for the callback to finish.\n qi::PeriodicTask::start(immediate);\n }\n\n };\n\n static boost::python::object pyAsync(PyThreadSafeObject safeargs) {\n GILScopedLock _gil;\n\n boost::python::list args(safeargs.object());\n boost::python::object callable = args[0];\n\n args.pop(0);\n\n try {\n return callable(*boost::python::tuple(args));\n } catch (const boost::python::error_already_set &) {\n throw std::runtime_error(PyFormatError());\n }\n }\n\n static boost::python::object pyasyncParamShrinker(boost::python::tuple args, boost::python::dict kwargs) {\n \/\/arg0 always exists\n \/\/check args[0] is a callable\n boost::python::object callable = args[0];\n if (!PyCallable_Check(callable.ptr()))\n throw std::runtime_error(\"Not a callable\");\n\n qi::uint64_t delay = boost::python::extract(kwargs.get(\"delay\", 0));\n\n \/\/Does not use PyThreadSafeObject, because, setValue will be done under the lock\n \/\/and the the future will be a PyFuture, that will be destroyed and use in the python world\n \/\/under the lock too.\n boost::function f = boost::bind(&pyAsync, PyThreadSafeObject(args));\n\n qi::Future fut = qi::getEventLoop()->async(f, delay);\n\n return boost::python::object(qi::py::toPyFuture(fut));\n }\n\n\n void export_pyasync() {\n boost::python::object async = boost::python::raw_function(&pyasyncParamShrinker, 1);\n\n async.attr(\"__doc__\") = \"async(callback [, delay=usec] [, arg1, ..., argn]) -> future\\n\"\n \":param callback: the callback that will be called\\n\"\n \":param delay: an optional delay in microseconds\\n\"\n \":return: a future with the return value of the function\\n\"\n \"\\n\";\n\n boost::python::def(\"async\", async);\n\n boost::python::class_, boost::noncopyable >(\"PeriodicTask\")\n .def(boost::python::init<>())\n .def(\"setCallback\", &PyPeriodicTask::setCallback,\n \"setCallback(callable)\\n\"\n \":param callable: a python callable, could be a method or a function\\n\"\n \"\\n\"\n \"set the callback used by the periodictask, this function can only be called once\")\n .def(\"setUsPeriod\", &PyPeriodicTask::setUsPeriod,\n \"setUsPeriod(usPeriod)\\n\"\n \":param usPeriod: the period in microseconds\\n\"\n \"\\n\"\n \"Set the call interval in microseconds.\\n\"\n \"This call will wait until next callback invocation to apply the change.\\n\"\n \"To apply the change immediately, use: \\n\"\n \"\\n\"\n \".. code-block:: python\\n\"\n \"\\n\"\n \" task.stop()\\n\"\n \" task.setUsPeriod()\\n\"\n \" task.start()\\n\"\n \"\\n\")\n .def(\"start\", &PyPeriodicTask::start,\n \"start(immediate)\\n\"\n \":param immediate: immediate if true, first schedule of the task will happen with no delay.\\n\"\n \"\\n\"\n \"start the periodic task at specified period. No effect if already running\\n\"\n \"\\n\"\n \".. warning::\\n\"\n \" concurrent calls to start() and stop() will result in undefined behavior.\"\n \"\\n\")\n .def(\"stop\", &PyPeriodicTask::stop,\n \"stop()\\n\"\n \"Stop the periodic task. When this function returns, the callback will not be called anymore.\\n\"\n \"Can be called from within the callback function\\n\"\n \"\\n\"\n \".. warning::\\n\"\n \" concurrent calls to start() and stop() will result in undefined behavior.\"\n \"\\n\")\n .def(\"asyncStop\", &PyPeriodicTask::asyncStop,\n \"asyncStop()\\n\"\n \"Can be called from within the callback function\\n\"\n \"Request for periodic task to stop asynchronously\")\n .def(\"compensateCallbackTime\", &PyPeriodicTask::compensateCallbackTime,\n \"compensateCallbackTime(compensate)\\n\"\n \":param compensate: If true, call interval will take into account call duration to maintain the period.\")\n .def(\"setName\", &PyPeriodicTask::setName,\n \"setName(name)\\n\"\n \"Set name for debugging and tracking purpose\")\n .def(\"isRunning\", &PyPeriodicTask::isRunning,\n \"isRunning() -> bool\\n\"\n \":return: true is task is running\\n\")\n .def(\"isStopping\", &PyPeriodicTask::isStopping,\n \"isStopping() -> bool\\n\"\n \":return: whether state is stopping or stopped.\\n\"\n \"\\n\"\n \"Can be called from within the callback to know if stop() or asyncStop() was called.\")\n ;\n }\n\n }\n}\n<|endoftext|>"} {"text":"\/\/ SimmPathMatrix.cpp\r\n\/\/ Author: Peter Loan\r\n\/*\r\n * Copyright (c) 2006, Stanford University. All rights reserved. \r\n * Permission is hereby granted, free of charge, to any person obtaining\r\n * a copy of this software and associated documentation files (the\r\n * \"Software\"), to deal in the Software without restriction, including \r\n * without limitation the rights to use, copy, modify, merge, publish, \r\n * distribute, sublicense, and\/or sell copies of the Software, and to\r\n * permit persons to whom the Software is furnished to do so, subject\r\n * to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included \r\n * in all copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n *\/\r\n\r\n\r\n\/\/=============================================================================\r\n\/\/ INCLUDES\r\n\/\/=============================================================================\r\n#include \"SimmPathMatrix.h\"\r\n#include \r\n#include \r\n\r\n\/\/=============================================================================\r\n\/\/ STATICS\r\n\/\/=============================================================================\r\nusing namespace std;\r\nusing namespace OpenSim;\r\n\r\nconst int SimmPathMatrix::cSizeFactor = 2;\r\nconst int SimmPathMatrix::cHash1 = 27;\r\nconst int SimmPathMatrix::cHash2 = 7;\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Default constructor.\r\n *\/\r\nSimmPathMatrix::SimmPathMatrix(int size)\r\n{\r\n\tif (size > 0)\r\n\t{\r\n\t\t_size = size * size * 2;\r\n\t\t_hashTable.reserve(_size);\r\n\t\t_factor = size;\r\n\t\tfor (int i = 0; i < _size; i++)\r\n\t\t\t_hashTable[i] = NULL;\r\n\t}\r\n\telse\r\n\t\t_size = 0;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Destructor.\r\n *\/\r\nSimmPathMatrix::~SimmPathMatrix()\r\n{\r\n\tdeletePaths();\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ GET AND SET\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Get a SimmPath between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return Pointer to the SimmPath from aFromBody to aToBody\r\n *\/\r\nSimmPath* SimmPathMatrix::getSimmPath(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\treturn _hashTable[index];\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Get a JointPath between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return Pointer to the JointPath from aFromBody to aToBody\r\n *\/\r\nconst JointPath* SimmPathMatrix::getPath(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\tif (_hashTable[index])\r\n\t\treturn &_hashTable[index]->getPath();\r\n\r\n\treturn NULL;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Set the path between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @param Pointer to the JointPath from aFromBody to aToBody\r\n *\/\r\nvoid SimmPathMatrix::setPath(const AbstractBody* aFromBody, const AbstractBody* aToBody, JointPath aPath)\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\t_hashTable[index] = new SimmPath(aPath, aFromBody, aToBody);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ UTILITY\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Delete all paths in the SimmPathMatrix.\r\n *\/\r\nvoid SimmPathMatrix::deletePaths()\r\n{\r\n\tfor (unsigned int i = 0; i < _hashTable.size(); i++)\r\n\t{\r\n\t\tif (_hashTable[i])\r\n\t\t\tdelete _hashTable[i];\r\n\t}\r\n\r\n\t_size = 0;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Initialize the has table which holds the paths\r\n *\/\r\nvoid SimmPathMatrix::initTable(int size)\r\n{\r\n\t\/* If there are already some paths stored in the hash table, delete them. *\/\r\n\tif (_size > 0)\r\n\t\tdeletePaths();\r\n\r\n\t\/* Make room for the new paths. *\/\r\n\tif (size > 0)\r\n\t{\r\n\t\t_size = size * size * cSizeFactor;\r\n\t\t_hashTable.reserve(_size);\r\n\t\t_factor = size;\r\n\t\tfor (int i = 0; i < _size; i++)\r\n\t\t\t_hashTable[i] = NULL;\r\n\t}\r\n}\r\n\r\nvoid SimmPathMatrix::invalidate()\r\n{\r\n\tfor (int i = 0; i < _size; i++)\r\n\t\tif (_hashTable[i])\r\n\t\t\t_hashTable[i]->invalidate();\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Hash a pair of bodies\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return The integer hash value\r\n *\/\r\nint SimmPathMatrix::hash(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tint hash_value = ((int)(intptr_t)aFromBody \/ cHash1 + (int)(intptr_t)aToBody) \/ cHash2 % _size;\r\n\r\n\tSimmPath* hashEntry;\r\n\tfor (int i = 0; i < _size; i++)\r\n\t{\r\n\t\thashEntry = _hashTable[hash_value];\r\n\t\tif ( hashEntry == NULL ||\r\n\t\t\t(hashEntry->getFromBody() == aFromBody && hashEntry->getToBody() == aToBody))\r\n\t\t{\r\n\t\t\treturn hash_value;\r\n\t\t}\r\n\t\thash_value++;\r\n\t\tif (hash_value >= _size)\r\n\t\t\thash_value = 0;\r\n\t}\r\n\r\n\treturn -1;\r\n}\r\n\r\nvoid SimmPathMatrix::peteTest() const\r\n{\r\n\tcout << \"SimmPathMatrix:\" << endl;\r\n\tfor (int i = 0; i < _size; i++)\r\n\t{\r\n\t\tif (_hashTable[i])\r\n\t\t\t_hashTable[i]->peteTest();\r\n\t\telse\r\n\t\t\tcout << \"slot \" << i << \" is empty.\" << endl;\r\n\t}\r\n}\r\navoid ending up with negatie hash_value on a 64 bit machine\/\/ SimmPathMatrix.cpp\r\n\/\/ Author: Peter Loan\r\n\/*\r\n * Copyright (c) 2006, Stanford University. All rights reserved. \r\n * Permission is hereby granted, free of charge, to any person obtaining\r\n * a copy of this software and associated documentation files (the\r\n * \"Software\"), to deal in the Software without restriction, including \r\n * without limitation the rights to use, copy, modify, merge, publish, \r\n * distribute, sublicense, and\/or sell copies of the Software, and to\r\n * permit persons to whom the Software is furnished to do so, subject\r\n * to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included \r\n * in all copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n *\/\r\n\r\n\r\n\/\/=============================================================================\r\n\/\/ INCLUDES\r\n\/\/=============================================================================\r\n#include \"SimmPathMatrix.h\"\r\n#include \r\n#include \r\n\r\n\/\/=============================================================================\r\n\/\/ STATICS\r\n\/\/=============================================================================\r\nusing namespace std;\r\nusing namespace OpenSim;\r\n\r\nconst int SimmPathMatrix::cSizeFactor = 2;\r\nconst int SimmPathMatrix::cHash1 = 27;\r\nconst int SimmPathMatrix::cHash2 = 7;\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Default constructor.\r\n *\/\r\nSimmPathMatrix::SimmPathMatrix(int size)\r\n{\r\n\tif (size > 0)\r\n\t{\r\n\t\t_size = size * size * 2;\r\n\t\t_hashTable.reserve(_size);\r\n\t\t_factor = size;\r\n\t\tfor (int i = 0; i < _size; i++)\r\n\t\t\t_hashTable[i] = NULL;\r\n\t}\r\n\telse\r\n\t\t_size = 0;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Destructor.\r\n *\/\r\nSimmPathMatrix::~SimmPathMatrix()\r\n{\r\n\tdeletePaths();\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ GET AND SET\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Get a SimmPath between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return Pointer to the SimmPath from aFromBody to aToBody\r\n *\/\r\nSimmPath* SimmPathMatrix::getSimmPath(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\treturn _hashTable[index];\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Get a JointPath between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return Pointer to the JointPath from aFromBody to aToBody\r\n *\/\r\nconst JointPath* SimmPathMatrix::getPath(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\tif (_hashTable[index])\r\n\t\treturn &_hashTable[index]->getPath();\r\n\r\n\treturn NULL;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Set the path between two bodies.\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @param Pointer to the JointPath from aFromBody to aToBody\r\n *\/\r\nvoid SimmPathMatrix::setPath(const AbstractBody* aFromBody, const AbstractBody* aToBody, JointPath aPath)\r\n{\r\n\tint index = hash(aFromBody, aToBody);\r\n\r\n\tassert(index >= 0);\r\n\r\n\t_hashTable[index] = new SimmPath(aPath, aFromBody, aToBody);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ UTILITY\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Delete all paths in the SimmPathMatrix.\r\n *\/\r\nvoid SimmPathMatrix::deletePaths()\r\n{\r\n\tfor (unsigned int i = 0; i < _hashTable.size(); i++)\r\n\t{\r\n\t\tif (_hashTable[i])\r\n\t\t\tdelete _hashTable[i];\r\n\t}\r\n\r\n\t_size = 0;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Initialize the has table which holds the paths\r\n *\/\r\nvoid SimmPathMatrix::initTable(int size)\r\n{\r\n\t\/* If there are already some paths stored in the hash table, delete them. *\/\r\n\tif (_size > 0)\r\n\t\tdeletePaths();\r\n\r\n\t\/* Make room for the new paths. *\/\r\n\tif (size > 0)\r\n\t{\r\n\t\t_size = size * size * cSizeFactor;\r\n\t\t_hashTable.reserve(_size);\r\n\t\t_factor = size;\r\n\t\tfor (int i = 0; i < _size; i++)\r\n\t\t\t_hashTable[i] = NULL;\r\n\t}\r\n}\r\n\r\nvoid SimmPathMatrix::invalidate()\r\n{\r\n\tfor (int i = 0; i < _size; i++)\r\n\t\tif (_hashTable[i])\r\n\t\t\t_hashTable[i]->invalidate();\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Hash a pair of bodies\r\n *\r\n * @param aFromBody the first body\r\n * @param aToBody the second body\r\n * @return The integer hash value\r\n *\/\r\nint SimmPathMatrix::hash(const AbstractBody* aFromBody, const AbstractBody* aToBody) const\r\n{\r\n\tunsigned int hash_value = ((unsigned int)(uintptr_t)aFromBody \/ cHash1 + (unsigned int)(uintptr_t)aToBody) \/ cHash2 % _size;\r\n\r\n\tSimmPath* hashEntry;\r\n\tfor (int i = 0; i < _size; i++)\r\n\t{\r\n\t\thashEntry = _hashTable[hash_value];\r\n\t\tif ( hashEntry == NULL ||\r\n\t\t\t(hashEntry->getFromBody() == aFromBody && hashEntry->getToBody() == aToBody))\r\n\t\t{\r\n\t\t\treturn hash_value;\r\n\t\t}\r\n\t\thash_value++;\r\n\t\tif (hash_value >= (unsigned int)_size)\r\n\t\t\thash_value = 0;\r\n\t}\r\n\r\n\treturn -1;\r\n}\r\n\r\nvoid SimmPathMatrix::peteTest() const\r\n{\r\n\tcout << \"SimmPathMatrix:\" << endl;\r\n\tfor (int i = 0; i < _size; i++)\r\n\t{\r\n\t\tif (_hashTable[i])\r\n\t\t\t_hashTable[i]->peteTest();\r\n\t\telse\r\n\t\t\tcout << \"slot \" << i << \" is empty.\" << endl;\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \ntypedef kv::interval itv;\ntypedef kv::complex< kv::interval > cp;\nusing namespace std;\nint main()\n{\n cout.precision(17);\n int n=20;\n itv x,nu,q,xx;\n q=\"0.8\";\n nu=1.5;\n x=2.5;\n for(int i=1;i<=n;i++){\n xx=mid(x);\n x=xx-kv::Jackson2(itv(xx),itv(nu),itv(q))*(1-q)*xx\n \/(kv::Jackson2(itv(xx),itv(nu),itv(q))-kv::Jackson2(itv(q*xx),itv(nu),itv(q)))\n +(1-xx*(kv::Jackson2(itv(x),itv(nu),itv(q))-kv::Jackson2(itv(q*x),itv(nu),itv(q))) \n\t\/x\/(kv::Jackson2(itv(xx),itv(nu),itv(q))-kv::Jackson2(itv(q*xx),itv(nu),itv(q))))*(x-xx);\n cout<Update J2qKrawczyk.cc#include \n#include \n#include \n#include \ntypedef kv::interval itv;\ntypedef kv::complex< kv::interval > cp;\nusing namespace std;\nint main()\n{\n cout.precision(17);\n int n=20;\n itv x,nu,q,xx;\n q=\"0.8\";\n nu=1.5;\n x=2.5;\n for(int i=1;i<=n;i++){\n xx=mid(x);\n x=xx-kv::Jackson2(itv(xx),itv(nu),itv(q))*(1-q)*xx\n \/(kv::Jackson2(itv(xx),itv(nu),itv(q))-kv::Jackson2(itv(q*xx),itv(nu),itv(q)))\n +(1-xx*(kv::Jackson2(itv(x),itv(nu),itv(q))-kv::Jackson2(itv(q*x),itv(nu),itv(q))) \n\t\/x\/(kv::Jackson2(itv(xx),itv(nu),itv(q))-kv::Jackson2(itv(q*xx),itv(nu),itv(q))))*(x-xx);\n cout<"} {"text":"\/\/\n\/\/ This file is part of Easylogging++ samples\n\/\/\n\/\/ Demonstration of multithreaded application using pthread\n\/\/ \n\/\/ Compile this program using (if using gcc-c++ or intel or clang++):\n\/\/ [icpc | g++ | clang++] .\/pthread.cpp -o bin\/.\/pthread.cpp.bin -D_ELPP_THREAD_SAFE -std=c++0x -pthread -Wall -Wextra\n\/\/ \n\/\/ Revision: 1.1\n\/\/ @author mkhan3189\n\/\/\n\n#include \n#include \"easylogging++.h\"\n\n_INITIALIZE_EASYLOGGINGPP\n\nstruct Args {\n const char* thrId;\n el::Logger* logger;\n}args;\n\nvoid* write2(void* args){\n struct Args* a = (struct Args*)args;\n \n char* threadId = (char*)a->thrId;\n el::Logger* logger = (el::Logger*)a->logger;\n\n LOG(INFO) << \"Writing from different function using macro [Thread #\" << threadId << \"]\";\n\n logger->info(\"Info log from [Thread #%v]\", threadId);\n logger->info(\"Info log\");\n logger->verbose(2, \"Verbose test [Thread #%v]\", threadId);\n logger->verbose(2, \"Verbose test\");\n return NULL;\n}\n\nvoid *write(void* thrId){\n char* threadId = (char*)thrId;\n \/\/ Following line will be logged with every thread\n LOG(INFO) << \"This standard log is written by [Thread #\" << threadId << \"]\";\n\n \/\/ Following line will be logged with every thread only when --v=2 argument \n \/\/ is provided, i.e, .\/bin\/multithread_test.cpp.bin --v=2\n VLOG(2) << \"This is verbose level 2 logging from [Thread #\" << threadId << \"]\";\n\n \/\/ Following line will be logged only once from second running thread (which every runs second into \n \/\/ this line because of interval 2)\n LOG_EVERY_N(2, WARNING) << \"This will be logged only once from thread who every reaches this line first. Currently running from [Thread #\" << threadId << \"]\";\n\n for (int i = 1; i <= 10; ++i) {\n VLOG_IF(true, 2) << \"Verbose condition [Thread #\" << threadId << \"]\";\n VLOG_EVERY_N(2, 3) << \"Verbose level 3 log every 4th time. This is at \" << i << \" from [Thread #\" << threadId << \"]\";\n }\n\n \/\/ Following line will be logged once with every thread because of interval 1 \n LOG_EVERY_N(1, INFO) << \"This interval log will be logged with every thread, this one is from [Thread #\" << threadId << \"]\";\n\n LOG_IF(strcmp(threadId, \"2\") == 0, INFO) << \"This log is only for thread 2 and is ran by [Thread #\" << threadId << \"]\";\n\n \/\/ Register 5 vague loggers\n for (int i = 1; i <= 5; ++i) {\n std::stringstream ss;\n ss << \"logger\" << i;\n el::Logger* logger = easyloggingpp::Loggers::getLogger(ss.str());\n LOG(INFO) << \"Registered logger [\" << *logger << \"] [Thread #\" << threadId << \"]\";\n }\n CLOG(INFO, \"logger1\") << \"Logging using new logger [Thread #\" << threadId << \"]\";\n CLOG(INFO, \"no-logger\") << \"THIS SHOULD SAY LOGGER NOT REGISTERED YET [Thread #\" << threadId << \"]\"; \/\/ << -- NOTE THIS!\n\n el::Logger* logger = el::Loggers::getLogger(\"default\");\n logger->info(\"Info log from [Thread #%v]\", threadId);\n\n \/\/ Check for log counters positions\n for (int i = 1; i <= 50; ++i) {\n LOG_EVERY_N(2, INFO) << \"Counter pos: \" << ELPP_COUNTER_POS << \" [Thread #\" << threadId << \"]\";\n }\n LOG_EVERY_N(2, INFO) << \"Counter pos: \" << ELPP_COUNTER_POS << \" [Thread #\" << threadId << \"]\";\n return NULL;\n}\n\n\/\/ If you wish you can define your own way to get thread ID\nconst char* getThreadId_CustomVersion(void) {\n return \"MyThreadId\";\n}\n\nint main(int argc, char** argv)\n{\n _START_EASYLOGGINGPP(argc, argv);\n\n \/\/ Your thread ID specification\n el::CustomFormatSpecifier myThreadIdSpecifier(\"%mythreadId\", getThreadId_CustomVersion);\n el::Helpers::installCustomFormatSpecifier(myThreadIdSpecifier);\n\n \/\/ Note your %mythreadId or built-in, both are logged\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"%datetime %level (%thread | %mythreadId) [%logger] [%func] [%loc] %msg\");\n el::Loggers::reconfigureAllLoggers(el::Level::Verbose, el::ConfigurationType::Format, \"%datetime %level-%vlevel (%thread | %mythreadId) [%logger] [%func] [%loc] %msg\");\n\n pthread_t thread1, thread2, thread3, thread4;\n\n \/* Create independent threads each of which will execute function *\/\n pthread_create( &thread1, NULL, write, (void*)\"1\");\n pthread_create( &thread2, NULL, write, (void*)\"2\");\n pthread_create( &thread3, NULL, write, (void*)\"3\");\n \n el::Logger* logger = el::Loggers::getLogger(\"default\");\n args.thrId = \"4\";\n args.logger = logger;\n pthread_create( &thread4, NULL, write2, (void*)&args);\n\n pthread_join(thread1, NULL);\n pthread_join(thread2, NULL); \n pthread_join(thread3, NULL); \n pthread_join(thread4, NULL); \n\n exit(0);\n}\nupdated version\/\/\n\/\/ This file is part of Easylogging++ samples\n\/\/\n\/\/ Demonstration of multithreaded application using pthread\n\/\/ \n\/\/ Compile this program using (if using gcc-c++ or intel or clang++):\n\/\/ [icpc | g++ | clang++] .\/pthread.cpp -o bin\/.\/pthread.cpp.bin -D_ELPP_THREAD_SAFE -std=c++0x -pthread -Wall -Wextra\n\/\/ \n\/\/ Revision: 1.1\n\/\/ @author mkhan3189\n\/\/\n\n#include \n#include \"easylogging++.h\"\n\n_INITIALIZE_EASYLOGGINGPP\n\nstruct Args {\n const char* thrId;\n el::Logger* logger;\n}args;\n\nvoid* write2(void* args){\n struct Args* a = (struct Args*)args;\n \n char* threadId = (char*)a->thrId;\n el::Logger* logger = (el::Logger*)a->logger;\n\n LOG(INFO) << \"Writing from different function using macro [Thread #\" << threadId << \"]\";\n\n logger->info(\"Info log from [Thread #%v]\", threadId);\n logger->info(\"Info log\");\n logger->verbose(2, \"Verbose test [Thread #%v]\", threadId);\n logger->verbose(2, \"Verbose test\");\n return NULL;\n}\n\nvoid *write(void* thrId){\n char* threadId = (char*)thrId;\n \/\/ Following line will be logged with every thread\n LOG(INFO) << \"This standard log is written by [Thread #\" << threadId << \"]\";\n\n \/\/ Following line will be logged with every thread only when --v=2 argument \n \/\/ is provided, i.e, .\/bin\/multithread_test.cpp.bin --v=2\n VLOG(2) << \"This is verbose level 2 logging from [Thread #\" << threadId << \"]\";\n\n \/\/ Following line will be logged only once from second running thread (which every runs second into \n \/\/ this line because of interval 2)\n LOG_EVERY_N(2, WARNING) << \"This will be logged only once from thread who every reaches this line first. Currently running from [Thread #\" << threadId << \"]\";\n\n for (int i = 1; i <= 10; ++i) {\n VLOG_IF(true, 2) << \"Verbose condition [Thread #\" << threadId << \"]\";\n VLOG_EVERY_N(2, 3) << \"Verbose level 3 log every 4th time. This is at \" << i << \" from [Thread #\" << threadId << \"]\";\n }\n\n \/\/ Following line will be logged once with every thread because of interval 1 \n LOG_EVERY_N(1, INFO) << \"This interval log will be logged with every thread, this one is from [Thread #\" << threadId << \"]\";\n\n LOG_IF(strcmp(threadId, \"2\") == 0, INFO) << \"This log is only for thread 2 and is ran by [Thread #\" << threadId << \"]\";\n\n \/\/ Register 5 vague loggers\n for (int i = 1; i <= 5; ++i) {\n std::stringstream ss;\n ss << \"logger\" << i;\n el::Logger* logger = easyloggingpp::Loggers::getLogger(ss.str());\n LOG(INFO) << \"Registered logger [\" << *logger << \"] [Thread #\" << threadId << \"]\";\n }\n CLOG(INFO, \"logger1\") << \"Logging using new logger [Thread #\" << threadId << \"]\";\n CLOG(INFO, \"no-logger\") << \"THIS SHOULD SAY LOGGER NOT REGISTERED YET [Thread #\" << threadId << \"]\"; \/\/ << -- NOTE THIS!\n\n el::Logger* logger = el::Loggers::getLogger(\"default\");\n logger->info(\"Info log from [Thread #%v]\", threadId);\n\n \/\/ Check for log counters positions\n for (int i = 1; i <= 50; ++i) {\n LOG_EVERY_N(2, INFO) << \"Counter pos: \" << ELPP_COUNTER_POS << \" [Thread #\" << threadId << \"]\";\n }\n LOG_EVERY_N(2, INFO) << \"Counter pos: \" << ELPP_COUNTER_POS << \" [Thread #\" << threadId << \"]\";\n return NULL;\n}\n\n\/\/ If you wish you can define your own way to get thread ID\nconst char* getThreadId_CustomVersion(void) {\n return std::to_string(static_cast(pthread_self())).c_str();\n}\n\nint main(int argc, char** argv)\n{\n _START_EASYLOGGINGPP(argc, argv);\n\n \/\/ Your thread ID specification\n el::CustomFormatSpecifier myThreadIdSpecifier(\"%mythreadId\", getThreadId_CustomVersion);\n el::Helpers::installCustomFormatSpecifier(myThreadIdSpecifier);\n\n \/\/ Note your %mythreadId or built-in, both are logged\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"%datetime %level (%thread | %mythreadId) [%logger] [%func] [%loc] %msg\");\n el::Loggers::reconfigureAllLoggers(el::Level::Verbose, el::ConfigurationType::Format, \"%datetime %level-%vlevel (%thread | %mythreadId) [%logger] [%func] [%loc] %msg\");\n\n pthread_t thread1, thread2, thread3, thread4;\n\n \/* Create independent threads each of which will execute function *\/\n pthread_create( &thread1, NULL, write, (void*)\"1\");\n pthread_create( &thread2, NULL, write, (void*)\"2\");\n pthread_create( &thread3, NULL, write, (void*)\"3\");\n \n el::Logger* logger = el::Loggers::getLogger(\"default\");\n args.thrId = \"4\";\n args.logger = logger;\n pthread_create( &thread4, NULL, write2, (void*)&args);\n\n pthread_join(thread1, NULL);\n pthread_join(thread2, NULL); \n pthread_join(thread3, NULL); \n pthread_join(thread4, NULL); \n\n exit(0);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \"snappy-sinksource.h\"\n\nnamespace snappy {\n\nSource::~Source() { }\n\nSink::~Sink() { }\n\nchar* Sink::GetAppendBuffer(size_t length, char* scratch) {\n return scratch;\n}\n\nByteArraySource::~ByteArraySource() { }\n\nsize_t ByteArraySource::Available() const { return left_; }\n\nconst char* ByteArraySource::Peek(size_t* len) {\n *len = left_;\n return ptr_;\n}\n\nvoid ByteArraySource::Skip(size_t n) {\n left_ -= n;\n ptr_ += n;\n}\n\nUncheckedByteArraySink::~UncheckedByteArraySink() { }\n\nvoid UncheckedByteArraySink::Append(const char* data, size_t n) {\n \/\/ Do no copying if the caller filled in the result of GetAppendBuffer()\n if (data != dest_) {\n memcpy(dest_, data, n);\n }\n dest_ += n;\n}\n\nchar* UncheckedByteArraySink::GetAppendBuffer(size_t len, char* scratch) {\n return dest_;\n}\n\n\n}\nFix more snappy compiler warnings.\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \"snappy-sinksource.h\"\n\nnamespace snappy {\n\nSource::~Source() { }\n\nSink::~Sink() { }\n\nchar* Sink::GetAppendBuffer(size_t \/* length *\/, char* scratch) {\n return scratch;\n}\n\nByteArraySource::~ByteArraySource() { }\n\nsize_t ByteArraySource::Available() const { return left_; }\n\nconst char* ByteArraySource::Peek(size_t* len) {\n *len = left_;\n return ptr_;\n}\n\nvoid ByteArraySource::Skip(size_t n) {\n left_ -= n;\n ptr_ += n;\n}\n\nUncheckedByteArraySink::~UncheckedByteArraySink() { }\n\nvoid UncheckedByteArraySink::Append(const char* data, size_t n) {\n \/\/ Do no copying if the caller filled in the result of GetAppendBuffer()\n if (data != dest_) {\n memcpy(dest_, data, n);\n }\n dest_ += n;\n}\n\nchar* UncheckedByteArraySink::GetAppendBuffer(size_t \/* len *\/, char* \/* scratch *\/) {\n return dest_;\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \n\n\/\/ TODO:\n\/\/ - REFLECTABLE\n\/\/ - REFLECTABLE_MEMBER_TYPE\n\/\/ - REFLECTABLE_MEMBER_FUNCTION\n\/\/ - REFLECTABLE_OPERATOR\n\/\/ - REFLECTABLE_OPERATOR_UNARY\n\/\/ - REFLECTABLE_OPERATOR_ASSIGNMENT\n\/\/ TODO:\n\/\/ - free function operators (see cppreference.com)\n\n\/\/ TODO: Re-enable tests\nREFLECTABLE(auto, operator!=, member_function);\nREFLECTABLE(auto, operator%, member_function);\nREFLECTABLE(auto, operator%=, member_function);\nREFLECTABLE(auto, operator&&, member_function);\nREFLECTABLE(auto, operator&, member_function);\nREFLECTABLE(auto, operator&=, member_function);\nREFLECTABLE(auto, operator(), member_function);\nREFLECTABLE(auto, operator*, member_function);\nREFLECTABLE(auto, operator*=, member_function);\nREFLECTABLE(auto, operator++, member_function);\nREFLECTABLE(auto, operator+, member_function);\nREFLECTABLE(auto, operator+=, member_function);\nREFLECTABLE(auto, operator-, member_function);\nREFLECTABLE(auto, operator--, member_function);\nREFLECTABLE(auto, operator-=, member_function);\nREFLECTABLE(auto, operator->*, member_function);\nREFLECTABLE(auto, operator\/, member_function);\nREFLECTABLE(auto, operator\/=, member_function);\nREFLECTABLE(auto, operator<, member_function);\nREFLECTABLE(auto, operator<<, member_function);\nREFLECTABLE(auto, operator<<=, member_function);\nREFLECTABLE(auto, operator<=, member_function);\nREFLECTABLE(auto, operator==, member_function);\nREFLECTABLE(auto, operator>, member_function);\nREFLECTABLE(auto, operator>=, member_function);\nREFLECTABLE(auto, operator>>, member_function);\nREFLECTABLE(auto, operator>>=, member_function);\nREFLECTABLE(auto, operator[], member_function);\nREFLECTABLE(auto, operator^, member_function);\nREFLECTABLE(auto, operator^=, member_function);\nREFLECTABLE(auto, operator|, member_function);\nREFLECTABLE(auto, operator|=, member_function);\nREFLECTABLE(auto, operator||, member_function);\n\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator!, member_function);\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator->, member_function);\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator~, member_function);\n\nREFLECTION_REFLECTABLE_NONINTRUSIVE_ASSIGNMENT_OPERATOR(auto, operator=, member_function);\n\n\/\/ TODO: operator,\n\/\/ #define REFLECTION_OPERATOR_COMMA operator,\n\/\/ REFLECTABLE(auto, REFLECTION_OPERATOR_COMMA, member_function);\nRemoved a TODO#include \n\n\/\/ TODO:\n\/\/ - REFLECTABLE\n\/\/ - REFLECTABLE_MEMBER_TYPE\n\/\/ - REFLECTABLE_MEMBER_FUNCTION\n\/\/ - REFLECTABLE_OPERATOR\n\/\/ - REFLECTABLE_OPERATOR_UNARY\n\/\/ - REFLECTABLE_OPERATOR_ASSIGNMENT\n\/\/ TODO:\n\/\/ - free function operators (see cppreference.com)\n\nREFLECTABLE(auto, operator!=, member_function);\nREFLECTABLE(auto, operator%, member_function);\nREFLECTABLE(auto, operator%=, member_function);\nREFLECTABLE(auto, operator&&, member_function);\nREFLECTABLE(auto, operator&, member_function);\nREFLECTABLE(auto, operator&=, member_function);\nREFLECTABLE(auto, operator(), member_function);\nREFLECTABLE(auto, operator*, member_function);\nREFLECTABLE(auto, operator*=, member_function);\nREFLECTABLE(auto, operator++, member_function);\nREFLECTABLE(auto, operator+, member_function);\nREFLECTABLE(auto, operator+=, member_function);\nREFLECTABLE(auto, operator-, member_function);\nREFLECTABLE(auto, operator--, member_function);\nREFLECTABLE(auto, operator-=, member_function);\nREFLECTABLE(auto, operator->*, member_function);\nREFLECTABLE(auto, operator\/, member_function);\nREFLECTABLE(auto, operator\/=, member_function);\nREFLECTABLE(auto, operator<, member_function);\nREFLECTABLE(auto, operator<<, member_function);\nREFLECTABLE(auto, operator<<=, member_function);\nREFLECTABLE(auto, operator<=, member_function);\nREFLECTABLE(auto, operator==, member_function);\nREFLECTABLE(auto, operator>, member_function);\nREFLECTABLE(auto, operator>=, member_function);\nREFLECTABLE(auto, operator>>, member_function);\nREFLECTABLE(auto, operator>>=, member_function);\nREFLECTABLE(auto, operator[], member_function);\nREFLECTABLE(auto, operator^, member_function);\nREFLECTABLE(auto, operator^=, member_function);\nREFLECTABLE(auto, operator|, member_function);\nREFLECTABLE(auto, operator|=, member_function);\nREFLECTABLE(auto, operator||, member_function);\n\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator!, member_function);\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator->, member_function);\nREFLECTION_REFLECTABLE_NONINTRUSIVE_UNARY_OPERATOR(auto, operator~, member_function);\n\nREFLECTION_REFLECTABLE_NONINTRUSIVE_ASSIGNMENT_OPERATOR(auto, operator=, member_function);\n\n\/\/ TODO: operator,\n\/\/ #define REFLECTION_OPERATOR_COMMA operator,\n\/\/ REFLECTABLE(auto, REFLECTION_OPERATOR_COMMA, member_function);\n<|endoftext|>"} {"text":"#include \"libcanister.h\"\n#include \"fileinterpretation.h\"\n#include \"bzipWrapper.h\"\nusing namespace std;\n\n\nlibcanister::canister::canister (char* fspath)\n{\n info.path = *(new canmem(fspath));\n cachemax = 25;\n cachecnt = 0;\n readonly = false;\n}\n\nlibcanister::canister::canister (canmem fspath)\n{\n info.path = fspath;\n cachemax = 25;\n cachecnt = 0;\n readonly = false;\n}\n\nlibcanister::canfile libcanister::canister::getTOC()\n{\n return TOC;\n}\n\nint libcanister::canister::delFile(canmem path)\n{\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if we found it\n if(!strcmp(files[i].path.data, path.data))\n {\n files[i].data.fragmem();\n files[i].cachestate = 2;\n files[i].isfrag = 1;\n files[i].cfid &= 0x80000000;\n files[i].path.data = (char*)\"FRAGMENT\";\n files[i].path.countlen();\n return 0;\n }\n i++;\n }\n return -1;\n}\n\nlibcanister::canfile libcanister::canister::getFile(canmem path)\n{\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if we found it\n if(!strcmp(files[i].path.data, path.data))\n {\n \/\/pull it into memory\n files[i].cache();\n \/\/and return it\n return files[i];\n }\n i++;\n }\n \/\/otherwise generate an error file to report it\n canfile tmp;\n tmp.data = *(new canmem((char*)\"Error: file not found.\"));\n tmp.cachestate = -1;\n return tmp;\n}\n\nbool libcanister::canister::writeFile(canmem path, canmem data)\n{\n \/\/here we simply wrap the information we're given and call\n \/\/the 'real' writeFile function\n canfile wrapper;\n wrapper.path = path;\n wrapper.data = data;\n wrapper.cfid = -1;\n wrapper.dsize = -1;\n wrapper.isfrag = 0;\n wrapper.cachestate = 2;\n wrapper.parent = this;\n writeFile(wrapper);\n return true;\n}\n\nbool libcanister::canister::writeFile(canfile file)\n{\n \/\/if we're in readonly mode, we're definitely not going to be\n \/\/writing this file under any circumstance.\n if (readonly)\n {\n cout << \"Error: canister is read only, file could not be written.\" << endl;\n return false;\n }\n \/\/we want to first figure out how much disk space it needs\n canmem tmpdata = bzipWrapper::compress(file.data);\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if it already exists\n if (!strcmp(files[i].path.data, file.path.data))\n {\n \/\/then we check to make sure the new version would fit within the old\n if (tmpdata.size == files[i].dsize || tmpdata.size < files[i].dsize - 6)\n {\n \/\/whereupon we make the changeover\n files[i].dsize = tmpdata.size;\n files[i].data = file.data;\n files[i].cachestate = 2; \/\/needs flush\n \/\/and handle the fragmented leftovers\n if (tmpdata.size < files[i].dsize - 6)\n {\n #warning \"Need to handle fragment.\"\n }\n return true;\n }\n else\n {\n \/\/otherwise, we're just going to have to make the original\n \/\/file into one big fragment and let the rest of the\n \/\/function take care of the bigger version of the file\n files[i].cfid &= 0x80000000;\n files[i].isfrag = 1;\n files[i].path = *(new canmem((char*)\"FRAGMENT\"));\n \/\/++info.numfiles; not sure if this was needed\n break;\n }\n }\n i++;\n }\n \/\/search for a fragment large enough to hold this\n while (i < info.numfiles)\n {\n \/\/is this a fragment?\n if (files[i].cfid & 0x80000000)\n {\n \/\/can we fit it inside the fragment?\n if (files[i].dsize >= tmpdata.size + 6)\n {\n files[i] = file;\n files[i].data = tmpdata;\n files[i].dsize = tmpdata.size;\n files[i].cachestate = 2;\n }\n }\n }\n \/\/here we generate a new CFID for the file\n file.cfid = ++info.numfiles;\n \/\/mark it to be in need of flushing\n file.cachestate = 2;\n \/\/it isn't a fragment\n file.isfrag = 0;\n \/\/then we rebuild the array to be one larger\n canfile* newSet = new canfile[info.numfiles];\n \/\/copy the old into the new\n memcpy(newSet, files, (info.numfiles - 1) * sizeof(canfile));\n \/\/put this file into the array\n newSet[info.numfiles-1] = file;\n \/\/and move the old pointer to look at this new array\n files = newSet;\n \/\/and here we add the new file onto the autogenerated TOC\n int tLen = TOC.data.size;\n TOC.data.size += file.path.size;\n char* tmp = TOC.data.data;\n TOC.data.data = new char[TOC.data.size];\n memcpy(TOC.data.data, tmp, tLen);\n memcpy(TOC.data.data + tLen, file.path.data, file.path.size);\n TOC.data.data[TOC.data.size-1] = '\\n';\n \/\/success!\n return true;\n}\n\n\/\/dumps files from memory until cachecnt <= cachemax\n\/\/first dumps unmodified files from memory until the condition is met\n\/\/however, it will do a full cache flush if needed\nvoid libcanister::canister::cacheclean (int sCFID, bool dFlush)\n{\n int i = 0;\n \/\/loop through and uncache files until we're within cachemax\n while (i < info.numfiles && cachecnt > cachemax)\n {\n \/\/preferably uncache only files which haven't been modified\n if (files[i].cfid != sCFID && (dFlush || files[i].cachestate == 1))\n {\n if (files[i].cachestate == 2)\n files[i].cachedump();\n else\n {\n files[i].data = canmem::null();\n files[i].cachestate = 0;\n }\n }\n i++;\n }\n\n \/\/if we still haven't done enough cleaning, flush the modified files too!\n if (!dFlush && cachecnt > cachemax && !readonly)\n cacheclean(sCFID, true);\n}\n\n\/\/actuates the close() item when naturally destroyed\nlibcanister::canister::~canister()\n{\n close();\n}\n\n\/\/flushes all caches and prepares for object deletion\nint libcanister::canister::close ()\n{\n \/\/don't do anything if readonly\n if (readonly)\n return 0;\n\n canmem fspath = info.path;\n fstream infile;\n infile.open(fspath.data, ios::in | ios::out | ios::binary);\n if (!infile.is_open())\n cout << \"Whoa there..\" << endl;\n infile.seekg(0, ios::beg);\n \/\/write the header verification (c00)\n unsigned char temp1, temp2, temp3, temp4, temp5;\n\n infile << 0x01;\n infile << 'c';\n infile << 'a';\n infile << 'n';\n infile << 0x01;\n\n\n \/\/write the new file count (filect) (c01)\n unsigned char* filect = (unsigned char*)(void*)&info.numfiles;\n infile << filect[3];\n infile << filect[2];\n infile << filect[1];\n infile << filect[0];\n\n \/\/make sure there is a footerloc (c11) in some form.\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile.seekg(14, ios::beg); \/\/seek to file section\n int i = 0;\n \/\/otherwise, loop through the files\n while (i < info.numfiles)\n {\n \/\/dout << files[i].cachestate << endl;\n files[i].cachedumpfinal(infile);\n files[i].data = canmem::null();\n files[i].cachestate = 0;\n i++;\n }\n \/\/here we rewrite the footer to represent the latest changes to the canister\n int footerloc = infile.tellg();\n \/\/ infile.seekg(footerloc, ios::beg); \/\/reset back to footer\n\n \/\/write footer verification (c00)\n infile << temp1;\n infile << temp2;\n infile << temp3;\n infile << temp4;\n infile << temp5;\n\n \/\/c02\n info.internalname.trim();\n infile.write(info.internalname.data, info.internalname.size);\n infile << (unsigned char)0x02;\n\n i = 0;\n while (i < info.numfiles)\n {\n \/\/c03\n infile << (unsigned char)0x01;\n\n \/\/c04\n unsigned char* sizeout = (unsigned char*)(void*)&files[i].dsize;\n infile << sizeout[7];\n infile << sizeout[6];\n infile << sizeout[5];\n infile << sizeout[4];\n infile << sizeout[3];\n infile << sizeout[2];\n infile << sizeout[1];\n infile << sizeout[0];\n\n \/\/c05\n unsigned char* id = (unsigned char*)(void*)&files[i].cfid;\n infile << id[3];\n infile << id[2];\n infile << id[1];\n infile << id[0];\n\n \/\/c06\n files[i].path.trim();\n infile.write(files[i].path.data, files[i].path.size);\n infile << (unsigned char)0x02;\n\n i++;\n }\n\n infile << (unsigned char)0x03; \/\/c07\n\n infile.seekg(9, ios::beg); \/\/go back to header\n\n \/\/write the new footerloc into place (c11)\n unsigned char* ftloc = (unsigned char*)(void*)&footerloc;\n infile << ftloc[3];\n infile << ftloc[2];\n infile << ftloc[1];\n infile << ftloc[0];\n infile << (unsigned char)0x03; \/\/c07\n\n \/\/no other modifications to the canister should happen after this point\n \/\/also prevents double closure from a manual close() call and the automated one\n \/\/coming from ~canister()\n readonly = true;\n return 0;\n}\n\nint libcanister::canister::open()\n{\n \/\/here we open the file associated with this canister\n canmem fspath = info.path;\n ifstream infile;\n infile.open(fspath.data);\n \/\/now we begin creating the table of contents\n TOC.parent = this;\n TOC.path = canmem::null();\n TOC.cachestate = 1;\n TOC.cfid = -1;\n TOC.dsize = 0;\n \/\/if the file didn't open, we need to do a\n \/\/skeletal initialization of the canister\n if (!infile.is_open())\n {\n info.internalname = *(new canmem((char*)\"generic canister\"));\n info.numfiles = 0;\n canmem tocData;\n tocData.data = (char*)\"\";\n tocData.size = 0;\n TOC.data = tocData;\n return 0;\n }\n \/\/otherwise, we're going to work on reading the file's\n \/\/header and footer into memory\n else\n {\n \/\/begin interpreting the file\n \/\/lets make some temporary variables to store the header\n unsigned char temp1, temp2, temp3, temp4, temp5;\n readonly = false;\n infile >> temp1;\n infile >> temp2;\n infile >> temp3;\n infile >> temp4;\n infile >> temp5;\n \/\/does the header match? (c00)\n if ((temp1 == 0x01) && (temp2 == 'c') && (temp3 == 'a') && (temp4 == 'n') && (temp5 == 0x01))\n { \/\/yes, valid header\n dout << \"valid header\" << endl;\n \/\/read in the number of files\n info.numfiles = readint32(infile);\n dout << \"numfiles: \" << info.numfiles << endl;\n #warning \"technically this should be a readint64, but seekg won't accept the 64-bit int. Solution needed.\"\n int footerloc = readint32(infile);\n infile.seekg(footerloc, ios::beg);\n \/\/does the footer match?\n infile >> temp1;\n infile >> temp2;\n infile >> temp3;\n infile >> temp4;\n infile >> temp5;\n if ((temp1 == 0x01) && (temp2 == 'c') && (temp3 == 'a') && (temp4 == 'n') && (temp5 == 0x01))\n { \/\/yes, valid footer (c00)\n \/\/create a file array to hold the files\n files = new canfile[info.numfiles];\n \/\/set the internal name of the canister\n info.internalname = readstr(infile);\n dout << \"internalname: \" << info.internalname.data << endl;\n int i = 0;\n char* tocRaw;\n int tocLen = 0;\n infile >> temp1;\n \/\/loop through the file headers for each file\n while (temp1 == 0x01)\n { \n \/\/if we've exceeded the number of files and have found another\n \/\/then something fishy is happening somewhere... let's just\n \/\/use the info we have and ignore the other stuff in here\n \/\/Entering read only mode to prevent further damage to the canister\n if (i >= info.numfiles)\n {\n cerr << \"Corrupted Canister! Error message: File table length exceeds the number of files!\" << endl;\n cerr << \"Best recovery option: read-only\" << endl;\n cerr << \"Opening as read-only to prevent further damage to the canister.\" << endl;\n readonly = true;\n \/\/loop to the end of the file header\n while (temp1 != 0x03)\n infile >> temp1;\n break;\n }\n \n \/\/read the file header\n files[i].parent = this;\n files[i].dsize = readint64(infile);\n dout << \"dsize: \" << files[i].dsize << endl;\n files[i].cfid = readint32(infile);\n dout << \"cfid: \" << files[i].cfid << endl;\n files[i].path = readstr(infile);\n files[i].cachestate = 0;\n files[i].data = canmem::null();\n if (files[i].cfid & 0x80000000 || !strcmp(files[i].path.data, (char*)\"FRAGMENT\"))\n files[i].isfrag = 1;\n else\n {\n files[i].isfrag = 0;\n \/\/deal with the table of contents\n int tLen = tocLen;\n tocLen += files[i].path.size;\n char* tmp = tocRaw;\n tocRaw = new char[tocLen];\n memcpy(tocRaw, tmp, tLen);\n memcpy(tocRaw + tLen, files[i].path.data, files[i].path.size);\n tocRaw[tocLen-1] = '\\n';\n }\n\n \/\/read the next file\n i++;\n infile >> temp1;\n }\n if (temp1 != 0x03)\n {\n cerr << \"Corrupted Canister! Error message: Incomplete file table! Data: \" << (unsigned int)temp1 << \" \" << infile.tellg() << endl;\n return -1;\n }\n if (tocLen > 0)\n tocRaw[tocLen] = 0x00;\n else\n {\n tocRaw = new char[1];\n tocRaw[0] = 0x00;\n }\n canmem tocDat = *(new canmem(tocLen));\n tocDat.data = tocRaw;\n TOC.data = tocDat;\n\n infile.close();\n \n return 1;\n }\n else\n {\n cout << \"Error: canister is corrupt.\" << endl;\n return -1;\n }\n }\n else\n {\n cout << \"Error: canister is corrupt.\" << endl;\n return -1;\n }\n }\n return -1;\n}\n\nminor fixes.#include \"libcanister.h\"\n#include \"fileinterpretation.h\"\n#include \"bzipWrapper.h\"\nusing namespace std;\n\n\nlibcanister::canister::canister (char* fspath)\n{\n info.path = *(new canmem(fspath));\n cachemax = 25;\n cachecnt = 0;\n readonly = false;\n}\n\nlibcanister::canister::canister (canmem fspath)\n{\n info.path = fspath;\n cachemax = 25;\n cachecnt = 0;\n readonly = false;\n}\n\nlibcanister::canfile libcanister::canister::getTOC()\n{\n return TOC;\n}\n\nint libcanister::canister::delFile(canmem path)\n{\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if we found it\n if(!strcmp(files[i].path.data, path.data))\n {\n files[i].data.fragmem();\n files[i].cachestate = 2;\n files[i].isfrag = 1;\n files[i].cfid &= 0x80000000;\n files[i].path.data = (char*)\"FRAGMENT\";\n files[i].path.countlen();\n return 0;\n }\n i++;\n }\n return -1;\n}\n\nlibcanister::canfile libcanister::canister::getFile(canmem path)\n{\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if we found it\n if(!strcmp(files[i].path.data, path.data))\n {\n \/\/pull it into memory\n files[i].cache();\n \/\/and return it\n return files[i];\n }\n i++;\n }\n \/\/otherwise generate an error file to report it\n canfile tmp;\n tmp.data = *(new canmem((char*)\"Error: file not found.\"));\n tmp.cachestate = -1;\n return tmp;\n}\n\nbool libcanister::canister::writeFile(canmem path, canmem data)\n{\n \/\/here we simply wrap the information we're given and call\n \/\/the 'real' writeFile function\n canfile wrapper;\n wrapper.path = path;\n wrapper.data = data;\n wrapper.cfid = -1;\n wrapper.dsize = -1;\n wrapper.isfrag = 0;\n wrapper.cachestate = 2;\n wrapper.parent = this;\n writeFile(wrapper);\n return true;\n}\n\nbool libcanister::canister::writeFile(canfile file)\n{\n \/\/if we're in readonly mode, we're definitely not going to be\n \/\/writing this file under any circumstance.\n if (readonly)\n {\n cout << \"Error: canister is read only, file could not be written.\" << endl;\n return false;\n }\n \/\/we want to first figure out how much disk space it needs\n canmem tmpdata = bzipWrapper::compress(file.data);\n int i = 0;\n \/\/search for the file\n while (i < info.numfiles)\n {\n \/\/if it already exists\n if (!strcmp(files[i].path.data, file.path.data))\n {\n \/\/then we check to make sure the new version would fit within the old\n if (tmpdata.size == files[i].dsize || tmpdata.size < files[i].dsize - 6)\n {\n \/\/whereupon we make the changeover\n files[i].dsize = tmpdata.size;\n files[i].data = file.data;\n files[i].cachestate = 2; \/\/needs flush\n \/\/and handle the fragmented leftovers\n if (tmpdata.size < files[i].dsize - 6)\n {\n #warning \"Need to handle fragment.\"\n }\n return true;\n }\n else\n {\n \/\/otherwise, we're just going to have to make the original\n \/\/file into one big fragment and let the rest of the\n \/\/function take care of the bigger version of the file\n files[i].cfid &= 0x80000000;\n files[i].isfrag = 1;\n files[i].path = *(new canmem((char*)\"FRAGMENT\"));\n \/\/++info.numfiles; not sure if this was needed\n break;\n }\n }\n i++;\n }\n \/\/search for a fragment large enough to hold this\n while (i < info.numfiles)\n {\n \/\/is this a fragment?\n if (files[i].cfid & 0x80000000)\n {\n \/\/can we fit it inside the fragment?\n if (files[i].dsize >= tmpdata.size + 6)\n {\n files[i] = file;\n files[i].data = tmpdata;\n files[i].dsize = tmpdata.size;\n files[i].cachestate = 2;\n }\n }\n }\n \/\/here we generate a new CFID for the file\n file.cfid = ++info.numfiles;\n \/\/mark it to be in need of flushing\n file.cachestate = 2;\n \/\/it isn't a fragment\n file.isfrag = 0;\n \/\/then we rebuild the array to be one larger\n canfile* newSet = new canfile[info.numfiles];\n \/\/copy the old into the new\n memcpy(newSet, files, (info.numfiles - 1) * sizeof(canfile));\n \/\/put this file into the array\n newSet[info.numfiles-1] = file;\n \/\/and move the old pointer to look at this new array\n files = newSet;\n \/\/and here we add the new file onto the autogenerated TOC\n int tLen = TOC.data.size;\n TOC.data.size += file.path.size;\n char* tmp = TOC.data.data;\n TOC.data.data = new char[TOC.data.size];\n memcpy(TOC.data.data, tmp, tLen);\n memcpy(TOC.data.data + tLen, file.path.data, file.path.size);\n TOC.data.data[TOC.data.size-1] = '\\n';\n \/\/success!\n return true;\n}\n\n\/\/dumps files from memory until cachecnt <= cachemax\n\/\/first dumps unmodified files from memory until the condition is met\n\/\/however, it will do a full cache flush if needed\nvoid libcanister::canister::cacheclean (int sCFID, bool dFlush)\n{\n int i = 0;\n \/\/loop through and uncache files until we're within cachemax\n while (i < info.numfiles && cachecnt > cachemax)\n {\n \/\/preferably uncache only files which haven't been modified\n if (files[i].cfid != sCFID && (dFlush || files[i].cachestate == 1))\n {\n if (files[i].cachestate == 2)\n files[i].cachedump();\n else\n {\n files[i].data = canmem::null();\n files[i].cachestate = 0;\n }\n }\n i++;\n }\n\n \/\/if we still haven't done enough cleaning, flush the modified files too!\n if (!dFlush && cachecnt > cachemax && !readonly)\n cacheclean(sCFID, true);\n}\n\n\/\/actuates the close() item when naturally destroyed\nlibcanister::canister::~canister()\n{\n close();\n}\n\n\/\/flushes all caches and prepares for object deletion\nint libcanister::canister::close ()\n{\n \/\/don't do anything if readonly\n if (readonly)\n return 0;\n\n canmem fspath = info.path;\n fstream infile;\n infile.open(fspath.data, ios::in | ios::out | ios::binary);\n if (!infile.is_open())\n cout << \"Whoa there..\" << endl;\n infile.seekg(0, ios::beg);\n \/\/write the header verification (c00)\n\n infile << 0x01;\n infile << 'c';\n infile << 'a';\n infile << 'n';\n infile << 0x01;\n\n\n \/\/write the new file count (filect) (c01)\n unsigned char* filect = (unsigned char*)(void*)&info.numfiles;\n infile << filect[3];\n infile << filect[2];\n infile << filect[1];\n infile << filect[0];\n\n \/\/make sure there is a footerloc (c11) in some form.\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile << (unsigned char)0xFF;\n infile.seekg(14, ios::beg); \/\/seek to file section\n int i = 0;\n \/\/otherwise, loop through the files\n while (i < info.numfiles)\n {\n \/\/dout << files[i].cachestate << endl;\n files[i].cachedumpfinal(infile);\n files[i].data = canmem::null();\n files[i].cachestate = 0;\n i++;\n }\n \/\/here we rewrite the footer to represent the latest changes to the canister\n int footerloc = infile.tellg();\n \/\/ infile.seekg(footerloc, ios::beg); \/\/reset back to footer\n\n \/\/write footer verification (c00)\n infile << 0x01;\n infile << 'c';\n infile << 'a';\n infile << 'n';\n infile << 0x01;\n\n \/\/c02\n info.internalname.trim();\n infile.write(info.internalname.data, info.internalname.size);\n infile << (unsigned char)0x02;\n\n i = 0;\n while (i < info.numfiles)\n {\n \/\/c03\n infile << (unsigned char)0x01;\n\n \/\/c04\n unsigned char* sizeout = (unsigned char*)(void*)&files[i].dsize;\n infile << sizeout[7];\n infile << sizeout[6];\n infile << sizeout[5];\n infile << sizeout[4];\n infile << sizeout[3];\n infile << sizeout[2];\n infile << sizeout[1];\n infile << sizeout[0];\n\n \/\/c05\n unsigned char* id = (unsigned char*)(void*)&files[i].cfid;\n infile << id[3];\n infile << id[2];\n infile << id[1];\n infile << id[0];\n\n \/\/c06\n files[i].path.trim();\n infile.write(files[i].path.data, files[i].path.size);\n infile << (unsigned char)0x02;\n\n i++;\n }\n\n infile << (unsigned char)0x03; \/\/c07\n\n infile.seekg(9, ios::beg); \/\/go back to header\n\n \/\/write the new footerloc into place (c11)\n unsigned char* ftloc = (unsigned char*)(void*)&footerloc;\n infile << ftloc[3];\n infile << ftloc[2];\n infile << ftloc[1];\n infile << ftloc[0];\n infile << (unsigned char)0x03; \/\/c07\n\n \/\/no other modifications to the canister should happen after this point\n \/\/also prevents double closure from a manual close() call and the automated one\n \/\/coming from ~canister()\n readonly = true;\n return 0;\n}\n\nint libcanister::canister::open()\n{\n \/\/here we open the file associated with this canister\n canmem fspath = info.path;\n ifstream infile;\n infile.open(fspath.data);\n \/\/now we begin creating the table of contents\n TOC.parent = this;\n TOC.path = canmem::null();\n TOC.cachestate = 1;\n TOC.cfid = -1;\n TOC.dsize = 0;\n \/\/if the file didn't open, we need to do a\n \/\/skeletal initialization of the canister\n if (!infile.is_open())\n {\n info.internalname = *(new canmem((char*)\"generic canister\"));\n info.numfiles = 0;\n canmem tocData;\n tocData.data = (char*)\"\";\n tocData.size = 0;\n TOC.data = tocData;\n return 0;\n }\n \/\/otherwise, we're going to work on reading the file's\n \/\/header and footer into memory\n else\n {\n \/\/begin interpreting the file\n \/\/lets make some temporary variables to store the header\n unsigned char temp1, temp2, temp3, temp4, temp5;\n readonly = false;\n infile >> temp1;\n infile >> temp2;\n infile >> temp3;\n infile >> temp4;\n infile >> temp5;\n \/\/does the header match? (c00)\n if ((temp1 == 0x01) && (temp2 == 'c') && (temp3 == 'a') && (temp4 == 'n') && (temp5 == 0x01))\n { \/\/yes, valid header\n dout << \"valid header\" << endl;\n \/\/read in the number of files\n info.numfiles = readint32(infile);\n dout << \"numfiles: \" << info.numfiles << endl;\n #warning \"technically this should be a readint64, but seekg won't accept the 64-bit int. Solution needed.\"\n int footerloc = readint32(infile);\n infile.seekg(footerloc, ios::beg);\n \/\/does the footer match?\n infile >> temp1;\n infile >> temp2;\n infile >> temp3;\n infile >> temp4;\n infile >> temp5;\n if ((temp1 == 0x01) && (temp2 == 'c') && (temp3 == 'a') && (temp4 == 'n') && (temp5 == 0x01))\n { \/\/yes, valid footer (c00)\n \/\/create a file array to hold the files\n files = new canfile[info.numfiles];\n \/\/set the internal name of the canister\n info.internalname = readstr(infile);\n dout << \"internalname: \" << info.internalname.data << endl;\n int i = 0;\n char* tocRaw = 0x0;\n int tocLen = 0;\n infile >> temp1;\n \/\/loop through the file headers for each file\n while (temp1 == 0x01)\n { \n \/\/if we've exceeded the number of files and have found another\n \/\/then something fishy is happening somewhere... let's just\n \/\/use the info we have and ignore the other stuff in here\n \/\/Entering read only mode to prevent further damage to the canister\n if (i >= info.numfiles)\n {\n cerr << \"Corrupted Canister! Error message: File table length exceeds the number of files!\" << endl;\n cerr << \"Best recovery option: read-only\" << endl;\n cerr << \"Opening as read-only to prevent further damage to the canister.\" << endl;\n readonly = true;\n \/\/loop to the end of the file header\n while (temp1 != 0x03)\n infile >> temp1;\n break;\n }\n \n \/\/read the file header\n files[i].parent = this;\n files[i].dsize = readint64(infile);\n dout << \"dsize: \" << files[i].dsize << endl;\n files[i].cfid = readint32(infile);\n dout << \"cfid: \" << files[i].cfid << endl;\n files[i].path = readstr(infile);\n files[i].cachestate = 0;\n files[i].data = canmem::null();\n if (files[i].cfid & 0x80000000 || !strcmp(files[i].path.data, (char*)\"FRAGMENT\"))\n files[i].isfrag = 1;\n else\n {\n files[i].isfrag = 0;\n \/\/deal with the table of contents\n int tLen = tocLen;\n tocLen += files[i].path.size;\n char* tmp = tocRaw;\n tocRaw = new char[tocLen];\n if (tLen > 0)\n memcpy(tocRaw, tmp, tLen);\n memcpy(tocRaw + tLen, files[i].path.data, files[i].path.size);\n tocRaw[tocLen-1] = '\\n';\n }\n\n \/\/read the next file\n i++;\n infile >> temp1;\n }\n if (temp1 != 0x03)\n {\n cerr << \"Corrupted Canister! Error message: Incomplete file table! Data: \" << (unsigned int)temp1 << \" \" << infile.tellg() << endl;\n return -1;\n }\n if (tocLen > 0)\n tocRaw[tocLen] = 0x00;\n else\n {\n tocRaw = new char[1];\n tocRaw[0] = 0x00;\n }\n canmem tocDat = *(new canmem(tocLen));\n tocDat.data = tocRaw;\n TOC.data = tocDat;\n\n infile.close();\n \n return 1;\n }\n else\n {\n cout << \"Error: canister is corrupt.\" << endl;\n return -1;\n }\n }\n else\n {\n cout << \"Error: canister is corrupt.\" << endl;\n return -1;\n }\n }\n return -1;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include \"server\/TSimpleServer.h\"\n#include \"transport\/TTransportException.h\"\n#include \n#include \n\nnamespace apache { namespace thrift { namespace server {\n\nusing namespace std;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\nusing boost::shared_ptr;\n\n\/**\n * A simple single-threaded application server. Perfect for unit tests!\n *\n *\/\nvoid TSimpleServer::serve() {\n\n shared_ptr client;\n shared_ptr inputTransport;\n shared_ptr outputTransport;\n shared_ptr inputProtocol;\n shared_ptr outputProtocol;\n\n try {\n \/\/ Start the server listening\n serverTransport_->listen();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TSimpleServer::run() listen(): \") + ttx.what();\n GlobalOutput(errStr.c_str());\n return;\n }\n\n \/\/ Run the preServe event\n if (eventHandler_ != NULL) {\n eventHandler_->preServe();\n }\n\n \/\/ Fetch client from server\n while (!stop_) {\n try {\n client = serverTransport_->accept();\n inputTransport = inputTransportFactory_->getTransport(client);\n outputTransport = outputTransportFactory_->getTransport(client);\n inputProtocol = inputProtocolFactory_->getProtocol(inputTransport);\n outputProtocol = outputProtocolFactory_->getProtocol(outputTransport);\n } catch (TTransportException& ttx) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n string errStr = string(\"TServerTransport died on accept: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n continue;\n } catch (TException& tx) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n string errStr = string(\"Some kind of accept exception: \") + tx.what();\n GlobalOutput(errStr.c_str());\n continue;\n } catch (string s) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n string errStr = string(\"Some kind of accept exception: \") + s;\n GlobalOutput(errStr.c_str());\n break;\n }\n\n \/\/ Get the processor\n shared_ptr processor = getProcessor(inputProtocol,\n outputProtocol, client);\n\n void* connectionContext = NULL;\n if (eventHandler_ != NULL) {\n connectionContext = eventHandler_->createContext(inputProtocol, outputProtocol);\n }\n try {\n for (;;) {\n if (eventHandler_ != NULL) {\n eventHandler_->processContext(connectionContext, client);\n }\n if (!processor->process(inputProtocol, outputProtocol,\n connectionContext) ||\n \/\/ Peek ahead, is the remote side closed?\n !inputProtocol->getTransport()->peek()) {\n break;\n }\n }\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer client died: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n } catch (const std::exception& x) {\n GlobalOutput.printf(\"TSimpleServer exception: %s: %s\",\n typeid(x).name(), x.what());\n } catch (...) {\n GlobalOutput(\"TSimpleServer uncaught exception.\");\n }\n if (eventHandler_ != NULL) {\n eventHandler_->deleteContext(connectionContext, inputProtocol, outputProtocol);\n }\n\n try {\n inputTransport->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer input close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n outputTransport->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer output close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n client->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer client close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n }\n\n if (stop_) {\n try {\n serverTransport_->close();\n } catch (TTransportException &ttx) {\n string errStr = string(\"TServerTransport failed on close: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n stop_ = false;\n }\n}\n\n}}} \/\/ apache::thrift::server\nThrift-1502:TSimpleServer::serve(): Do not print out error message if server was stopped. Client: cpp Patch: Vibhav Sreekanti\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include \"server\/TSimpleServer.h\"\n#include \"transport\/TTransportException.h\"\n#include \n#include \n\nnamespace apache { namespace thrift { namespace server {\n\nusing namespace std;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\nusing boost::shared_ptr;\n\n\/**\n * A simple single-threaded application server. Perfect for unit tests!\n *\n *\/\nvoid TSimpleServer::serve() {\n\n shared_ptr client;\n shared_ptr inputTransport;\n shared_ptr outputTransport;\n shared_ptr inputProtocol;\n shared_ptr outputProtocol;\n\n try {\n \/\/ Start the server listening\n serverTransport_->listen();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TSimpleServer::run() listen(): \") + ttx.what();\n GlobalOutput(errStr.c_str());\n return;\n }\n\n \/\/ Run the preServe event\n if (eventHandler_ != NULL) {\n eventHandler_->preServe();\n }\n\n \/\/ Fetch client from server\n while (!stop_) {\n try {\n client = serverTransport_->accept();\n inputTransport = inputTransportFactory_->getTransport(client);\n outputTransport = outputTransportFactory_->getTransport(client);\n inputProtocol = inputProtocolFactory_->getProtocol(inputTransport);\n outputProtocol = outputProtocolFactory_->getProtocol(outputTransport);\n } catch (TTransportException& ttx) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {\n string errStr = string(\"TServerTransport died on accept: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n continue;\n } catch (TException& tx) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n string errStr = string(\"Some kind of accept exception: \") + tx.what();\n GlobalOutput(errStr.c_str());\n continue;\n } catch (string s) {\n if (inputTransport != NULL) { inputTransport->close(); }\n if (outputTransport != NULL) { outputTransport->close(); }\n if (client != NULL) { client->close(); }\n string errStr = string(\"Some kind of accept exception: \") + s;\n GlobalOutput(errStr.c_str());\n break;\n }\n\n \/\/ Get the processor\n shared_ptr processor = getProcessor(inputProtocol,\n outputProtocol, client);\n\n void* connectionContext = NULL;\n if (eventHandler_ != NULL) {\n connectionContext = eventHandler_->createContext(inputProtocol, outputProtocol);\n }\n try {\n for (;;) {\n if (eventHandler_ != NULL) {\n eventHandler_->processContext(connectionContext, client);\n }\n if (!processor->process(inputProtocol, outputProtocol,\n connectionContext) ||\n \/\/ Peek ahead, is the remote side closed?\n !inputProtocol->getTransport()->peek()) {\n break;\n }\n }\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer client died: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n } catch (const std::exception& x) {\n GlobalOutput.printf(\"TSimpleServer exception: %s: %s\",\n typeid(x).name(), x.what());\n } catch (...) {\n GlobalOutput(\"TSimpleServer uncaught exception.\");\n }\n if (eventHandler_ != NULL) {\n eventHandler_->deleteContext(connectionContext, inputProtocol, outputProtocol);\n }\n\n try {\n inputTransport->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer input close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n outputTransport->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer output close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n client->close();\n } catch (const TTransportException& ttx) {\n string errStr = string(\"TSimpleServer client close failed: \")\n + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n }\n\n if (stop_) {\n try {\n serverTransport_->close();\n } catch (TTransportException &ttx) {\n string errStr = string(\"TServerTransport failed on close: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n stop_ = false;\n }\n}\n\n}}} \/\/ apache::thrift::server\n<|endoftext|>"} {"text":"\/\/ runV0ChCorrelations.C\n\/\/\n\/\/ AddTask for AliAnalysisTaskV0ChCorrelations task\n\/\/\nAliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const Bool_t bMCtruth=kFALSE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaDToPV = 0.1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaV0D = 1.0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n{\n \/\/ Creates a V0Ch correlations analysis task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskV0ChCorrelations\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ mc event handlerrunEx01.C\n if(bMCtruth) {\n AliMCEventHandler* mchandler = new AliMCEventHandler();\n \/\/ Not reading track references\n mchandler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(mchandler);\n } \n\n\t\/\/ create task\n AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations(\"V0ChCorrelations_task\");\n\ttask->SetDcaDToPV(DcaDToPV);\n\ttask->SetDcaV0D(DcaV0D);\n mgr->AddTask(task);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/ outputFileName = \"list.grid.v0ch.root\";\n\n \/\/ create containers for input\/output\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"coutput1\", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);\n \n \/\/ connect input\/output\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput1);\n \n \/\/ Return task pointer at the end\n return task;\n}\n\n\/\/ runV0ChCorrelations.C\n\/\/\n\/\/ AddTask for AliAnalysisTaskV0ChCorrelations task\n\/\/\nAliAnalysisTaskV0ChCorrelations *AddTaskV0ChCorrelations(const char * outfilename,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const Bool_t bMCtruth=kTRUE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaDToPV = 0.05,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Float_t DcaV0D = 3.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t const Bool_t bChCh=kTRUE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Int_t OStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n{\n \/\/ Creates a V0Ch correlations analysis task and adds it to the analysis manager.\n\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskV0ChCorrelations\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ mc event handlerrunEx01.C\n \/*\n\tif(bMCtruth) {\n\t\tcout << \"I am here too! \" << endl;\n AliAODMCEventHandler* mchandler = new AliAODMCEventHandler();\n \/\/ Not reading track references\n mchandler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(mchandler);\n } \n*\/\n\t\/\/ create task\n AliAnalysisTaskV0ChCorrelations* task = new AliAnalysisTaskV0ChCorrelations(\"V0ChCorrelations_task\");\n task->SetAnalysisMC(bMCtruth);\n\ttask->SetDcaDToPV(DcaDToPV);\n\ttask->SetDcaV0D(DcaV0D);\n\ttask->SetWithChCh(bChCh);\n\ttask->SetOStatus(OStatus);\n mgr->AddTask(task);\n \n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/outputFileName = \"list.grid.v0ch.root\";\n\n \/\/ create containers for input\/output\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(outfilename, TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);\n \n \/\/ connect input\/output\n mgr->ConnectInput(task, 0, cinput);\n mgr->ConnectOutput(task, 1, coutput1);\n \n \/\/ Return task pointer at the end\n return task;\n}\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n** Copyright (c) 2013-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \n#include \n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET))\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)\n# include \n#endif\n\n#if defined(_OPENMP)\n# include \n#endif\n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload_attribute(pop)\n#endif\n\n#define MAX_SIZE (80 * 80)\n\n\ntemplate\nstruct LIBXSMM_RETARGETABLE init {\n template init(T *LIBXSMM_RESTRICT dst, int nrows, int ncols, int n = 0, int ld = 0) {\n const int ldx = 0 == ld ? ncols : ld;\n const int minval = n + Seed, addval = (nrows - 1) * ldx + (ncols - 1);\n const int maxval = std::max(std::abs(minval), addval);\n const double norm = 0 != maxval ? (1.0 \/ maxval) : 1.0;\n for (int i = 0; i < nrows; ++i) {\n for (int j = 0; j < ncols; ++j) {\n const double value = static_cast(i * ldx + j + minval);\n dst[i*ldx+j] = static_cast(norm * (value - 0.5 * addval));\n }\n }\n }\n};\n\n\nint main(int argc, char* argv[])\n{\n try {\n typedef double T;\n const int m = 1 < argc ? std::atoi(argv[1]) : 23;\n const int n = 2 < argc ? std::atoi(argv[2]) : m;\n const int k = 3 < argc ? std::atoi(argv[3]) : m;\n\n const int csize = m * n;\n if ((MAX_SIZE) < csize) {\n throw std::runtime_error(\"The size M x N is exceeding MAX_SIZE!\");\n }\n\n const int asize = m * k, bsize = k * n, aspace = (LIBXSMM_ALIGNED_MAX) \/ sizeof(T);\n const int ldc = LIBXSMM_ALIGN_STORES(LIBXSMM_LD(m, n), sizeof(T));\n const int csize_act = ldc*n;\n const int s = (2ULL << 30) \/ ((asize + bsize + csize_act) * sizeof(T)); \/\/ 2 GByte\n const size_t bwsize_batched = (asize\/*load*\/ + bsize\/*load*\/ + 2*csize_act \/*RFO*\/) * sizeof(T); \/\/ batched\n const size_t bwsize = (asize\/*load*\/ + bsize\/*load*\/) * sizeof(T); \/\/ streamed, we skip C as this just in cache\n const double gflops = 2.0 * s * m * n * k * 1E-9;\n\n struct raii { \/\/ avoid std::vector (first-touch init. causes NUMA issue)\n T *a, *b, *c;\n raii(int asize, int bsize, int csize_act): a(new T[asize]), b(new T[bsize]), c(new T[csize_act]) {}\n ~raii() { delete[] a; delete[] b; delete[] c; }\n } buffer(s * asize + aspace - 1, s * bsize + aspace - 1, s * csize_act + aspace - 1);\n T *const a = LIBXSMM_ALIGN(buffer.a, LIBXSMM_ALIGNED_MAX);\n T *const b = LIBXSMM_ALIGN(buffer.b, LIBXSMM_ALIGNED_MAX);\n T *c = LIBXSMM_ALIGN(buffer.c, LIBXSMM_ALIGNED_MAX);\n\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n init<42>(a + i * asize, m, k, i);\n init<24>(b + i * bsize, k, n, i);\n init<22>(c + i * csize_act, ldc, n, i);\n }\n\n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload target(LIBXSMM_OFFLOAD_TARGET) in(a: length(s * asize)) in(b: length(s * bsize)) inout(c: length(s * csize_act))\n#endif\n {\n#if defined(MKL_ENABLE_AVX512_MIC)\n mkl_enable_instructions(MKL_ENABLE_AVX512_MIC);\n#endif\n \/\/ initialize LIBXSMM\n libxsmm_init();\n\n fprintf(stdout, \"m=%i n=%i k=%i ldc=%i (%s) size=%i memory=%.f MB\\n\\n\",\n m, n, k, ldc, 0 != (LIBXSMM_ROW_MAJOR) ? \"row-major\" : \"column-major\",\n s, 1.0 * s * (asize + bsize + csize_act) * sizeof(T) \/ (1 << 20));\n\n { \/\/ batched\n fprintf(stdout, \"Batched (A,B,C)...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n const T *const pa = a + i * asize, *const pb = b + i * bsize;\n T* pc = c + i * csize_act;\n libxsmm_imm(m, n, k, pa, pb, pc);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", s * bwsize_batched \/ (duration * (1 << 30)));\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n { \/\/ streaming\n fprintf(stdout, \"Streamed (A,B)...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n \/\/ make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules\n LIBXSMM_ALIGNED(T tmp[MAX_SIZE], LIBXSMM_ALIGNED_MAX);\n const T *const pa = a + i * asize, *const pb = b + i * bsize;\n libxsmm_imm(m, n, k, pa, pb, tmp);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", s * bwsize \/ (duration * (1 << 30)));\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n { \/\/ cached\n fprintf(stdout, \"Cached...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n \/\/ make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules\n LIBXSMM_ALIGNED(T tmp[MAX_SIZE], LIBXSMM_ALIGNED_MAX);\n \/\/ do nothing else with tmp; just a benchmark\n libxsmm_imm(m, n, k, a, b, tmp);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n fprintf(stdout, \"Finished\\n\");\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\nCall LIBXSMM_XIMM rather than libxsmm_imm since the latter was removed as part of resolving issue #35.\/******************************************************************************\n** Copyright (c) 2013-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \n#include \n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET))\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(USE_MKL) || defined(MKL_DIRECT_CALL_SEQ) || defined(MKL_DIRECT_CALL)\n# include \n#endif\n\n#if defined(_OPENMP)\n# include \n#endif\n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload_attribute(pop)\n#endif\n\n#define MAX_SIZE (80 * 80)\n\n\ntemplate\nstruct LIBXSMM_RETARGETABLE init {\n template init(T *LIBXSMM_RESTRICT dst, int nrows, int ncols, int n = 0, int ld = 0) {\n const int ldx = 0 == ld ? ncols : ld;\n const int minval = n + Seed, addval = (nrows - 1) * ldx + (ncols - 1);\n const int maxval = std::max(std::abs(minval), addval);\n const double norm = 0 != maxval ? (1.0 \/ maxval) : 1.0;\n for (int i = 0; i < nrows; ++i) {\n for (int j = 0; j < ncols; ++j) {\n const double value = static_cast(i * ldx + j + minval);\n dst[i*ldx+j] = static_cast(norm * (value - 0.5 * addval));\n }\n }\n }\n};\n\n\nint main(int argc, char* argv[])\n{\n try {\n typedef double T;\n const int m = 1 < argc ? std::atoi(argv[1]) : 23;\n const int n = 2 < argc ? std::atoi(argv[2]) : m;\n const int k = 3 < argc ? std::atoi(argv[3]) : m;\n\n const int csize = m * n;\n if ((MAX_SIZE) < csize) {\n throw std::runtime_error(\"The size M x N is exceeding MAX_SIZE!\");\n }\n\n const int asize = m * k, bsize = k * n, aspace = (LIBXSMM_ALIGNED_MAX) \/ sizeof(T);\n const int ldc = LIBXSMM_ALIGN_STORES(LIBXSMM_LD(m, n), sizeof(T));\n const int csize_act = ldc*n;\n const int s = (2ULL << 30) \/ ((asize + bsize + csize_act) * sizeof(T)); \/\/ 2 GByte\n const size_t bwsize_batched = (asize\/*load*\/ + bsize\/*load*\/ + 2*csize_act \/*RFO*\/) * sizeof(T); \/\/ batched\n const size_t bwsize = (asize\/*load*\/ + bsize\/*load*\/) * sizeof(T); \/\/ streamed, we skip C as this just in cache\n const double gflops = 2.0 * s * m * n * k * 1E-9;\n\n struct raii { \/\/ avoid std::vector (first-touch init. causes NUMA issue)\n T *a, *b, *c;\n raii(int asize, int bsize, int csize_act): a(new T[asize]), b(new T[bsize]), c(new T[csize_act]) {}\n ~raii() { delete[] a; delete[] b; delete[] c; }\n } buffer(s * asize + aspace - 1, s * bsize + aspace - 1, s * csize_act + aspace - 1);\n T *const a = LIBXSMM_ALIGN(buffer.a, LIBXSMM_ALIGNED_MAX);\n T *const b = LIBXSMM_ALIGN(buffer.b, LIBXSMM_ALIGNED_MAX);\n T *c = LIBXSMM_ALIGN(buffer.c, LIBXSMM_ALIGNED_MAX);\n\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n init<42>(a + i * asize, m, k, i);\n init<24>(b + i * bsize, k, n, i);\n init<22>(c + i * csize_act, ldc, n, i);\n }\n\n\n#if defined(LIBXSMM_OFFLOAD_BUILD)\n# pragma offload target(LIBXSMM_OFFLOAD_TARGET) in(a: length(s * asize)) in(b: length(s * bsize)) inout(c: length(s * csize_act))\n#endif\n {\n#if defined(MKL_ENABLE_AVX512_MIC)\n mkl_enable_instructions(MKL_ENABLE_AVX512_MIC);\n#endif\n \/\/ initialize LIBXSMM\n libxsmm_init();\n\n fprintf(stdout, \"m=%i n=%i k=%i ldc=%i (%s) size=%i memory=%.f MB\\n\\n\",\n m, n, k, ldc, 0 != (LIBXSMM_ROW_MAJOR) ? \"row-major\" : \"column-major\",\n s, 1.0 * s * (asize + bsize + csize_act) * sizeof(T) \/ (1 << 20));\n\n { \/\/ batched\n fprintf(stdout, \"Batched (A,B,C)...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n const T *const pa = a + i * asize, *const pb = b + i * bsize;\n T* pc = c + i * csize_act;\n LIBXSMM_XIMM(m, n, k, pa, pb, pc, 0);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", s * bwsize_batched \/ (duration * (1 << 30)));\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n { \/\/ streaming\n fprintf(stdout, \"Streamed (A,B)...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n \/\/ make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules\n LIBXSMM_ALIGNED(T tmp[MAX_SIZE], LIBXSMM_ALIGNED_MAX);\n const T *const pa = a + i * asize, *const pb = b + i * bsize;\n LIBXSMM_XIMM(m, n, k, pa, pb, tmp, 0);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n fprintf(stdout, \"\\tbandwidth: %.1f GB\/s\\n\", s * bwsize \/ (duration * (1 << 30)));\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n { \/\/ cached\n fprintf(stdout, \"Cached...\\n\");\n const unsigned long long start = libxsmm_timer_tick();\n#if defined(_OPENMP)\n# pragma omp parallel for\n#endif\n for (int i = 0; i < s; ++i) {\n \/\/ make sure that stacksize is covering the problem size; tmp is zero-initialized by lang. rules\n LIBXSMM_ALIGNED(T tmp[MAX_SIZE], LIBXSMM_ALIGNED_MAX);\n \/\/ do nothing else with tmp; just a benchmark\n LIBXSMM_XIMM(m, n, k, a, b, tmp, 0);\n }\n const double duration = libxsmm_timer_duration(start, libxsmm_timer_tick());\n if (0 < duration) {\n fprintf(stdout, \"\\tperformance: %.1f GFLOPS\/s\\n\", gflops \/ duration);\n }\n fprintf(stdout, \"\\tduration: %.0f ms\\n\", 1000.0 * duration);\n }\n\n fprintf(stdout, \"Finished\\n\");\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"summarywidget.h\"\n\nSummaryWidget::SummaryWidget( QWidget *parent, const char *name )\n : Kontact::Summary( parent, name ),\n DCOPObject( \"WeatherSummaryWidget\" ), mProc( 0 )\n{\n mLayout = new QVBoxLayout( this, 3, 3 );\n mLayout->setAlignment( Qt::AlignTop );\n\n QPixmap icon = KGlobal::iconLoader()->loadIcon( \"kweather\", KIcon::Desktop, KIcon::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Weather Information\" ) );\n mLayout->addWidget( header );\n\n QString error;\n QCString appID;\n bool serviceAvailable = true;\n if ( !kapp->dcopClient()->isApplicationRegistered( \"KWeatherService\" ) ) {\n if ( KApplication::startServiceByDesktopName( \"kweatherservice\", QStringList(), &error, &appID ) ) {\n QLabel *label = new QLabel( i18n( \"No weather dcop service available;\\nyou need KWeather to use this plugin.\" ), this );\n mLayout->addWidget( label, Qt::AlignHCenter );\n serviceAvailable = false;\n }\n }\n\n if ( serviceAvailable ) {\n connectDCOPSignal( 0, 0, \"fileUpdate(QString)\", \"refresh(QString)\", false );\n connectDCOPSignal( 0, 0, \"stationRemoved(QString)\", \"stationRemoved(QString)\", false );\n\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n DCOPReply reply = dcopCall.call( \"listStations()\", true );\n if ( reply.isValid() ) {\n mStations = reply;\n\n connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );\n mTimer.start( 0 );\n } else {\n kdDebug(5602) << \"ERROR: dcop reply not valid...\" << endl;\n }\n }\n}\n\n\nvoid SummaryWidget::updateView()\n{\n mLayouts.setAutoDelete( true );\n mLayouts.clear();\n mLayouts.setAutoDelete( false );\n\n mLabels.setAutoDelete( true );\n mLabels.clear();\n mLabels.setAutoDelete( false );\n\n if ( mStations.count() == 0 ) {\n kdDebug(5602) << \"No weather stations defined...\" << endl;\n return;\n }\n\n\n QValueList dataList = mWeatherMap.values();\n qHeapSort( dataList );\n\n QValueList::Iterator it;\n for ( it = dataList.begin(); it != dataList.end(); ++it ) {\n QString cover;\n for ( uint i = 0; i < (*it).cover().count(); ++i )\n cover += QString( \"- %1\\n\" ).arg( (*it).cover()[ i ] );\n\n QImage img;\n img = (*it).icon();\n\n QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 );\n mLayouts.append( layout );\n\n KURLLabel* urlLabel = new KURLLabel(this);\n urlLabel->installEventFilter(this);\n urlLabel->setURL((*it).stationID());\n urlLabel->setPixmap( img.smoothScale( 32, 32 ) );\n urlLabel->setMaximumSize(urlLabel->sizeHint());\n urlLabel->setAlignment(\/* AlignRight |*\/ AlignTop );\n layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 );\n mLabels.append( urlLabel );\n connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ),\n \tthis, SLOT(slotShowReport(const QString& )));\n\n QLabel* label = new QLabel( this );\n label->setText( QString( \"%1 (%2)\" ).arg( (*it).name() ).arg( (*it).temperature() ) );\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n label->setAlignment( AlignLeft );\n layout->addMultiCellWidget( label, 0, 0, 1, 2 );\n mLabels.append( label );\n\n QString labelText;\n labelText = QString( \"%1:<\/b> %2
\"\n \"%3:<\/b> %4\" )\n .arg( i18n( \"Wind Speed\" ) )\n .arg( (*it).windSpeed() )\n .arg( i18n( \"Rel. Humidity\" ) )\n .arg( (*it).relativeHumidity() );\n\n QToolTip::add( label, labelText.replace( \" \", \" \" ) );\n\n label = new QLabel( cover, this );\n label->setAlignment( AlignLeft );\n layout->addMultiCellWidget( label, 1, 1, 1, 2 );\n mLabels.append( label );\n }\n\n for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )\n label->show();\n\n mLayout->addStretch( 1 );\n}\n\nvoid SummaryWidget::timeout()\n{\n mTimer.stop();\n\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n dcopCall.send( \"updateAll()\" );\n\n mTimer.start( 15 * 60000 );\n}\n\nvoid SummaryWidget::refresh( QString station )\n{\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n\n mWeatherMap[ station ].setIcon( dcopCall.call( \"currentIcon(QString)\", station, true ) );\n mWeatherMap[ station ].setName( dcopCall.call( \"stationName(QString)\", station, true ) );\n mWeatherMap[ station ].setCover( dcopCall.call( \"cover(QString)\", station, true ) );\n mWeatherMap[ station ].setTemperature( dcopCall.call( \"temperature(QString)\", station, true ) );\n mWeatherMap[ station ].setWindSpeed( dcopCall.call( \"wind(QString)\", station, true ) );\n mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( \"relativeHumidity(QString)\", station, true ) );\n mWeatherMap[ station ].setStationID(station);\n\n updateView();\n}\n\nvoid SummaryWidget::stationRemoved( QString station )\n{\n mWeatherMap.remove( station );\n updateView();\n}\n\nQStringList SummaryWidget::configModules() const\n{\n return QStringList( \"kcmweatherservice.desktop\" );\n}\n\nvoid SummaryWidget::slotShowReport(const QString &stationID)\n{\n mProc = new KProcess;\n QApplication::connect(mProc, SIGNAL(processExited(KProcess *)),\n\tthis, SLOT(slotReportFinished(KProcess* )));\n *mProc << \"kweatherreport\";\n *mProc << stationID;\n if ( !mProc->start() )\n {\n delete mProc;\n mProc=0;\n }\n}\n\nvoid SummaryWidget::slotReportFinished(KProcess* \/*proc*\/){\n delete mProc;\n mProc = 0;\n}\n\n#include \"summarywidget.moc\"\nRemove spacer to avoid empty space between the plugin header and the KURL's approved by: Reinhold\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"summarywidget.h\"\n\nSummaryWidget::SummaryWidget( QWidget *parent, const char *name )\n : Kontact::Summary( parent, name ),\n DCOPObject( \"WeatherSummaryWidget\" ), mProc( 0 )\n{\n mLayout = new QVBoxLayout( this, 3, 3 );\n mLayout->setAlignment( Qt::AlignTop );\n\n QPixmap icon = KGlobal::iconLoader()->loadIcon( \"kweather\", KIcon::Desktop, KIcon::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Weather Information\" ) );\n mLayout->addWidget( header );\n\n QString error;\n QCString appID;\n bool serviceAvailable = true;\n if ( !kapp->dcopClient()->isApplicationRegistered( \"KWeatherService\" ) ) {\n if ( KApplication::startServiceByDesktopName( \"kweatherservice\", QStringList(), &error, &appID ) ) {\n QLabel *label = new QLabel( i18n( \"No weather dcop service available;\\nyou need KWeather to use this plugin.\" ), this );\n mLayout->addWidget( label, Qt::AlignHCenter );\n serviceAvailable = false;\n }\n }\n\n if ( serviceAvailable ) {\n connectDCOPSignal( 0, 0, \"fileUpdate(QString)\", \"refresh(QString)\", false );\n connectDCOPSignal( 0, 0, \"stationRemoved(QString)\", \"stationRemoved(QString)\", false );\n\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n DCOPReply reply = dcopCall.call( \"listStations()\", true );\n if ( reply.isValid() ) {\n mStations = reply;\n\n connect( &mTimer, SIGNAL( timeout() ), this, SLOT( timeout() ) );\n mTimer.start( 0 );\n } else {\n kdDebug(5602) << \"ERROR: dcop reply not valid...\" << endl;\n }\n }\n}\n\n\nvoid SummaryWidget::updateView()\n{\n mLayouts.setAutoDelete( true );\n mLayouts.clear();\n mLayouts.setAutoDelete( false );\n\n mLabels.setAutoDelete( true );\n mLabels.clear();\n mLabels.setAutoDelete( false );\n\n if ( mStations.count() == 0 ) {\n kdDebug(5602) << \"No weather stations defined...\" << endl;\n return;\n }\n\n\n QValueList dataList = mWeatherMap.values();\n qHeapSort( dataList );\n\n QValueList::Iterator it;\n for ( it = dataList.begin(); it != dataList.end(); ++it ) {\n QString cover;\n for ( uint i = 0; i < (*it).cover().count(); ++i )\n cover += QString( \"- %1\\n\" ).arg( (*it).cover()[ i ] );\n\n QImage img;\n img = (*it).icon();\n\n QGridLayout *layout = new QGridLayout( mLayout, 3, 3, 3 );\n mLayouts.append( layout );\n\n KURLLabel* urlLabel = new KURLLabel(this);\n urlLabel->installEventFilter(this);\n urlLabel->setURL((*it).stationID());\n urlLabel->setPixmap( img.smoothScale( 32, 32 ) );\n urlLabel->setMaximumSize(urlLabel->sizeHint());\n urlLabel->setAlignment(\/* AlignRight |*\/ AlignTop );\n layout->addMultiCellWidget( urlLabel, 0, 1, 0, 0 );\n mLabels.append( urlLabel );\n connect (urlLabel, SIGNAL(leftClickedURL( const QString&) ),\n \tthis, SLOT(slotShowReport(const QString& )));\n\n QLabel* label = new QLabel( this );\n label->setText( QString( \"%1 (%2)\" ).arg( (*it).name() ).arg( (*it).temperature() ) );\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n label->setAlignment( AlignLeft );\n layout->addMultiCellWidget( label, 0, 0, 1, 2 );\n mLabels.append( label );\n\n QString labelText;\n labelText = QString( \"%1:<\/b> %2
\"\n \"%3:<\/b> %4\" )\n .arg( i18n( \"Wind Speed\" ) )\n .arg( (*it).windSpeed() )\n .arg( i18n( \"Rel. Humidity\" ) )\n .arg( (*it).relativeHumidity() );\n\n QToolTip::add( label, labelText.replace( \" \", \" \" ) );\n\n label = new QLabel( cover, this );\n label->setAlignment( AlignLeft );\n layout->addMultiCellWidget( label, 1, 1, 1, 2 );\n mLabels.append( label );\n }\n\n for ( QLabel *label = mLabels.first(); label; label = mLabels.next() )\n label->show();\n}\n\nvoid SummaryWidget::timeout()\n{\n mTimer.stop();\n\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n dcopCall.send( \"updateAll()\" );\n\n mTimer.start( 15 * 60000 );\n}\n\nvoid SummaryWidget::refresh( QString station )\n{\n DCOPRef dcopCall( \"KWeatherService\", \"WeatherService\" );\n\n mWeatherMap[ station ].setIcon( dcopCall.call( \"currentIcon(QString)\", station, true ) );\n mWeatherMap[ station ].setName( dcopCall.call( \"stationName(QString)\", station, true ) );\n mWeatherMap[ station ].setCover( dcopCall.call( \"cover(QString)\", station, true ) );\n mWeatherMap[ station ].setTemperature( dcopCall.call( \"temperature(QString)\", station, true ) );\n mWeatherMap[ station ].setWindSpeed( dcopCall.call( \"wind(QString)\", station, true ) );\n mWeatherMap[ station ].setRelativeHumidity( dcopCall.call( \"relativeHumidity(QString)\", station, true ) );\n mWeatherMap[ station ].setStationID(station);\n\n updateView();\n}\n\nvoid SummaryWidget::stationRemoved( QString station )\n{\n mWeatherMap.remove( station );\n updateView();\n}\n\nQStringList SummaryWidget::configModules() const\n{\n return QStringList( \"kcmweatherservice.desktop\" );\n}\n\nvoid SummaryWidget::slotShowReport(const QString &stationID)\n{\n mProc = new KProcess;\n QApplication::connect(mProc, SIGNAL(processExited(KProcess *)),\n\tthis, SLOT(slotReportFinished(KProcess* )));\n *mProc << \"kweatherreport\";\n *mProc << stationID;\n if ( !mProc->start() )\n {\n delete mProc;\n mProc=0;\n }\n}\n\nvoid SummaryWidget::slotReportFinished(KProcess* \/*proc*\/){\n delete mProc;\n mProc = 0;\n}\n\n#include \"summarywidget.moc\"\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"..\\task1\\VectorProcessor.h\"\r\n\r\nusing namespace std;\n\nbool VectorsAreEqual(vector const& x, vector const& y)\n{\n\treturn x == y;\n}\n\n\/\/ Функция ProcessVector\nBOOST_AUTO_TEST_SUITE(ProcessVector_function)\n\n\t\/\/ Создает пустой вектор из пустого вектора\n\tBOOST_AUTO_TEST_CASE(makes_empty_vector_from_empty_vector)\n\t{\n\t\tvector emptyVector;\n\t\tProcessVector(emptyVector);\n\t\tBOOST_CHECK(emptyVector.empty());\n\t}\n\n\t\/\/ не изменяет содержимое вектора, который не содержит положительных чисел\n\tBOOST_AUTO_TEST_CASE(does_not_change_vector_containing_no_positive_numbers)\n\t{\n\t\tvector numbers = { -4, 0, -3 };\n\t\tauto copy(numbers);\n\t\tProcessVector(numbers);\n\t\tBOOST_CHECK(numbers == copy);\n\t}\n\n\t\/\/ при обработке вектора с одним положительным числом\n\tBOOST_AUTO_TEST_SUITE(when_processing_a_vector_with_one_positive_number)\r\n\t\t\/\/ должен добавить это число ко всем элементам вектора\r\n\t\tBOOST_AUTO_TEST_CASE(should_add_this_number_to_each_element)\n\t\t{\n\t\t\tvector numbers = { -1, 3.5 };\n\t\t\tProcessVector(numbers);\n\n\t\t\tBOOST_CHECK(VectorsAreEqual( numbers, \n\t\t\t\t{ (-1 + 3.5), (3.5 + 3.5) }\n\t\t\t));\n\t\t}\n\tBOOST_AUTO_TEST_SUITE_END()\n\n\t\/\/ при обработке вектора с несколькими положительными элементами\n\tBOOST_AUTO_TEST_SUITE(when_processing_a_vector_with_several_positive_elements)\r\n\t\t\/\/ должен добавить их среднее арифметическое к каждому элементу\r\n\t\tBOOST_AUTO_TEST_CASE(should_add_their_average_to_each_element)\r\n\t\t{\r\n\t\t\tvector numbers = { -1, 1, 2, 3 };\n\t\t\tProcessVector(numbers);\n\n\t\t\tconst double average = (1.0 + 2.0 + 3.0) \/ 3;\n\t\t\tBOOST_CHECK(VectorsAreEqual(numbers,\n\t\t\t{ (-1 + average), (1 + average), (2 + average), (3 + average) }\n\t\t\t));\n\t\t}\r\n\tBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nобновлены концы строк#include \"stdafx.h\"\r\n#include \"..\\task1\\VectorProcessor.h\"\r\n\r\nusing namespace std;\r\n\r\nbool VectorsAreEqual(vector const& x, vector const& y)\r\n{\r\n\treturn x == y;\r\n}\r\n\r\n\/\/ Функция ProcessVector\r\nBOOST_AUTO_TEST_SUITE(ProcessVector_function)\r\n\r\n\t\/\/ Создает пустой вектор из пустого вектора\r\n\tBOOST_AUTO_TEST_CASE(makes_empty_vector_from_empty_vector)\r\n\t{\r\n\t\tvector emptyVector;\r\n\t\tProcessVector(emptyVector);\r\n\t\tBOOST_CHECK(emptyVector.empty());\r\n\t}\r\n\r\n\t\/\/ не изменяет содержимое вектора, который не содержит положительных чисел\r\n\tBOOST_AUTO_TEST_CASE(does_not_change_vector_containing_no_positive_numbers)\r\n\t{\r\n\t\tvector numbers = { -4, 0, -3 };\r\n\t\tauto copy(numbers);\r\n\t\tProcessVector(numbers);\r\n\t\tBOOST_CHECK(numbers == copy);\r\n\t}\r\n\r\n\t\/\/ при обработке вектора с одним положительным числом\r\n\tBOOST_AUTO_TEST_SUITE(when_processing_a_vector_with_one_positive_number)\r\n\t\t\/\/ должен добавить это число ко всем элементам вектора\r\n\t\tBOOST_AUTO_TEST_CASE(should_add_this_number_to_each_element)\r\n\t\t{\r\n\t\t\tvector numbers = { -1, 3.5 };\r\n\t\t\tProcessVector(numbers);\r\n\r\n\t\t\tBOOST_CHECK(VectorsAreEqual( numbers, \r\n\t\t\t\t{ (-1 + 3.5), (3.5 + 3.5) }\r\n\t\t\t));\r\n\t\t}\r\n\tBOOST_AUTO_TEST_SUITE_END()\r\n\r\n\t\/\/ при обработке вектора с несколькими положительными элементами\r\n\tBOOST_AUTO_TEST_SUITE(when_processing_a_vector_with_several_positive_elements)\r\n\t\t\/\/ должен добавить их среднее арифметическое к каждому элементу\r\n\t\tBOOST_AUTO_TEST_CASE(should_add_their_average_to_each_element)\r\n\t\t{\r\n\t\t\tvector numbers = { -1, 1, 2, 3 };\r\n\t\t\tProcessVector(numbers);\r\n\r\n\t\t\tconst double average = (1.0 + 2.0 + 3.0) \/ 3;\r\n\t\t\tBOOST_CHECK(VectorsAreEqual(numbers,\r\n\t\t\t{ (-1 + average), (1 + average), (2 + average), (3 + average) }\r\n\t\t\t));\r\n\t\t}\r\n\tBOOST_AUTO_TEST_SUITE_END()\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n\r\n<|endoftext|>"} {"text":"\/\/===--- Editor.cpp - Output Of Text ----------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the text manipulation (\"editing\") interface.\n\/\/\n\/\/ Axel Naumann , 2011-05-12\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"textinput\/Editor.h\"\n\n#include \"textinput\/Callbacks.h\"\n#include \"textinput\/History.h\"\n#include \"textinput\/KeyBinding.h\"\n#include \"textinput\/TextInput.h\"\n#include \"textinput\/TextInputContext.h\"\n\n#include \n\nnamespace textinput {\n Editor::EProcessResult\n Editor::Process(Command cmd, EditorRange& R) {\n switch (cmd.GetKind()) {\n case kCKChar:\n return ProcessChar(cmd.GetChar(), R);\n case kCKMove:\n return ProcessMove(cmd.GetMoveID(), R);\n case kCKCommand:\n return ProcessCommand(cmd.GetCommandID(), R);\n case kCKControl:\n case kCKError:\n return kPRError;\n }\n return kPRError;\n }\n\n Range\n Editor::ResetText() {\n bool addToHist = !fContext->GetLine().empty()\n && !fContext->GetTextInput()->IsInputHidden()\n && fContext->GetTextInput()->IsAutoHistAddEnabled();\n if (addToHist) {\n fContext->GetHistory()->AddLine(fContext->GetLine().GetText());\n if (fReplayHistEntry != (size_t) -1) {\n \/\/ Added a line, thus renumber\n ++fReplayHistEntry;\n }\n }\n Range R(0, fContext->GetLine().length());\n fContext->GetLine().clear();\n fContext->SetCursor(0);\n ClearPasteBuf();\n fSearch.clear();\n CancelSpecialInputMode(R);\n if (fReplayHistEntry != (size_t) -1) {\n --fReplayHistEntry; \/\/ intentional overflow to -1\n fContext->SetLine(fContext->GetHistory()->GetLine(fReplayHistEntry));\n }\n return R;\n }\n\n void\n Editor::SetReverseHistSearchPrompt(Range& RDisplay) {\n std::string P(\"[bkw'\");\n SetEditorPrompt(Text(P + fSearch + \"'] \"));\n RDisplay.ExtendPromptUpdate(Range::kUpdateEditorPrompt);\n }\n\n bool\n Editor::UpdateHistSearch(EditorRange& R) {\n History* Hist = fContext->GetHistory();\n Text& Line = fContext->GetLine();\n size_t NewHistEntry = (size_t) -1;\n if (fSearch.empty()) {\n NewHistEntry = 0;\n } else {\n size_t startAt = fCurHistEntry;\n if (startAt == (size_t) -1) {\n startAt = 0;\n }\n for (size_t i = startAt, n = Hist->GetSize(); i < n; ++i) {\n if (Hist->GetLine(i).find(fSearch) != std::string::npos) {\n NewHistEntry = i;\n break;\n }\n }\n }\n if (NewHistEntry != (size_t) -1) {\n if (NewHistEntry != fCurHistEntry) {\n fCurHistEntry = NewHistEntry;\n Line = Hist->GetLine(fCurHistEntry);\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n \/\/ Resets mode, thus can't call:\n \/\/ ProcessMove(kMoveEnd, R);\n fContext->SetCursor(Line.length());\n }\n return true;\n }\n\n fCurHistEntry = (size_t) -1;\n return false;\n }\n\n void\n Editor::CancelSpecialInputMode(Range& DisplayR) {\n if (fMode == kInputMode) return;\n fContext->GetKeyBinding()->SetAllowEscModifier(false);\n SetEditorPrompt(Text());\n DisplayR.ExtendPromptUpdate(Range::kUpdateEditorPrompt);\n fMode = kInputMode;\n }\n\n Editor::EProcessResult\n Editor::ProcessChar(char C, EditorRange& R) {\n if (C < 32) return kPRError;\n\n if (fMode == kHistSearchMode) {\n fSearch += C;\n SetReverseHistSearchPrompt(R.fDisplay);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n }\n\n PushUndo();\n ClearPasteBuf();\n\n Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n\n if (fOverwrite) {\n if (Cursor < Line.length()) {\n Line[Cursor] = C;\n } else {\n Line += C;\n }\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor));\n } else {\n Line.insert(Cursor, C);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n fContext->SetCursor(Cursor + 1);\n }\n return kPRSuccess;\n }\n\n Editor::EProcessResult\n Editor::ProcessMove(EMoveID M, EditorRange &R) {\n ClearPasteBuf();\n CancelSpecialInputMode(R.fDisplay);\n\n size_t Cursor = fContext->GetCursor();\n size_t LineLen = fContext->GetLine().length();\n\n switch (M) {\n case kMoveEnd: fContext->SetCursor(LineLen); return kPRSuccess;\n case kMoveFront: fContext->SetCursor(0); return kPRSuccess;\n case kMoveRight:\n if (Cursor < LineLen) {\n fContext->SetCursor(Cursor + 1);\n return kPRSuccess;\n } else {\n return kPRError;\n }\n case kMoveLeft:\n if (Cursor > 0) {\n fContext->SetCursor(Cursor - 1);\n return kPRSuccess;\n } else {\n return kPRError;\n }\n case kMoveNextWord:\n case kMovePrevWord:\n fContext->SetCursor(FindWordBoundary(M == kMoveNextWord ? 1 : -1));\n return kPRSuccess;\n }\n return kPRError;\n }\n\n Editor::EProcessResult\n Editor::ProcessCommand(ECommandID M, EditorRange &R) {\n if (M < kCmd_END_TEXT_MODIFYING_CMDS) {\n PushUndo();\n }\n if (fMode == kHistSearchMode) {\n if (M == kCmdDelLeft) {\n if (fSearch.empty()) return kPRError;\n fSearch.erase(fSearch.length() - 1);\n SetReverseHistSearchPrompt(R.fDisplay);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n } else {\n CancelSpecialInputMode(R.fDisplay);\n return kPRError;\n }\n }\n\n Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n History* Hist = fContext->GetHistory();\n\n switch (M) {\n case kCmdIgnore:\n return kPRSuccess;\n case kCmdEnter:\n fReplayHistEntry = (size_t) -1;\n fCurHistEntry = (size_t) -1;\n CancelSpecialInputMode(R.fDisplay);\n return kPRSuccess;\n case kCmdDelLeft:\n if (Cursor == 0) return kPRError;\n fContext->SetCursor(--Cursor);\n \/\/ intentional fallthrough:\n case kCmdDel:\n if (Cursor == Line.length()) return kPRError;\n AddToPasteBuf(M == kCmdDel ? 1 : -1, Line[Cursor]);\n Line.erase(Cursor);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n return kPRSuccess;\n case kCmdCutToEnd:\n AddToPasteBuf(1, Line.GetText().c_str() + Cursor);\n Line.erase(Cursor, Line.length() - Cursor);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n return kPRSuccess;\n case kCmdCutNextWord:\n {\n size_t posWord = FindWordBoundary(1);\n AddToPasteBuf(1, Line.GetText().substr(Cursor, posWord - Cursor));\n R.fEdit.Extend(Range(Cursor, posWord));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n Line.erase(Cursor, posWord - Cursor);\n return kPRSuccess;\n }\n case kCmdCutPrevWord:\n {\n size_t posWord = FindWordBoundary(-1);\n AddToPasteBuf(-1, Line.GetText().substr(posWord, Cursor - posWord));\n R.fEdit.Extend(Range(posWord, Cursor));\n R.fDisplay.Extend(Range(posWord, Range::End()));\n Line.erase(posWord, Cursor - posWord);\n fContext->SetCursor(posWord);\n return kPRSuccess;\n }\n case kCmdToggleOverwriteMode:\n fOverwrite = !fOverwrite;\n return kPRSuccess;\n case kCmdInsertMode:\n fOverwrite = false;\n return kPRSuccess;\n case kCmdOverwiteMode:\n fOverwrite = true;\n return kPRSuccess;\n case kCmdCutToFront:\n R.fEdit.Extend(Range(0, Cursor));\n R.fDisplay.Extend(Range::AllText());\n AddToPasteBuf(-1, Line.GetText().substr(0, Cursor));\n Line.erase(0, Cursor);\n fContext->SetCursor(0);\n return kPRSuccess;\n case kCmdPaste:\n {\n size_t PasteLen = fPasteBuf.length();\n R.fEdit.Extend(Range(Cursor, PasteLen));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n Line.insert(Cursor, fPasteBuf);\n fContext->SetCursor(Cursor + PasteLen);\n ClearPasteBuf();\n return kPRSuccess;\n }\n case kCmdSwapThisAndLeftThenMoveRight:\n {\n if (Cursor < 1) return kPRError;\n R.fEdit.Extend(Range(Cursor - 1, Cursor));\n R.fDisplay.Extend(Range(Cursor - 1, Cursor));\n char tmp = Line.GetText()[Cursor];\n Line[Cursor] = Line[Cursor - 1];\n Line[Cursor] = tmp;\n \/\/ optional:\n ProcessMove(kMoveRight, R);\n return kPRSuccess;\n }\n case kCmdToUpperMoveNextWord:\n {\n if (Cursor >= Line.length()) return kPRError;\n Line[Cursor] = toupper(Line[Cursor]);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor));\n ProcessMove(kMoveNextWord, R);\n return kPRSuccess;\n }\n case kCmdWordToLower:\n case kCmdWordToUpper:\n {\n size_t posWord = FindWordBoundary(1);\n if (M == kCmdWordToUpper) {\n for (size_t i = Cursor; i < posWord; ++i) {\n Line[Cursor] = toupper(Line[Cursor]);\n }\n } else {\n for (size_t i = Cursor; i < posWord; ++i) {\n Line[Cursor] = tolower(Line[Cursor]);\n }\n }\n R.fEdit.Extend(Range(Cursor, posWord - Cursor));\n R.fDisplay.Extend(Range(Cursor, posWord - Cursor));\n fContext->SetCursor(posWord);\n return kPRSuccess;\n }\n case kCmdUndo:\n Line = fUndoBuf.back().first;\n fContext->SetCursor(fUndoBuf.back().second);\n fUndoBuf.pop_back();\n return kPRSuccess;\n case kCmdHistNewer:\n \/\/ already newest?\n if (fCurHistEntry == (size_t)-1) {\n \/\/ not a history line (\"newer\" doesn't mean anything)?\n return kPRError;\n }\n if (fCurHistEntry == 0) {\n Hist->ModifyLine(fCurHistEntry, Line.GetText().c_str());\n Line = fLineNotInHist;\n fLineNotInHist.clear();\n fCurHistEntry = (size_t)-1; \/\/ not in hist\n } else {\n --fCurHistEntry;\n Line = Hist->GetLine(fCurHistEntry);\n }\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n ProcessMove(kMoveEnd, R);\n return kPRSuccess;\n case kCmdHistOlder:\n \/\/ intentional overflow from -1 to 0:\n if (fCurHistEntry + 1 >= Hist->GetSize()) {\n return kPRError;\n }\n if (fCurHistEntry == (size_t)-1) {\n fLineNotInHist = Line.GetText();\n fCurHistEntry = 0;\n } else {\n Hist->ModifyLine(fCurHistEntry, Line.GetText().c_str());\n ++fCurHistEntry;\n }\n Line = Hist->GetLine(fCurHistEntry);\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n ProcessMove(kMoveEnd, R);\n return kPRSuccess;\n case kCmdReverseSearch:\n fMode = kHistSearchMode;\n fSearch.clear();\n SetReverseHistSearchPrompt(R.fDisplay);\n fContext->GetKeyBinding()->SetAllowEscModifier(true);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n case kCmdHistReplay:\n if (fCurHistEntry == (size_t) -1) return kPRError;\n fReplayHistEntry = fCurHistEntry;\n return kPRSuccess;\n case kCmdClearScreen:\n case kCmd_END_TEXT_MODIFYING_CMDS:\n return kPRError;\n case kCmdEsc:\n \/\/ Already done for all commands:\n \/\/CancelSpecialInputMode(R);\n return kPRSuccess;\n case kCmdComplete:\n {\n \/\/ Completion happens below current input.\n ProcessMove(kMoveEnd, R);\n std::vector completions;\n TabCompletion* tc = fContext->GetCompletion();\n if (tc) {\n bool ret = tc->Complete(Line, Cursor, R, completions);\n if (ret) {\n if (!completions.empty()) {\n fContext->GetTextInput()->DisplayInfo(completions);\n R.fDisplay.Extend(Range::AllWithPrompt());\n }\n fContext->SetCursor(Cursor);\n return kPRSuccess;\n }\n }\n return kPRError;\n }\n case kCmdWindowResize:\n fContext->GetTextInput()->HandleResize();\n return kPRSuccess;\n case kCmdHistComplete:\n \/\/ Not handled yet, todo.\n return kPRError;\n }\n return kPRError;\n }\n\n size_t\n Editor::FindWordBoundary(int Direction) {\n static const char space[] = \" \\x9\";\n\n const Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n\n if (Direction < 0 && Cursor < 2) return 0;\n size_t ret = Direction > 0 ?\n Line.GetText().find_first_of(space, Cursor + 1)\n : Line.GetText().find_last_of(space, Cursor - 2);\n\n if (ret == std::string::npos) {\n if (Direction > 0) return Line.length();\n else return 0;\n }\n\n if (Direction < 0)\n ret += 1;\n\n if (ret == std::string::npos) {\n if (Direction > 0) return Line.length();\n else return 0;\n }\n return ret;\n }\n\n void\n Editor::AddToPasteBuf(int Dir, std::string const &T) {\n if (fCutDirection == Dir) {\n if (Dir < 0) {\n fPasteBuf = T + fPasteBuf;\n } else {\n fPasteBuf += T;\n }\n } else {\n fCutDirection = Dir;\n fPasteBuf = T;\n }\n }\n\n void\n Editor::AddToPasteBuf(int Dir, char T) {\n if (fCutDirection == Dir) {\n if (Dir < 0) {\n fPasteBuf = std::string(1, T) + fPasteBuf;\n } else {\n fPasteBuf += T;\n }\n } else {\n fCutDirection = Dir;\n fPasteBuf = T;\n }\n }\n\n void\n Editor::PushUndo() {\n static const size_t MaxUndoBufSize = 100;\n if (fUndoBuf.size() > MaxUndoBufSize) {\n fUndoBuf.pop_front();\n }\n fUndoBuf.push_back(std::make_pair(fContext->GetLine(),\n fContext->GetCursor()));\n }\n\n \/\/ Pin vtables:\n TabCompletion::~TabCompletion() {}\n FunKey::~FunKey() {}\n}\nFix repeated ^R.\/\/===--- Editor.cpp - Output Of Text ----------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the text manipulation (\"editing\") interface.\n\/\/\n\/\/ Axel Naumann , 2011-05-12\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"textinput\/Editor.h\"\n\n#include \"textinput\/Callbacks.h\"\n#include \"textinput\/History.h\"\n#include \"textinput\/KeyBinding.h\"\n#include \"textinput\/TextInput.h\"\n#include \"textinput\/TextInputContext.h\"\n\n#include \n\nnamespace textinput {\n Editor::EProcessResult\n Editor::Process(Command cmd, EditorRange& R) {\n switch (cmd.GetKind()) {\n case kCKChar:\n return ProcessChar(cmd.GetChar(), R);\n case kCKMove:\n return ProcessMove(cmd.GetMoveID(), R);\n case kCKCommand:\n return ProcessCommand(cmd.GetCommandID(), R);\n case kCKControl:\n case kCKError:\n return kPRError;\n }\n return kPRError;\n }\n\n Range\n Editor::ResetText() {\n bool addToHist = !fContext->GetLine().empty()\n && !fContext->GetTextInput()->IsInputHidden()\n && fContext->GetTextInput()->IsAutoHistAddEnabled();\n if (addToHist) {\n fContext->GetHistory()->AddLine(fContext->GetLine().GetText());\n if (fReplayHistEntry != (size_t) -1) {\n \/\/ Added a line, thus renumber\n ++fReplayHistEntry;\n }\n }\n Range R(0, fContext->GetLine().length());\n fContext->GetLine().clear();\n fContext->SetCursor(0);\n ClearPasteBuf();\n fSearch.clear();\n CancelSpecialInputMode(R);\n if (fReplayHistEntry != (size_t) -1) {\n --fReplayHistEntry; \/\/ intentional overflow to -1\n fContext->SetLine(fContext->GetHistory()->GetLine(fReplayHistEntry));\n }\n return R;\n }\n\n void\n Editor::SetReverseHistSearchPrompt(Range& RDisplay) {\n std::string P(\"[bkw'\");\n SetEditorPrompt(Text(P + fSearch + \"'] \"));\n RDisplay.ExtendPromptUpdate(Range::kUpdateEditorPrompt);\n }\n\n bool\n Editor::UpdateHistSearch(EditorRange& R) {\n History* Hist = fContext->GetHistory();\n Text& Line = fContext->GetLine();\n size_t NewHistEntry = (size_t) -1;\n if (fSearch.empty()) {\n NewHistEntry = 0;\n } else {\n size_t startAt = fCurHistEntry;\n if (startAt == (size_t) -1) {\n startAt = 0;\n }\n for (size_t i = startAt, n = Hist->GetSize(); i < n; ++i) {\n if (Hist->GetLine(i).find(fSearch) != std::string::npos) {\n NewHistEntry = i;\n break;\n }\n }\n }\n if (NewHistEntry != (size_t) -1) {\n \/\/ No, even if they are unchanged: we might have\n \/\/ subsequent ^R updates triggered by faking a different\n \/\/ fCurHistEntry.\n \/\/ if (NewHistEntry != fCurHistEntry) {\n fCurHistEntry = NewHistEntry;\n Line = Hist->GetLine(fCurHistEntry);\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n \/\/ Resets mode, thus can't call:\n \/\/ ProcessMove(kMoveEnd, R);\n fContext->SetCursor(Line.length());\n return true;\n }\n\n fCurHistEntry = (size_t) -1;\n return false;\n }\n\n void\n Editor::CancelSpecialInputMode(Range& DisplayR) {\n if (fMode == kInputMode) return;\n fContext->GetKeyBinding()->SetAllowEscModifier(false);\n SetEditorPrompt(Text());\n DisplayR.ExtendPromptUpdate(Range::kUpdateEditorPrompt);\n fMode = kInputMode;\n }\n\n Editor::EProcessResult\n Editor::ProcessChar(char C, EditorRange& R) {\n if (C < 32) return kPRError;\n\n if (fMode == kHistSearchMode) {\n fSearch += C;\n SetReverseHistSearchPrompt(R.fDisplay);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n }\n\n PushUndo();\n ClearPasteBuf();\n\n Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n\n if (fOverwrite) {\n if (Cursor < Line.length()) {\n Line[Cursor] = C;\n } else {\n Line += C;\n }\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor));\n } else {\n Line.insert(Cursor, C);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n fContext->SetCursor(Cursor + 1);\n }\n return kPRSuccess;\n }\n\n Editor::EProcessResult\n Editor::ProcessMove(EMoveID M, EditorRange &R) {\n ClearPasteBuf();\n CancelSpecialInputMode(R.fDisplay);\n\n size_t Cursor = fContext->GetCursor();\n size_t LineLen = fContext->GetLine().length();\n\n switch (M) {\n case kMoveEnd: fContext->SetCursor(LineLen); return kPRSuccess;\n case kMoveFront: fContext->SetCursor(0); return kPRSuccess;\n case kMoveRight:\n if (Cursor < LineLen) {\n fContext->SetCursor(Cursor + 1);\n return kPRSuccess;\n } else {\n return kPRError;\n }\n case kMoveLeft:\n if (Cursor > 0) {\n fContext->SetCursor(Cursor - 1);\n return kPRSuccess;\n } else {\n return kPRError;\n }\n case kMoveNextWord:\n case kMovePrevWord:\n fContext->SetCursor(FindWordBoundary(M == kMoveNextWord ? 1 : -1));\n return kPRSuccess;\n }\n return kPRError;\n }\n\n Editor::EProcessResult\n Editor::ProcessCommand(ECommandID M, EditorRange &R) {\n if (M < kCmd_END_TEXT_MODIFYING_CMDS) {\n PushUndo();\n }\n if (fMode == kHistSearchMode) {\n if (M == kCmdDelLeft) {\n if (fSearch.empty()) return kPRError;\n fSearch.erase(fSearch.length() - 1);\n SetReverseHistSearchPrompt(R.fDisplay);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n } else if (M == kCmdReverseSearch) {\n \/\/ Search again. Move to older hist entry:\n size_t prevHistEntry = fCurHistEntry;\n \/\/ intentional overflow from -1 to 0:\n if (fCurHistEntry + 1 >= fContext->GetHistory()->GetSize()) {\n return kPRError;\n }\n if (fCurHistEntry == (size_t)-1) {\n fCurHistEntry = 0;\n } else {\n ++fCurHistEntry;\n }\n if (UpdateHistSearch(R)) return kPRSuccess;\n fCurHistEntry = prevHistEntry;\n return kPRError;\n } else {\n CancelSpecialInputMode(R.fDisplay);\n return kPRError;\n }\n }\n\n Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n History* Hist = fContext->GetHistory();\n\n switch (M) {\n case kCmdIgnore:\n return kPRSuccess;\n case kCmdEnter:\n fReplayHistEntry = (size_t) -1;\n fCurHistEntry = (size_t) -1;\n CancelSpecialInputMode(R.fDisplay);\n return kPRSuccess;\n case kCmdDelLeft:\n if (Cursor == 0) return kPRError;\n fContext->SetCursor(--Cursor);\n \/\/ intentional fallthrough:\n case kCmdDel:\n if (Cursor == Line.length()) return kPRError;\n AddToPasteBuf(M == kCmdDel ? 1 : -1, Line[Cursor]);\n Line.erase(Cursor);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n return kPRSuccess;\n case kCmdCutToEnd:\n AddToPasteBuf(1, Line.GetText().c_str() + Cursor);\n Line.erase(Cursor, Line.length() - Cursor);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n return kPRSuccess;\n case kCmdCutNextWord:\n {\n size_t posWord = FindWordBoundary(1);\n AddToPasteBuf(1, Line.GetText().substr(Cursor, posWord - Cursor));\n R.fEdit.Extend(Range(Cursor, posWord));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n Line.erase(Cursor, posWord - Cursor);\n return kPRSuccess;\n }\n case kCmdCutPrevWord:\n {\n size_t posWord = FindWordBoundary(-1);\n AddToPasteBuf(-1, Line.GetText().substr(posWord, Cursor - posWord));\n R.fEdit.Extend(Range(posWord, Cursor));\n R.fDisplay.Extend(Range(posWord, Range::End()));\n Line.erase(posWord, Cursor - posWord);\n fContext->SetCursor(posWord);\n return kPRSuccess;\n }\n case kCmdToggleOverwriteMode:\n fOverwrite = !fOverwrite;\n return kPRSuccess;\n case kCmdInsertMode:\n fOverwrite = false;\n return kPRSuccess;\n case kCmdOverwiteMode:\n fOverwrite = true;\n return kPRSuccess;\n case kCmdCutToFront:\n R.fEdit.Extend(Range(0, Cursor));\n R.fDisplay.Extend(Range::AllText());\n AddToPasteBuf(-1, Line.GetText().substr(0, Cursor));\n Line.erase(0, Cursor);\n fContext->SetCursor(0);\n return kPRSuccess;\n case kCmdPaste:\n {\n size_t PasteLen = fPasteBuf.length();\n R.fEdit.Extend(Range(Cursor, PasteLen));\n R.fDisplay.Extend(Range(Cursor, Range::End()));\n Line.insert(Cursor, fPasteBuf);\n fContext->SetCursor(Cursor + PasteLen);\n ClearPasteBuf();\n return kPRSuccess;\n }\n case kCmdSwapThisAndLeftThenMoveRight:\n {\n if (Cursor < 1) return kPRError;\n R.fEdit.Extend(Range(Cursor - 1, Cursor));\n R.fDisplay.Extend(Range(Cursor - 1, Cursor));\n char tmp = Line.GetText()[Cursor];\n Line[Cursor] = Line[Cursor - 1];\n Line[Cursor] = tmp;\n \/\/ optional:\n ProcessMove(kMoveRight, R);\n return kPRSuccess;\n }\n case kCmdToUpperMoveNextWord:\n {\n if (Cursor >= Line.length()) return kPRError;\n Line[Cursor] = toupper(Line[Cursor]);\n R.fEdit.Extend(Range(Cursor));\n R.fDisplay.Extend(Range(Cursor));\n ProcessMove(kMoveNextWord, R);\n return kPRSuccess;\n }\n case kCmdWordToLower:\n case kCmdWordToUpper:\n {\n size_t posWord = FindWordBoundary(1);\n if (M == kCmdWordToUpper) {\n for (size_t i = Cursor; i < posWord; ++i) {\n Line[Cursor] = toupper(Line[Cursor]);\n }\n } else {\n for (size_t i = Cursor; i < posWord; ++i) {\n Line[Cursor] = tolower(Line[Cursor]);\n }\n }\n R.fEdit.Extend(Range(Cursor, posWord - Cursor));\n R.fDisplay.Extend(Range(Cursor, posWord - Cursor));\n fContext->SetCursor(posWord);\n return kPRSuccess;\n }\n case kCmdUndo:\n Line = fUndoBuf.back().first;\n fContext->SetCursor(fUndoBuf.back().second);\n fUndoBuf.pop_back();\n return kPRSuccess;\n case kCmdHistNewer:\n \/\/ already newest?\n if (fCurHistEntry == (size_t)-1) {\n \/\/ not a history line (\"newer\" doesn't mean anything)?\n return kPRError;\n }\n if (fCurHistEntry == 0) {\n Hist->ModifyLine(fCurHistEntry, Line.GetText().c_str());\n Line = fLineNotInHist;\n fLineNotInHist.clear();\n fCurHistEntry = (size_t)-1; \/\/ not in hist\n } else {\n --fCurHistEntry;\n Line = Hist->GetLine(fCurHistEntry);\n }\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n ProcessMove(kMoveEnd, R);\n return kPRSuccess;\n case kCmdHistOlder:\n \/\/ intentional overflow from -1 to 0:\n if (fCurHistEntry + 1 >= Hist->GetSize()) {\n return kPRError;\n }\n if (fCurHistEntry == (size_t)-1) {\n fLineNotInHist = Line.GetText();\n fCurHistEntry = 0;\n } else {\n Hist->ModifyLine(fCurHistEntry, Line.GetText().c_str());\n ++fCurHistEntry;\n }\n Line = Hist->GetLine(fCurHistEntry);\n R.fEdit.Extend(Range::AllText());\n R.fDisplay.Extend(Range::AllText());\n ProcessMove(kMoveEnd, R);\n return kPRSuccess;\n case kCmdReverseSearch:\n fMode = kHistSearchMode;\n fSearch.clear();\n SetReverseHistSearchPrompt(R.fDisplay);\n fContext->GetKeyBinding()->SetAllowEscModifier(true);\n if (UpdateHistSearch(R)) return kPRSuccess;\n return kPRError;\n case kCmdHistReplay:\n if (fCurHistEntry == (size_t) -1) return kPRError;\n fReplayHistEntry = fCurHistEntry;\n return kPRSuccess;\n case kCmdClearScreen:\n case kCmd_END_TEXT_MODIFYING_CMDS:\n return kPRError;\n case kCmdEsc:\n \/\/ Already done for all commands:\n \/\/CancelSpecialInputMode(R);\n return kPRSuccess;\n case kCmdComplete:\n {\n \/\/ Completion happens below current input.\n ProcessMove(kMoveEnd, R);\n std::vector completions;\n TabCompletion* tc = fContext->GetCompletion();\n if (tc) {\n bool ret = tc->Complete(Line, Cursor, R, completions);\n if (ret) {\n if (!completions.empty()) {\n fContext->GetTextInput()->DisplayInfo(completions);\n R.fDisplay.Extend(Range::AllWithPrompt());\n }\n fContext->SetCursor(Cursor);\n return kPRSuccess;\n }\n }\n return kPRError;\n }\n case kCmdWindowResize:\n fContext->GetTextInput()->HandleResize();\n return kPRSuccess;\n case kCmdHistComplete:\n \/\/ Not handled yet, todo.\n return kPRError;\n }\n return kPRError;\n }\n\n size_t\n Editor::FindWordBoundary(int Direction) {\n static const char space[] = \" \\x9\";\n\n const Text& Line = fContext->GetLine();\n size_t Cursor = fContext->GetCursor();\n\n if (Direction < 0 && Cursor < 2) return 0;\n size_t ret = Direction > 0 ?\n Line.GetText().find_first_of(space, Cursor + 1)\n : Line.GetText().find_last_of(space, Cursor - 2);\n\n if (ret == std::string::npos) {\n if (Direction > 0) return Line.length();\n else return 0;\n }\n\n if (Direction < 0)\n ret += 1;\n\n if (ret == std::string::npos) {\n if (Direction > 0) return Line.length();\n else return 0;\n }\n return ret;\n }\n\n void\n Editor::AddToPasteBuf(int Dir, std::string const &T) {\n if (fCutDirection == Dir) {\n if (Dir < 0) {\n fPasteBuf = T + fPasteBuf;\n } else {\n fPasteBuf += T;\n }\n } else {\n fCutDirection = Dir;\n fPasteBuf = T;\n }\n }\n\n void\n Editor::AddToPasteBuf(int Dir, char T) {\n if (fCutDirection == Dir) {\n if (Dir < 0) {\n fPasteBuf = std::string(1, T) + fPasteBuf;\n } else {\n fPasteBuf += T;\n }\n } else {\n fCutDirection = Dir;\n fPasteBuf = T;\n }\n }\n\n void\n Editor::PushUndo() {\n static const size_t MaxUndoBufSize = 100;\n if (fUndoBuf.size() > MaxUndoBufSize) {\n fUndoBuf.pop_front();\n }\n fUndoBuf.push_back(std::make_pair(fContext->GetLine(),\n fContext->GetCursor()));\n }\n\n \/\/ Pin vtables:\n TabCompletion::~TabCompletion() {}\n FunKey::~FunKey() {}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: autoregisterhelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2003-11-18 16:34:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \n#include \n#include \"autoregisterhelper.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \"filehelper.hxx\"\n\nFunctionList m_Functions;\n\/\/ osl::Mutex m_Mutex;\n\nvoid SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)\n{\n \/\/ printf(\"Function register call for func(%s) successful.\\n\", _sFuncName);\n m_Functions.push_back(_pFunc);\n}\n\n\/\/ -----------------------------------------------------------------------------\nAutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions \/*, JobList * _pJobList*\/)\n :DynamicLibraryHelper(_sDLLName, _aOptions)\n{\n \/\/ try to get the entry pointer\n FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getSymbol( rtl::OUString::createFromAscii( \"registerAllTestFunction\" ) );\n\n if (pFunc)\n {\n \/\/ FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;\n \/\/ pFunc(pRegisterFunc);\n \/\/ osl::Guard aGuard(m_Mutex);\n FktRegFuncPtr pRegisterFunc = ®isterFunc;\n\n CallbackStructure aCallback;\n aCallback.aRegisterFunction = pRegisterFunc;\n\n aCallback.aCallbackDispatch = &CallbackDispatch;\n\n \/\/ special parameter for API testing\n if (_aOptions.hasOpt(\"-forward\"))\n {\n aCallback.psForward = _aOptions.getOpt(\"-forward\").getStr();\n }\n\n \/\/ aCallback.pJobList = _pJobList;\n\n \/\/# aCallback.aStartTest = &TestResult_startTest;\n \/\/# aCallback.aAddFailure = &TestResult_addFailure;\n \/\/# aCallback.aAddError = &TestResult_addError;\n \/\/# aCallback.aEndTest = &TestResult_endTest;\n \/\/# aCallback.aShouldStop = &TestResult_shouldStop;\n \/\/# aCallback.aAddInfo = &TestResult_addInfo;\n \/\/# aCallback.aEnterNode = &TestResult_enterNode;\n \/\/# aCallback.aLeaveNode = &TestResult_leaveNode;\n\n aCallback.nBits = FileHelper::createFlags(_aOptions);\n\n pFunc(&aCallback);\n\n if (aCallback.nMagic == aCallback.nMagic2)\n {\n \/\/ ok internal simple test done.\n m_aFunctionList = m_Functions;\n }\n else\n {\n \/\/ ERROR, the function seams not to be what we thing it's to be.\n fprintf(stderr, \"error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\\nPlease recompile your test libraries.\");\n exit(-1);\n }\n }\n else\n {\n fprintf(stderr, \"warning: Function 'registerAllTestFunction' not found.\\n\");\n fprintf(stderr, \"If you think, you are right, build testshl2 completly new.\\n\");\n }\n}\n\nvoid AutomaticRegisterHelper::CallAll(hTestResult _hResult) const\n{\n for (FunctionList::const_iterator it = m_aFunctionList.begin();\n it != m_aFunctionList.end();\n ++it)\n {\n FktPtr pFunc = *it;\n if (pFunc)\n {\n (pFunc)(_hResult);\n }\n }\n}\n\nINTEGRATION: CWS qadev19 (1.5.36); FILE MERGED 2004\/09\/22 08:12:35 lla 1.5.36.1: #i34302# testshl2 will fail, if library can't load\/*************************************************************************\n *\n * $RCSfile: autoregisterhelper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-02 10:25:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \n#include \n#include \"autoregisterhelper.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \"filehelper.hxx\"\n\nFunctionList m_Functions;\n\/\/ osl::Mutex m_Mutex;\n\nvoid SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)\n{\n \/\/ printf(\"Function register call for func(%s) successful.\\n\", _sFuncName);\n m_Functions.push_back(_pFunc);\n}\n\n\/\/ -----------------------------------------------------------------------------\nAutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions \/*, JobList * _pJobList*\/)\n :DynamicLibraryHelper(_sDLLName, _aOptions),\n m_bLoadLibraryOK(false)\n{\n \/\/ try to get the entry pointer\n FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getSymbol( rtl::OUString::createFromAscii( \"registerAllTestFunction\" ) );\n\n if (pFunc)\n {\n m_bLoadLibraryOK = true;\n \/\/ FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;\n \/\/ pFunc(pRegisterFunc);\n \/\/ osl::Guard aGuard(m_Mutex);\n FktRegFuncPtr pRegisterFunc = ®isterFunc;\n\n CallbackStructure aCallback;\n aCallback.aRegisterFunction = pRegisterFunc;\n\n aCallback.aCallbackDispatch = &CallbackDispatch;\n\n \/\/ special parameter for API testing\n if (_aOptions.hasOpt(\"-forward\"))\n {\n aCallback.psForward = _aOptions.getOpt(\"-forward\").getStr();\n }\n\n \/\/ aCallback.pJobList = _pJobList;\n\n \/\/# aCallback.aStartTest = &TestResult_startTest;\n \/\/# aCallback.aAddFailure = &TestResult_addFailure;\n \/\/# aCallback.aAddError = &TestResult_addError;\n \/\/# aCallback.aEndTest = &TestResult_endTest;\n \/\/# aCallback.aShouldStop = &TestResult_shouldStop;\n \/\/# aCallback.aAddInfo = &TestResult_addInfo;\n \/\/# aCallback.aEnterNode = &TestResult_enterNode;\n \/\/# aCallback.aLeaveNode = &TestResult_leaveNode;\n\n aCallback.nBits = FileHelper::createFlags(_aOptions);\n\n pFunc(&aCallback);\n\n if (aCallback.nMagic == aCallback.nMagic2)\n {\n \/\/ ok internal simple test done.\n m_aFunctionList = m_Functions;\n }\n else\n {\n \/\/ ERROR, the function seams not to be what we thing it's to be.\n fprintf(stderr, \"error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\\nPlease recompile your test libraries.\");\n exit(-1);\n }\n }\n else\n {\n fprintf(stderr, \"warning: Function 'registerAllTestFunction' not found.\\n\");\n fprintf(stderr, \"If you think, you are right, build testshl2 completly new.\\n\");\n }\n}\n\nvoid AutomaticRegisterHelper::CallAll(hTestResult _hResult) const\n{\n \/\/ can't load the module, break the tests.\n if (m_bLoadLibraryOK == false)\n {\n return;\n }\n\n for (FunctionList::const_iterator it = m_aFunctionList.begin();\n it != m_aFunctionList.end();\n ++it)\n {\n FktPtr pFunc = *it;\n if (pFunc)\n {\n (pFunc)(_hResult);\n }\n }\n}\n\n<|endoftext|>"} {"text":"#include \"TestGeneratedProperty.h\"\n#include \"PEG\/test.peg.h\"\n#include \"PEG\/test2.peg.h\"\n#include \n\nvoid TestGeneratedProperty::test1()\n{\n QtnPropertySetTest1 p;\n QVERIFY(p.name() == \"Test1\");\n\n p.a = 2;\n QVERIFY(p.a == 2);\n p.a = 15;\n QVERIFY(p.a.maxValue() == 10);\n QVERIFY(p.a == 2);\n\n p.a.incrementValue();\n QVERIFY(p.a == 1);\n QVERIFY(p.a > 0 && p.a >= 0 && p.a < 2 && p.a <= 1 && p.a != 3);\n\n QVERIFY(p.text == \"#^{};\");\n QVERIFY(p.text.description() == \"defrf\\\"sde\\\"\"\"deerf3rfderf r g\\r\\nreg r{}dfrgergfwrewre\");\n\n p.text = tr(\"new value\");\n QVERIFY(p.text == \"new value\");\n}\n\nvoid TestGeneratedProperty::test2()\n{\n QtnPropertySetTest3 n(this);\n n.setName(\"SS\");\n\n QVERIFY(n.name() == \"SS\");\n QVERIFY(n.yy.rect == QRect(10, 10, 10, 10));\n QVERIFY(!n.s.a);\n n.s.a = true;\n QVERIFY(n.s.a);\n QVERIFY(n.yy.rect == QRect(1, 1, 1, 1));\n\n QVERIFY(n.ww == n.bc && n.bc == false);\n n.ww = true;\n QVERIFY(n.ww == n.bc && n.ww == true);\n n.bc = false;\n QVERIFY(n.bc);\n n.m_s = false;\n n.bc = true;\n QVERIFY(n.m_s);\n}\n\nvoid TestGeneratedProperty::testAllPropertyTypes()\n{\n QtnPropertySetAllPropertyTypes p;\n\n QVERIFY(p.ep == COLOR::BLUE);\n p.ep = COLOR::RED;\n switch (p.ep)\n {\n case COLOR::BLUE:\n case COLOR::YELLOW:\n QFAIL(\"ep expected as COLOR::RED\");\n break;\n\n case COLOR::RED:\n break;\n\n default:\n QFAIL(\"ep expected as COLOR::RED\");\n }\n}\n\nvoid TestGeneratedProperty::testLoadSave()\n{\n {\n QtnPropertySetAllPropertyTypes p;\n QtnPropertySetA p2;\n\n {\n QtnPropertySet allProperties(nullptr);\n allProperties.addChildProperty(&p, false);\n allProperties.addChildProperty(&p2, false);\n\n QByteArray data;\n\n {\n QDataStream s(&data, QIODevice::WriteOnly);\n QVERIFY(allProperties.save(s));\n printf(\"QDataStream: %d, %d, %d\\n\", s.byteOrder(), s.floatingPointPrecision(), s.version());\n }\n\n printf(data.toBase64().data());\n QCOMPARE(data.toBase64(), QByteArray(\"GYQBAAADngABAAAAAAAAAAABAAAADRmEAQAAA1QAAQAAAAAAAAAAAQAAAA4ZhAEAAAALAAEAAAAIAAAAAAAAAAAPGYQBAAAACwABAAAACAAAAAABAAAAEBmEAQAAAA4AAQAAAAgAAAAAAAAAAAAAABEZhAEAAAAOAAEAAAAIAAAAAAAAAAwAAAASGYQBAAAADgABAAAACAAAAAAAAAAAAAAAExmEAQAAAA4AAQAAAAgAAAAAAAAACQAAABQZhAEAAAASAAEAAAAIAAAAAAAAAAAAAAAAAAAAFRmEAQAAABIAAQAAAAgAAAAAP8mZmaAAAAAAAAAWGYQBAAAAEgABAAAACAAAAAAAAAAAAAAAAAAAABcZhAEAAAASAAEAAAAIAAAAAEBAMzMzMzMzAAAAGBmEAQAAAA4AAQAAAAgAAAAA\/\/\/\/\/wAAABkZhAEAAAAWAAEAAAAIAAAAAAAAAAgAbgBhAG0AZQAAABoZhAEAAAAaAAEAAAAIAAAAAAAAAAAAAAAA\/\/\/\/\/\/\/\/\/\/8AAAAbGYQBAAAAGgABAAAACAAAAAAAAAAKAAAACgAAABMAAAATAAAAHBmEAQAAABIAAQAAAAgAAAAAAAAAAAAAAAAAAAAdGYQBAAAAEgABAAAACAAAAAAAAAAJAAAAAgAAAB4ZhAEAAAASAAEAAAAIAAAAAP\/\/\/\/\/\/\/\/\/\/AAAAHxmEAQAAABIAAQAAAAgAAAAAAAAAIQAAABUAAAAgGYQBAAAADgABAAAACAAAAAAAAAAWAAAAIRmEAQAAAA4AAQAAAAgAAAAAAAAACgAAACIZhAEAAAAOAAEAAAAIAAAAAAAAAAUAAAAjGYQBAAAADgABAAAACAAAAAAAAAAFAAAAJBmEAQAAABUAAQAAAAgAAAAAAf\/\/AAAAAP\/\/AAAAAAAlGYQBAAAAFQABAAAACAAAAAAB\/\/\/\/\/wAAAAAAAAAAACYZhAEAAAA\/AAEAAAAIAAAAAAAAAA4AQwBvAHUAcgBpAGUAcv\/\/\/\/9AJAAAAAAAAP\/\/\/\/8FAAEAMhAAZAEAAAAAAAAAAAAAAAAAJxmEAQAAADsAAQAAAAgAAAAAAAAACgBBAHIAaQBhAGz\/\/\/\/\/QDMAAAAAAAD\/\/\/\/\/BQABADIQAGQBAAAAAAAAAAAAAAAAACgZhAEAAAAKAAEAAAAIAAAAAP\/\/\/\/8AAAAyGYQBAAAAJQABAAAAAAAAAAABAAAAMxmEAQAAAAsAAQAAAAgAAAAAAf\/\/\/\/\/\/\/\/\/\/\"));\n \/\/QCOMPARE(data.size(), 933);\n\n {\n QDataStream s(&data, QIODevice::ReadOnly);\n QVERIFY(allProperties.load(s));\n }\n\n QString result;\n QVERIFY(allProperties.toStr(result));\n\n QCOMPARE(result.size(), 925);\n }\n }\n}\n\nvoid TestGeneratedProperty::testJson()\n{\n QtnPropertySetAllPropertyTypes p;\n\n QJsonObject o;\n QVERIFY(p.toJson(o));\n\n QJsonDocument d(o);\n auto res = d.toJson();\n QCOMPARE(res.size(), 1321);\n res = d.toJson(QJsonDocument::Compact);\n QCOMPARE(res.size(), 752);\n\n QVERIFY(p.fromJson(o));\n}\nupdated tests 5#include \"TestGeneratedProperty.h\"\n#include \"PEG\/test.peg.h\"\n#include \"PEG\/test2.peg.h\"\n#include \n\nvoid TestGeneratedProperty::test1()\n{\n QtnPropertySetTest1 p;\n QVERIFY(p.name() == \"Test1\");\n\n p.a = 2;\n QVERIFY(p.a == 2);\n p.a = 15;\n QVERIFY(p.a.maxValue() == 10);\n QVERIFY(p.a == 2);\n\n p.a.incrementValue();\n QVERIFY(p.a == 1);\n QVERIFY(p.a > 0 && p.a >= 0 && p.a < 2 && p.a <= 1 && p.a != 3);\n\n QVERIFY(p.text == \"#^{};\");\n QVERIFY(p.text.description() == \"defrf\\\"sde\\\"\"\"deerf3rfderf r g\\r\\nreg r{}dfrgergfwrewre\");\n\n p.text = tr(\"new value\");\n QVERIFY(p.text == \"new value\");\n}\n\nvoid TestGeneratedProperty::test2()\n{\n QtnPropertySetTest3 n(this);\n n.setName(\"SS\");\n\n QVERIFY(n.name() == \"SS\");\n QVERIFY(n.yy.rect == QRect(10, 10, 10, 10));\n QVERIFY(!n.s.a);\n n.s.a = true;\n QVERIFY(n.s.a);\n QVERIFY(n.yy.rect == QRect(1, 1, 1, 1));\n\n QVERIFY(n.ww == n.bc && n.bc == false);\n n.ww = true;\n QVERIFY(n.ww == n.bc && n.ww == true);\n n.bc = false;\n QVERIFY(n.bc);\n n.m_s = false;\n n.bc = true;\n QVERIFY(n.m_s);\n}\n\nvoid TestGeneratedProperty::testAllPropertyTypes()\n{\n QtnPropertySetAllPropertyTypes p;\n\n QVERIFY(p.ep == COLOR::BLUE);\n p.ep = COLOR::RED;\n switch (p.ep)\n {\n case COLOR::BLUE:\n case COLOR::YELLOW:\n QFAIL(\"ep expected as COLOR::RED\");\n break;\n\n case COLOR::RED:\n break;\n\n default:\n QFAIL(\"ep expected as COLOR::RED\");\n }\n}\n\nvoid TestGeneratedProperty::testLoadSave()\n{\n {\n QtnPropertySetAllPropertyTypes p;\n QtnPropertySetA p2;\n\n {\n QtnPropertySet allProperties(nullptr);\n allProperties.addChildProperty(&p, false);\n allProperties.addChildProperty(&p2, false);\n\n QByteArray data;\n\n {\n QDataStream s(&data, QIODevice::WriteOnly);\n s.setVersion(10);\n QVERIFY(allProperties.save(s));\n \/\/printf(\"QDataStream: %d\\n\", s.version());\n }\n\n \/\/printf(data.toBase64().data());\n \/\/QCOMPARE(data.toBase64(), QByteArray(\"GYQBAAADngABAAAAAAAAAAABAAAADRmEAQAAA1QAAQAAAAAAAAAAAQAAAA4ZhAEAAAALAAEAAAAIAAAAAAAAAAAPGYQBAAAACwABAAAACAAAAAABAAAAEBmEAQAAAA4AAQAAAAgAAAAAAAAAAAAAABEZhAEAAAAOAAEAAAAIAAAAAAAAAAwAAAASGYQBAAAADgABAAAACAAAAAAAAAAAAAAAExmEAQAAAA4AAQAAAAgAAAAAAAAACQAAABQZhAEAAAASAAEAAAAIAAAAAAAAAAAAAAAAAAAAFRmEAQAAABIAAQAAAAgAAAAAP8mZmaAAAAAAAAAWGYQBAAAAEgABAAAACAAAAAAAAAAAAAAAAAAAABcZhAEAAAASAAEAAAAIAAAAAEBAMzMzMzMzAAAAGBmEAQAAAA4AAQAAAAgAAAAA\/\/\/\/\/wAAABkZhAEAAAAWAAEAAAAIAAAAAAAAAAgAbgBhAG0AZQAAABoZhAEAAAAaAAEAAAAIAAAAAAAAAAAAAAAA\/\/\/\/\/\/\/\/\/\/8AAAAbGYQBAAAAGgABAAAACAAAAAAAAAAKAAAACgAAABMAAAATAAAAHBmEAQAAABIAAQAAAAgAAAAAAAAAAAAAAAAAAAAdGYQBAAAAEgABAAAACAAAAAAAAAAJAAAAAgAAAB4ZhAEAAAASAAEAAAAIAAAAAP\/\/\/\/\/\/\/\/\/\/AAAAHxmEAQAAABIAAQAAAAgAAAAAAAAAIQAAABUAAAAgGYQBAAAADgABAAAACAAAAAAAAAAWAAAAIRmEAQAAAA4AAQAAAAgAAAAAAAAACgAAACIZhAEAAAAOAAEAAAAIAAAAAAAAAAUAAAAjGYQBAAAADgABAAAACAAAAAAAAAAFAAAAJBmEAQAAABUAAQAAAAgAAAAAAf\/\/AAAAAP\/\/AAAAAAAlGYQBAAAAFQABAAAACAAAAAAB\/\/\/\/\/wAAAAAAAAAAACYZhAEAAAA\/AAEAAAAIAAAAAAAAAA4AQwBvAHUAcgBpAGUAcv\/\/\/\/9AJAAAAAAAAP\/\/\/\/8FAAEAMhAAZAEAAAAAAAAAAAAAAAAAJxmEAQAAADsAAQAAAAgAAAAAAAAACgBBAHIAaQBhAGz\/\/\/\/\/QDMAAAAAAAD\/\/\/\/\/BQABADIQAGQBAAAAAAAAAAAAAAAAACgZhAEAAAAKAAEAAAAIAAAAAP\/\/\/\/8AAAAyGYQBAAAAJQABAAAAAAAAAAABAAAAMxmEAQAAAAsAAQAAAAgAAAAAAf\/\/\/\/\/\/\/\/\/\/\"));\n \/\/QCOMPARE(data.size(), 933);\n\n {\n QDataStream s(&data, QIODevice::ReadOnly);\n QVERIFY(allProperties.load(s));\n }\n\n QString result;\n QVERIFY(allProperties.toStr(result));\n\n QCOMPARE(result.size(), 925);\n }\n }\n}\n\nvoid TestGeneratedProperty::testJson()\n{\n QtnPropertySetAllPropertyTypes p;\n\n QJsonObject o;\n QVERIFY(p.toJson(o));\n\n QJsonDocument d(o);\n auto res = d.toJson();\n QCOMPARE(res.size(), 1321);\n res = d.toJson(QJsonDocument::Compact);\n QCOMPARE(res.size(), 752);\n\n QVERIFY(p.fromJson(o));\n}\n<|endoftext|>"} {"text":"\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n\n#include \"config.h\"\n#include \"include\/types.h\"\n#include \"armor.h\"\n#include \"include\/Spinlock.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace ceph {\n\nSpinlock buffer_lock(\"buffer_lock\");\natomic_t buffer_total_alloc;\n\nvoid buffer::list::encode_base64(buffer::list& o)\n{\n bufferptr bp(length() * 4 \/ 3 + 3);\n int l = ceph_armor(bp.c_str(), c_str(), c_str() + length());\n bp.set_length(l);\n o.push_back(bp);\n}\n\nvoid buffer::list::decode_base64(buffer::list& e)\n{\n bufferptr bp(e.length() * 3 \/ 4 + 4);\n int l = ceph_unarmor(bp.c_str(), e.c_str(), e.c_str() + e.length());\n assert(l <= (int)bp.length());\n bp.set_length(l);\n push_back(bp);\n}\n\nvoid buffer::list::rebuild_page_aligned()\n{\n std::list::iterator p = _buffers.begin();\n while (p != _buffers.end()) {\n \/\/ keep anything that's already page sized+aligned\n if (p->is_page_aligned() && p->is_n_page_sized()) {\n \/*generic_dout(0) << \" segment \" << (void*)p->c_str()\n\t\t << \" offset \" << ((unsigned long)p->c_str() & ~PAGE_MASK)\n\t\t << \" length \" << p->length()\n\t\t << \" \" << (p->length() & ~PAGE_MASK) << \" ok\" << dendl;\n *\/\n p++;\n continue;\n }\n \n \/\/ consolidate unaligned items, until we get something that is sized+aligned\n list unaligned;\n unsigned offset = 0;\n do {\n \/*generic_dout(0) << \" segment \" << (void*)p->c_str()\n\t\t << \" offset \" << ((unsigned long)p->c_str() & ~PAGE_MASK)\n\t\t << \" length \" << p->length() << \" \" << (p->length() & ~PAGE_MASK)\n\t\t << \" overall offset \" << offset << \" \" << (offset & ~PAGE_MASK)\n\t\t << \" not ok\" << dendl;\n *\/\n offset += p->length();\n unaligned.push_back(*p);\n _buffers.erase(p++);\n } while (p != _buffers.end() &&\n\t (!p->is_page_aligned() ||\n\t !p->is_n_page_sized() ||\n\t (offset & ~PAGE_MASK)));\n unaligned.rebuild();\n _buffers.insert(p, unaligned._buffers.front());\n }\n}\n \n\nint buffer::list::read_file(const char *fn, bool silent)\n{\n struct stat st;\n int fd = ::open(fn, O_RDONLY);\n if (fd < 0) {\n if (!silent) {\n char buf[80];\n cerr << \"can't open \" << fn << \": \" << strerror_r(errno, buf, sizeof(buf)) << std::endl;\n }\n return -errno;\n }\n ::fstat(fd, &st);\n int s = ROUND_UP_TO(st.st_size, PAGE_SIZE);\n bufferptr bp = buffer::create_page_aligned(s);\n int left = st.st_size;\n int got = 0;\n while (left > 0) {\n int r = ::read(fd, (void *)(bp.c_str() + got), left);\n if (r <= 0)\n break;\n got += r;\n left -= r;\n }\n ::close(fd);\n bp.set_length(got);\n append(bp);\n return 0;\n}\n\nint buffer::list::write_file(const char *fn, int mode)\n{\n int fd = ::open(fn, O_WRONLY|O_CREAT|O_TRUNC, mode);\n if (fd < 0) {\n char buf[80];\n cerr << \"can't write \" << fn << \": \" << strerror_r(errno, buf, sizeof(buf)) << std::endl;\n return -errno;\n }\n int err = write_fd(fd);\n ::close(fd);\n return err;\n}\n\nint buffer::list::write_fd(int fd)\n{\n \/\/ write buffer piecewise\n if (false) {\n for (std::list::const_iterator it = _buffers.begin(); \n\t it != _buffers.end(); \n\t it++) {\n int left = it->length();\n if (!left)\n continue;\n const char *c = it->c_str();\n while (left > 0) {\n\tint r = ::write(fd, c, left);\n\tif (r < 0)\n\t return -errno;\n\tc += r;\n\tleft -= r;\n }\n }\n return 0;\n }\n\n \/\/ use writev!\n iovec iov[IOV_MAX];\n int iovlen = 0;\n ssize_t bytes = 0;\n\n std::list::const_iterator p = _buffers.begin(); \n while (true) {\n if (p->length() > 0) {\n iov[iovlen].iov_base = (void *)p->c_str();\n iov[iovlen].iov_len = p->length();\n bytes += p->length();\n iovlen++;\n }\n p++;\n\n if (iovlen == IOV_MAX-1 ||\n\tp == _buffers.end()) {\n iovec *start = iov;\n int num = iovlen;\n ssize_t wrote;\n retry:\n wrote = ::writev(fd, start, num);\n if (wrote < 0)\n\treturn -errno;\n if (wrote < bytes) {\n\t\/\/ partial write, recover!\n\twhile ((size_t)wrote >= start[0].iov_len) {\n\t wrote -= start[0].iov_len;\n\t bytes -= start[0].iov_len;\n\t start++;\n\t num--;\n\t}\n\tif (wrote > 0) {\n\t start[0].iov_len -= wrote;\n\t start[0].iov_base = (char *)start[0].iov_base + wrote;\n\t bytes -= wrote;\n\t}\n\tgoto retry;\n }\n }\n if (p == _buffers.end())\n break;\n }\n return 0;\n}\n\n\nvoid buffer::list::hexdump(std::ostream &out) const\n{\n out.setf(std::ios::right);\n out.fill('0');\n\n unsigned per = 16;\n\n for (unsigned o=0; obuffer: handle write_fd() on empty bufferlist\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n\n#include \"config.h\"\n#include \"include\/types.h\"\n#include \"armor.h\"\n#include \"include\/Spinlock.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace ceph {\n\nSpinlock buffer_lock(\"buffer_lock\");\natomic_t buffer_total_alloc;\n\nvoid buffer::list::encode_base64(buffer::list& o)\n{\n bufferptr bp(length() * 4 \/ 3 + 3);\n int l = ceph_armor(bp.c_str(), c_str(), c_str() + length());\n bp.set_length(l);\n o.push_back(bp);\n}\n\nvoid buffer::list::decode_base64(buffer::list& e)\n{\n bufferptr bp(e.length() * 3 \/ 4 + 4);\n int l = ceph_unarmor(bp.c_str(), e.c_str(), e.c_str() + e.length());\n assert(l <= (int)bp.length());\n bp.set_length(l);\n push_back(bp);\n}\n\nvoid buffer::list::rebuild_page_aligned()\n{\n std::list::iterator p = _buffers.begin();\n while (p != _buffers.end()) {\n \/\/ keep anything that's already page sized+aligned\n if (p->is_page_aligned() && p->is_n_page_sized()) {\n \/*generic_dout(0) << \" segment \" << (void*)p->c_str()\n\t\t << \" offset \" << ((unsigned long)p->c_str() & ~PAGE_MASK)\n\t\t << \" length \" << p->length()\n\t\t << \" \" << (p->length() & ~PAGE_MASK) << \" ok\" << dendl;\n *\/\n p++;\n continue;\n }\n \n \/\/ consolidate unaligned items, until we get something that is sized+aligned\n list unaligned;\n unsigned offset = 0;\n do {\n \/*generic_dout(0) << \" segment \" << (void*)p->c_str()\n\t\t << \" offset \" << ((unsigned long)p->c_str() & ~PAGE_MASK)\n\t\t << \" length \" << p->length() << \" \" << (p->length() & ~PAGE_MASK)\n\t\t << \" overall offset \" << offset << \" \" << (offset & ~PAGE_MASK)\n\t\t << \" not ok\" << dendl;\n *\/\n offset += p->length();\n unaligned.push_back(*p);\n _buffers.erase(p++);\n } while (p != _buffers.end() &&\n\t (!p->is_page_aligned() ||\n\t !p->is_n_page_sized() ||\n\t (offset & ~PAGE_MASK)));\n unaligned.rebuild();\n _buffers.insert(p, unaligned._buffers.front());\n }\n}\n \n\nint buffer::list::read_file(const char *fn, bool silent)\n{\n struct stat st;\n int fd = ::open(fn, O_RDONLY);\n if (fd < 0) {\n if (!silent) {\n char buf[80];\n cerr << \"can't open \" << fn << \": \" << strerror_r(errno, buf, sizeof(buf)) << std::endl;\n }\n return -errno;\n }\n ::fstat(fd, &st);\n int s = ROUND_UP_TO(st.st_size, PAGE_SIZE);\n bufferptr bp = buffer::create_page_aligned(s);\n int left = st.st_size;\n int got = 0;\n while (left > 0) {\n int r = ::read(fd, (void *)(bp.c_str() + got), left);\n if (r <= 0)\n break;\n got += r;\n left -= r;\n }\n ::close(fd);\n bp.set_length(got);\n append(bp);\n return 0;\n}\n\nint buffer::list::write_file(const char *fn, int mode)\n{\n int fd = ::open(fn, O_WRONLY|O_CREAT|O_TRUNC, mode);\n if (fd < 0) {\n char buf[80];\n cerr << \"can't write \" << fn << \": \" << strerror_r(errno, buf, sizeof(buf)) << std::endl;\n return -errno;\n }\n int err = write_fd(fd);\n ::close(fd);\n return err;\n}\n\nint buffer::list::write_fd(int fd)\n{\n \/\/ write buffer piecewise\n if (false) {\n for (std::list::const_iterator it = _buffers.begin(); \n\t it != _buffers.end(); \n\t it++) {\n int left = it->length();\n if (!left)\n continue;\n const char *c = it->c_str();\n while (left > 0) {\n\tint r = ::write(fd, c, left);\n\tif (r < 0)\n\t return -errno;\n\tc += r;\n\tleft -= r;\n }\n }\n return 0;\n }\n\n \/\/ use writev!\n iovec iov[IOV_MAX];\n int iovlen = 0;\n ssize_t bytes = 0;\n\n std::list::const_iterator p = _buffers.begin(); \n while (p != _buffers.end()) {\n if (p->length() > 0) {\n iov[iovlen].iov_base = (void *)p->c_str();\n iov[iovlen].iov_len = p->length();\n bytes += p->length();\n iovlen++;\n }\n p++;\n\n if (iovlen == IOV_MAX-1 ||\n\tp == _buffers.end()) {\n iovec *start = iov;\n int num = iovlen;\n ssize_t wrote;\n retry:\n wrote = ::writev(fd, start, num);\n if (wrote < 0)\n\treturn -errno;\n if (wrote < bytes) {\n\t\/\/ partial write, recover!\n\twhile ((size_t)wrote >= start[0].iov_len) {\n\t wrote -= start[0].iov_len;\n\t bytes -= start[0].iov_len;\n\t start++;\n\t num--;\n\t}\n\tif (wrote > 0) {\n\t start[0].iov_len -= wrote;\n\t start[0].iov_base = (char *)start[0].iov_base + wrote;\n\t bytes -= wrote;\n\t}\n\tgoto retry;\n }\n }\n }\n return 0;\n}\n\n\nvoid buffer::list::hexdump(std::ostream &out) const\n{\n out.setf(std::ios::right);\n out.fill('0');\n\n unsigned per = 16;\n\n for (unsigned o=0; o"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mc\/mc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file mc.H\n\/\/\/ @brief Subroutines to manipulate the memory controller\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_MC_H_\n#define _MSS_MC_H_\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace mss\n{\n\n\/\/ I have a dream that the xlate code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the MC\n\/\/\/ @tparam T, fapi2::TargetType representing the MC\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mcTraits;\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Centaur controller\n\/\/\/\ntemplate<>\nclass mcTraits\n{\n};\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus controller\n\/\/\/\ntemplate<>\nclass mcTraits\n{\n public:\n enum\n {\n SLOT0_VALID = MCS_PORT02_MCP0XLT0_SLOT0_VALID,\n SLOT0_ROW15_VALID = MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID,\n SLOT0_M1_VALID = MCS_PORT02_MCP0XLT0_SLOT0_M1_VALID,\n M1_BIT_MAP = MCS_PORT02_MCP0XLT0_M1_BIT_MAP,\n M1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN,\n D_BIT_MAP = MCS_PORT02_MCP0XLT0_D_BIT_MAP,\n D_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN,\n R15_BIT_MAP = MCS_PORT02_MCP0XLT0_R15_BIT_MAP,\n R15_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN,\n COL4_BIT_MAP = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,\n COL4_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN,\n COL5_BIT_MAP = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,\n COL5_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN,\n COL6_BIT_MAP = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,\n COL6_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN,\n COL7_BIT_MAP = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,\n COL7_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN,\n COL8_BIT_MAP = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,\n COL8_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN,\n COL9_BIT_MAP = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,\n COL9_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN,\n BANK0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,\n BANK0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN,\n BANK1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,\n BANK1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN,\n BANK_GROUP0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,\n BANK_GROUP0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN,\n BANK_GROUP1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,\n BANK_GROUP1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN,\n };\n\n};\n\n\/\/ Why two enums? Two reasons. First, we need these to be contiguous, and\n\/\/ we can't always guarentee the symbols will be generated as such. Second,\n\/\/ we want to be 0'based so that we can use a static array as a table and\n\/\/ it's probably not possible for the symbols to be 0'based.\nenum\n{\n THIS_ENTRY_VALID = 0,\n VALUE_OF_D_BIT_INDEX = 1,\n GB12_ENABLE_INDEX = 2,\n MASTER_BIT_0_VALID_INDEX = 3,\n MASTER_BIT_1_VALID_INDEX = 4,\n SLAVE_BIT_0_VALID_INDEX = 5,\n SLAVE_BIT_1_VALID_INDEX = 6,\n SLAVE_BIT_2_VALID_INDEX = 7,\n ROW_BIT_15_VALID_INDEX = 8,\n ROW_BIT_16_VALID_INDEX = 9,\n ROW_BIT_17_VALID_INDEX = 10,\n BANK_BIT_2_VALID_INDEX = 11,\n DIMM_BIT_INDEX = 12,\n MASTER_BIT_0_INDEX = 13,\n MASTER_BIT_1_INDEX = 14,\n SLAVE_BIT_0_INDEX = 15,\n SLAVE_BIT_1_INDEX = 16,\n SLAVE_BIT_2_INDEX = 17,\n ROW_17_INDEX = 18,\n ROW_16_INDEX = 19,\n COLUMN_4_INDEX = 20,\n COLUMN_5_INDEX = 21,\n COLUMN_6_INDEX = 22,\n COLUMN_7_INDEX = 23,\n COLUMN_8_INDEX = 24,\n COLUMN_9_INDEX = 25,\n BANK_0_INDEX = 26,\n BANK_1_INDEX = 27,\n BANK_2_INDEX = 28,\n BANK_GROUP_0_BIT_INDEX = 29,\n BANK_GROUP_1_BIT_INDEX = 30,\n MAX_TRANSLATIONS = 31,\n};\n\n\/\/\/\n\/\/\/ @class mss::mc\n\/\/\/ @brief The memory controller class\n\/\/\/ @tparam T the fapi2::TargetType of the controller\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mc\n{\n\n public:\n \/\/\/\n \/\/\/ @brief Perform initializations for the MC\n \/\/\/ @tparam T the fapi2::TargetType\n \/\/\/ @param[in] i_target the target which has the MCs to initialize\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode scominit(const fapi2::Target& i_target);\n\n \/\/\/\n \/\/\/ @brief Perform initializations of the MC translation\n \/\/\/ @tparam P the fapi2::TargetType of the port\n \/\/\/ @tparam TT the typename of the traits\n \/\/\/ @param[in] i_target the target which has the MCA to map\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n template< fapi2::TargetType P, typename TT = mcTraits >\n fapi2::ReturnCode setup_xlate_map(const fapi2::Target

& i_target);\n\n};\n\n}\n\n#endif\nImplementing thermal_init\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mc\/mc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file mc.H\n\/\/\/ @brief Subroutines to manipulate the memory controller\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_MC_H_\n#define _MSS_MC_H_\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace mss\n{\n\n\/\/ I have a dream that the xlate code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the MC\n\/\/\/ @tparam T, fapi2::TargetType representing the MC\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mcTraits;\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Centaur controller\n\/\/\/\ntemplate<>\nclass mcTraits\n{\n};\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus controller\n\/\/\/\ntemplate<>\nclass mcTraits\n{\n public:\n enum\n {\n SLOT0_VALID = MCS_PORT02_MCP0XLT0_SLOT0_VALID,\n SLOT0_ROW15_VALID = MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID,\n SLOT0_M1_VALID = MCS_PORT02_MCP0XLT0_SLOT0_M1_VALID,\n M1_BIT_MAP = MCS_PORT02_MCP0XLT0_M1_BIT_MAP,\n M1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN,\n D_BIT_MAP = MCS_PORT02_MCP0XLT0_D_BIT_MAP,\n D_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN,\n R15_BIT_MAP = MCS_PORT02_MCP0XLT0_R15_BIT_MAP,\n R15_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN,\n COL4_BIT_MAP = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,\n COL4_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN,\n COL5_BIT_MAP = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,\n COL5_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN,\n COL6_BIT_MAP = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,\n COL6_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN,\n COL7_BIT_MAP = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,\n COL7_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN,\n COL8_BIT_MAP = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,\n COL8_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN,\n COL9_BIT_MAP = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,\n COL9_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN,\n BANK0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,\n BANK0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN,\n BANK1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,\n BANK1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN,\n BANK_GROUP0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,\n BANK_GROUP0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN,\n BANK_GROUP1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,\n BANK_GROUP1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN,\n };\n\n};\n\n\/\/ Why two enums? Two reasons. First, we need these to be contiguous, and\n\/\/ we can't always guarentee the symbols will be generated as such. Second,\n\/\/ we want to be 0'based so that we can use a static array as a table and\n\/\/ it's probably not possible for the symbols to be 0'based.\nenum\n{\n THIS_ENTRY_VALID = 0,\n VALUE_OF_D_BIT_INDEX = 1,\n GB12_ENABLE_INDEX = 2,\n MASTER_BIT_0_VALID_INDEX = 3,\n MASTER_BIT_1_VALID_INDEX = 4,\n SLAVE_BIT_0_VALID_INDEX = 5,\n SLAVE_BIT_1_VALID_INDEX = 6,\n SLAVE_BIT_2_VALID_INDEX = 7,\n ROW_BIT_15_VALID_INDEX = 8,\n ROW_BIT_16_VALID_INDEX = 9,\n ROW_BIT_17_VALID_INDEX = 10,\n BANK_BIT_2_VALID_INDEX = 11,\n DIMM_BIT_INDEX = 12,\n MASTER_BIT_0_INDEX = 13,\n MASTER_BIT_1_INDEX = 14,\n SLAVE_BIT_0_INDEX = 15,\n SLAVE_BIT_1_INDEX = 16,\n SLAVE_BIT_2_INDEX = 17,\n ROW_17_INDEX = 18,\n ROW_16_INDEX = 19,\n COLUMN_4_INDEX = 20,\n COLUMN_5_INDEX = 21,\n COLUMN_6_INDEX = 22,\n COLUMN_7_INDEX = 23,\n COLUMN_8_INDEX = 24,\n COLUMN_9_INDEX = 25,\n BANK_0_INDEX = 26,\n BANK_1_INDEX = 27,\n BANK_2_INDEX = 28,\n BANK_GROUP_0_BIT_INDEX = 29,\n BANK_GROUP_1_BIT_INDEX = 30,\n MAX_TRANSLATIONS = 31,\n};\n\nnamespace mc\n{\n\n\/\/\/\n\/\/\/ @brief safemode throttle values defined from MRW attributes\n\/\/\/ @param[in] i_target the MCA target\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/ @note sets safemode values for emergency mode and regular throttling\n\/\/\/\nfapi2::ReturnCode thermal_throttle_scominit (const fapi2::Target& i_target);\n\/\/\/\n\/\/\/ @brief Disable emergency mode throttle for thermal_init\n\/\/\/ @param[in] i_target the MCS target\n\/\/\/ @return FAPI_RC_SUCCESS iff ok\n\/\/\/ @note Clears MCMODE0_ENABLE_EMER_THROTTLE bit in MCSMODE0\n\/\/\/\nfapi2::ReturnCode disable_emergency_throttle (const fapi2::Target& i_target);\n\n\/\/\/\n\/\/\/ @brief Perform initializations of the MC translation\n\/\/\/ @tparam P the fapi2::TargetType of the port\n\/\/\/ @tparam TT the mcTraits associated with P\n\/\/\/ @param[in] i_target the target which has the MCA to map\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\ntemplate< fapi2::TargetType P, typename TT = mcTraits

>\nfapi2::ReturnCode setup_xlate_map(const fapi2::Target

& i_target);\n} \/\/mc\n} \/\/mss\n#endif\n<|endoftext|>"} {"text":"\/\/===----- RISCVMergeBaseOffset.cpp - Optimise address calculations ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Merge the offset of address calculation into the offset field\n\/\/ of instructions in a global address lowering sequence. This pass transforms:\n\/\/ lui vreg1, %hi(s)\n\/\/ addi vreg2, vreg1, %lo(s)\n\/\/ addi vreg3, verg2, Offset\n\/\/\n\/\/ Into:\n\/\/ lui vreg1, %hi(s+Offset)\n\/\/ addi vreg2, vreg1, %lo(s+Offset)\n\/\/\n\/\/ The transformation is carried out under certain conditions:\n\/\/ 1) The offset field in the base of global address lowering sequence is zero.\n\/\/ 2) The lowered global address has only one use.\n\/\/\n\/\/ The offset field can be in a different form. This pass handles all of them.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"RISCV.h\"\n#include \"RISCVTargetMachine.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \nusing namespace llvm;\n\n#define DEBUG_TYPE \"riscv-merge-base-offset\"\n#define RISCV_MERGE_BASE_OFFSET_NAME \"RISCV Merge Base Offset\"\nnamespace {\n\nstruct RISCVMergeBaseOffsetOpt : public MachineFunctionPass {\n static char ID;\n const MachineFunction *MF;\n bool runOnMachineFunction(MachineFunction &Fn) override;\n bool detectLuiAddiGlobal(MachineInstr &LUI, MachineInstr *&ADDI);\n\n bool detectAndFoldOffset(MachineInstr &HiLUI, MachineInstr &LoADDI);\n void foldOffset(MachineInstr &HiLUI, MachineInstr &LoADDI, MachineInstr &Tail,\n int64_t Offset);\n bool matchLargeOffset(MachineInstr &TailAdd, unsigned GSReg, int64_t &Offset);\n RISCVMergeBaseOffsetOpt() : MachineFunctionPass(ID) {}\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::IsSSA);\n }\n\n StringRef getPassName() const override {\n return RISCV_MERGE_BASE_OFFSET_NAME;\n }\n\nprivate:\n MachineRegisterInfo *MRI;\n std::set DeadInstrs;\n};\n}; \/\/ end anonymous namespace\n\nchar RISCVMergeBaseOffsetOpt::ID = 0;\nINITIALIZE_PASS(RISCVMergeBaseOffsetOpt, \"riscv-merge-base-offset\",\n RISCV_MERGE_BASE_OFFSET_NAME, false, false)\n\n\/\/ Detect the pattern:\n\/\/ lui vreg1, %hi(s)\n\/\/ addi vreg2, vreg1, %lo(s)\n\/\/\n\/\/ Pattern only accepted if:\n\/\/ 1) ADDI has only one use.\n\/\/ 2) LUI has only one use; which is the ADDI.\n\/\/ 3) Both ADDI and LUI have GlobalAddress type which indicates that these\n\/\/ are generated from global address lowering.\n\/\/ 4) Offset value in the Global Address is 0.\nbool RISCVMergeBaseOffsetOpt::detectLuiAddiGlobal(MachineInstr &HiLUI,\n MachineInstr *&LoADDI) {\n if (HiLUI.getOpcode() != RISCV::LUI ||\n HiLUI.getOperand(1).getTargetFlags() != RISCVII::MO_HI ||\n HiLUI.getOperand(1).getType() != MachineOperand::MO_GlobalAddress ||\n HiLUI.getOperand(1).getOffset() != 0 ||\n !MRI->hasOneUse(HiLUI.getOperand(0).getReg()))\n return false;\n unsigned HiLuiDestReg = HiLUI.getOperand(0).getReg();\n LoADDI = MRI->use_begin(HiLuiDestReg)->getParent();\n if (LoADDI->getOpcode() != RISCV::ADDI ||\n LoADDI->getOperand(2).getTargetFlags() != RISCVII::MO_LO ||\n LoADDI->getOperand(2).getType() != MachineOperand::MO_GlobalAddress ||\n LoADDI->getOperand(2).getOffset() != 0 ||\n !MRI->hasOneUse(LoADDI->getOperand(0).getReg()))\n return false;\n return true;\n}\n\n\/\/ Update the offset in HiLUI and LoADDI instructions.\n\/\/ Delete the tail instruction and update all the uses to use the\n\/\/ output from LoADDI.\nvoid RISCVMergeBaseOffsetOpt::foldOffset(MachineInstr &HiLUI,\n MachineInstr &LoADDI,\n MachineInstr &Tail, int64_t Offset) {\n \/\/ Put the offset back in HiLUI and the LoADDI\n HiLUI.getOperand(1).setOffset(Offset);\n LoADDI.getOperand(2).setOffset(Offset);\n \/\/ Delete the tail instruction.\n DeadInstrs.insert(&Tail);\n MRI->replaceRegWith(Tail.getOperand(0).getReg(),\n LoADDI.getOperand(0).getReg());\n LLVM_DEBUG(dbgs() << \" Merged offset \" << Offset << \" into base.\\n\"\n << \" \" << HiLUI << \" \" << LoADDI;);\n}\n\n\/\/ Detect patterns for large offsets that are passed into an ADD instruction.\n\/\/\n\/\/ Base address lowering is of the form:\n\/\/ HiLUI: lui vreg1, %hi(s)\n\/\/ LoADDI: addi vreg2, vreg1, %lo(s)\n\/\/ \/ \\\n\/\/ \/ \\\n\/\/ \/ \\\n\/\/ \/ The large offset can be of two forms: \\\n\/\/ 1) Offset that has non zero bits in lower 2) Offset that has non zero\n\/\/ 12 bits and upper 20 bits bits in upper 20 bits only\n\/\/ OffseLUI: lui vreg3, 4\n\/\/ OffsetTail: addi voff, vreg3, 188 OffsetTail: lui voff, 128\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ TailAdd: add vreg4, vreg2, voff\nbool RISCVMergeBaseOffsetOpt::matchLargeOffset(MachineInstr &TailAdd,\n unsigned GAReg,\n int64_t &Offset) {\n assert((TailAdd.getOpcode() == RISCV::ADD) && \"Expected ADD instruction!\");\n unsigned Rs = TailAdd.getOperand(1).getReg();\n unsigned Rt = TailAdd.getOperand(2).getReg();\n unsigned Reg = Rs == GAReg ? Rt : Rs;\n\n \/\/ Can't fold if the register has more than one use.\n if (!MRI->hasOneUse(Reg))\n return false;\n \/\/ This can point to an ADDI or a LUI:\n MachineInstr &OffsetTail = *MRI->getVRegDef(Reg);\n if (OffsetTail.getOpcode() == RISCV::ADDI) {\n \/\/ The offset value has non zero bits in both %hi and %lo parts.\n \/\/ Detect an ADDI that feeds from a LUI instruction.\n MachineOperand &AddiImmOp = OffsetTail.getOperand(2);\n if (AddiImmOp.getTargetFlags() != RISCVII::MO_None)\n return false;\n int64_t OffLo = AddiImmOp.getImm();\n MachineInstr &OffsetLui =\n *MRI->getVRegDef(OffsetTail.getOperand(1).getReg());\n MachineOperand &LuiImmOp = OffsetLui.getOperand(1);\n if (OffsetLui.getOpcode() != RISCV::LUI ||\n LuiImmOp.getTargetFlags() != RISCVII::MO_None ||\n !MRI->hasOneUse(OffsetLui.getOperand(0).getReg()))\n return false;\n int64_t OffHi = OffsetLui.getOperand(1).getImm();\n Offset = (OffHi << 12) + OffLo;\n LLVM_DEBUG(dbgs() << \" Offset Instrs: \" << OffsetTail\n << \" \" << OffsetLui);\n DeadInstrs.insert(&OffsetTail);\n DeadInstrs.insert(&OffsetLui);\n return true;\n } else if (OffsetTail.getOpcode() == RISCV::LUI) {\n \/\/ The offset value has all zero bits in the lower 12 bits. Only LUI\n \/\/ exists.\n LLVM_DEBUG(dbgs() << \" Offset Instr: \" << OffsetTail);\n Offset = OffsetTail.getOperand(1).getImm() << 12;\n DeadInstrs.insert(&OffsetTail);\n return true;\n }\n return false;\n}\n\nbool RISCVMergeBaseOffsetOpt::detectAndFoldOffset(MachineInstr &HiLUI,\n MachineInstr &LoADDI) {\n unsigned DestReg = LoADDI.getOperand(0).getReg();\n assert(MRI->hasOneUse(DestReg) && \"expected one use for LoADDI\");\n \/\/ LoADDI has only one use.\n MachineInstr &Tail = *MRI->use_begin(DestReg)->getParent();\n switch (Tail.getOpcode()) {\n default:\n LLVM_DEBUG(dbgs() << \"Don't know how to get offset from this instr:\"\n << Tail);\n return false;\n case RISCV::ADDI: {\n \/\/ Offset is simply an immediate operand.\n int64_t Offset = Tail.getOperand(2).getImm();\n LLVM_DEBUG(dbgs() << \" Offset Instr: \" << Tail);\n foldOffset(HiLUI, LoADDI, Tail, Offset);\n return true;\n } break;\n case RISCV::ADD: {\n \/\/ The offset is too large to fit in the immediate field of ADDI.\n \/\/ This can be in two forms:\n \/\/ 1) LUI hi_Offset followed by:\n \/\/ ADDI lo_offset\n \/\/ This happens in case the offset has non zero bits in\n \/\/ both hi 20 and lo 12 bits.\n \/\/ 2) LUI (offset20)\n \/\/ This happens in case the lower 12 bits of the offset are zeros.\n int64_t Offset;\n if (!matchLargeOffset(Tail, DestReg, Offset))\n return false;\n foldOffset(HiLUI, LoADDI, Tail, Offset);\n return true;\n } break;\n case RISCV::LB:\n case RISCV::LH:\n case RISCV::LW:\n case RISCV::LBU:\n case RISCV::LHU:\n case RISCV::LWU:\n case RISCV::LD:\n case RISCV::FLW:\n case RISCV::FLD:\n case RISCV::SB:\n case RISCV::SH:\n case RISCV::SW:\n case RISCV::SD:\n case RISCV::FSW:\n case RISCV::FSD: {\n \/\/ Transforms the sequence: Into:\n \/\/ HiLUI: lui vreg1, %hi(foo) ---> lui vreg1, %hi(foo+8)\n \/\/ LoADDI: addi vreg2, vreg1, %lo(foo) ---> lw vreg3, lo(foo+8)(vreg1)\n \/\/ Tail: lw vreg3, 8(vreg2)\n if (Tail.getOperand(1).isFI())\n return false;\n \/\/ Register defined by LoADDI should be used in the base part of the\n \/\/ load\\store instruction. Otherwise, no folding possible.\n unsigned BaseAddrReg = Tail.getOperand(1).getReg();\n if (DestReg != BaseAddrReg)\n return false;\n MachineOperand &TailImmOp = Tail.getOperand(2);\n int64_t Offset = TailImmOp.getImm();\n \/\/ Update the offsets in global address lowering.\n HiLUI.getOperand(1).setOffset(Offset);\n \/\/ Update the immediate in the Tail instruction to add the offset.\n Tail.RemoveOperand(2);\n MachineOperand &ImmOp = LoADDI.getOperand(2);\n ImmOp.setOffset(Offset);\n Tail.addOperand(ImmOp);\n \/\/ Update the base reg in the Tail instruction to feed from LUI.\n \/\/ Output of HiLUI is only used in LoADDI, no need to use\n \/\/ MRI->replaceRegWith().\n Tail.getOperand(1).setReg(HiLUI.getOperand(0).getReg());\n DeadInstrs.insert(&LoADDI);\n return true;\n } break;\n }\n return false;\n}\n\nbool RISCVMergeBaseOffsetOpt::runOnMachineFunction(MachineFunction &Fn) {\n if (skipFunction(Fn.getFunction()))\n return false;\n\n DeadInstrs.clear();\n MRI = &Fn.getRegInfo();\n for (MachineBasicBlock &MBB : Fn) {\n LLVM_DEBUG(dbgs() << \"MBB: \" << MBB.getName() << \"\\n\");\n for (MachineInstr &HiLUI : MBB) {\n MachineInstr *LoADDI = nullptr;\n if (!detectLuiAddiGlobal(HiLUI, LoADDI))\n continue;\n LLVM_DEBUG(dbgs() << \" Found lowered global address with one use: \"\n << *LoADDI->getOperand(2).getGlobal() << \"\\n\");\n \/\/ If the use count is only one, merge the offset\n detectAndFoldOffset(HiLUI, *LoADDI);\n }\n }\n \/\/ Delete dead instructions.\n for (auto *MI : DeadInstrs)\n MI->eraseFromParent();\n return true;\n}\n\n\/\/\/ Returns an instance of the Merge Base Offset Optimization pass.\nFunctionPass *llvm::createRISCVMergeBaseOffsetOptPass() {\n return new RISCVMergeBaseOffsetOpt();\n}\nTest commit.\/\/===----- RISCVMergeBaseOffset.cpp - Optimise address calculations ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Merge the offset of address calculation into the offset field\n\/\/ of instructions in a global address lowering sequence. This pass transforms:\n\/\/ lui vreg1, %hi(s)\n\/\/ addi vreg2, vreg1, %lo(s)\n\/\/ addi vreg3, verg2, Offset\n\/\/\n\/\/ Into:\n\/\/ lui vreg1, %hi(s+Offset)\n\/\/ addi vreg2, vreg1, %lo(s+Offset)\n\/\/\n\/\/ The transformation is carried out under certain conditions:\n\/\/ 1) The offset field in the base of global address lowering sequence is zero.\n\/\/ 2) The lowered global address has only one use.\n\/\/\n\/\/ The offset field can be in a different form. This pass handles all of them.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"RISCV.h\"\n#include \"RISCVTargetMachine.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \nusing namespace llvm;\n\n#define DEBUG_TYPE \"riscv-merge-base-offset\"\n#define RISCV_MERGE_BASE_OFFSET_NAME \"RISCV Merge Base Offset\"\nnamespace {\n\nstruct RISCVMergeBaseOffsetOpt : public MachineFunctionPass {\n static char ID;\n const MachineFunction *MF;\n bool runOnMachineFunction(MachineFunction &Fn) override;\n bool detectLuiAddiGlobal(MachineInstr &LUI, MachineInstr *&ADDI);\n\n bool detectAndFoldOffset(MachineInstr &HiLUI, MachineInstr &LoADDI);\n void foldOffset(MachineInstr &HiLUI, MachineInstr &LoADDI, MachineInstr &Tail,\n int64_t Offset);\n bool matchLargeOffset(MachineInstr &TailAdd, unsigned GSReg, int64_t &Offset);\n RISCVMergeBaseOffsetOpt() : MachineFunctionPass(ID) {}\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::IsSSA);\n }\n\n StringRef getPassName() const override {\n return RISCV_MERGE_BASE_OFFSET_NAME;\n }\n\nprivate:\n MachineRegisterInfo *MRI;\n std::set DeadInstrs;\n};\n} \/\/ end anonymous namespace\n\nchar RISCVMergeBaseOffsetOpt::ID = 0;\nINITIALIZE_PASS(RISCVMergeBaseOffsetOpt, \"riscv-merge-base-offset\",\n RISCV_MERGE_BASE_OFFSET_NAME, false, false)\n\n\/\/ Detect the pattern:\n\/\/ lui vreg1, %hi(s)\n\/\/ addi vreg2, vreg1, %lo(s)\n\/\/\n\/\/ Pattern only accepted if:\n\/\/ 1) ADDI has only one use.\n\/\/ 2) LUI has only one use; which is the ADDI.\n\/\/ 3) Both ADDI and LUI have GlobalAddress type which indicates that these\n\/\/ are generated from global address lowering.\n\/\/ 4) Offset value in the Global Address is 0.\nbool RISCVMergeBaseOffsetOpt::detectLuiAddiGlobal(MachineInstr &HiLUI,\n MachineInstr *&LoADDI) {\n if (HiLUI.getOpcode() != RISCV::LUI ||\n HiLUI.getOperand(1).getTargetFlags() != RISCVII::MO_HI ||\n HiLUI.getOperand(1).getType() != MachineOperand::MO_GlobalAddress ||\n HiLUI.getOperand(1).getOffset() != 0 ||\n !MRI->hasOneUse(HiLUI.getOperand(0).getReg()))\n return false;\n unsigned HiLuiDestReg = HiLUI.getOperand(0).getReg();\n LoADDI = MRI->use_begin(HiLuiDestReg)->getParent();\n if (LoADDI->getOpcode() != RISCV::ADDI ||\n LoADDI->getOperand(2).getTargetFlags() != RISCVII::MO_LO ||\n LoADDI->getOperand(2).getType() != MachineOperand::MO_GlobalAddress ||\n LoADDI->getOperand(2).getOffset() != 0 ||\n !MRI->hasOneUse(LoADDI->getOperand(0).getReg()))\n return false;\n return true;\n}\n\n\/\/ Update the offset in HiLUI and LoADDI instructions.\n\/\/ Delete the tail instruction and update all the uses to use the\n\/\/ output from LoADDI.\nvoid RISCVMergeBaseOffsetOpt::foldOffset(MachineInstr &HiLUI,\n MachineInstr &LoADDI,\n MachineInstr &Tail, int64_t Offset) {\n \/\/ Put the offset back in HiLUI and the LoADDI\n HiLUI.getOperand(1).setOffset(Offset);\n LoADDI.getOperand(2).setOffset(Offset);\n \/\/ Delete the tail instruction.\n DeadInstrs.insert(&Tail);\n MRI->replaceRegWith(Tail.getOperand(0).getReg(),\n LoADDI.getOperand(0).getReg());\n LLVM_DEBUG(dbgs() << \" Merged offset \" << Offset << \" into base.\\n\"\n << \" \" << HiLUI << \" \" << LoADDI;);\n}\n\n\/\/ Detect patterns for large offsets that are passed into an ADD instruction.\n\/\/\n\/\/ Base address lowering is of the form:\n\/\/ HiLUI: lui vreg1, %hi(s)\n\/\/ LoADDI: addi vreg2, vreg1, %lo(s)\n\/\/ \/ \\\n\/\/ \/ \\\n\/\/ \/ \\\n\/\/ \/ The large offset can be of two forms: \\\n\/\/ 1) Offset that has non zero bits in lower 2) Offset that has non zero\n\/\/ 12 bits and upper 20 bits bits in upper 20 bits only\n\/\/ OffseLUI: lui vreg3, 4\n\/\/ OffsetTail: addi voff, vreg3, 188 OffsetTail: lui voff, 128\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ \\ \/\n\/\/ TailAdd: add vreg4, vreg2, voff\nbool RISCVMergeBaseOffsetOpt::matchLargeOffset(MachineInstr &TailAdd,\n unsigned GAReg,\n int64_t &Offset) {\n assert((TailAdd.getOpcode() == RISCV::ADD) && \"Expected ADD instruction!\");\n unsigned Rs = TailAdd.getOperand(1).getReg();\n unsigned Rt = TailAdd.getOperand(2).getReg();\n unsigned Reg = Rs == GAReg ? Rt : Rs;\n\n \/\/ Can't fold if the register has more than one use.\n if (!MRI->hasOneUse(Reg))\n return false;\n \/\/ This can point to an ADDI or a LUI:\n MachineInstr &OffsetTail = *MRI->getVRegDef(Reg);\n if (OffsetTail.getOpcode() == RISCV::ADDI) {\n \/\/ The offset value has non zero bits in both %hi and %lo parts.\n \/\/ Detect an ADDI that feeds from a LUI instruction.\n MachineOperand &AddiImmOp = OffsetTail.getOperand(2);\n if (AddiImmOp.getTargetFlags() != RISCVII::MO_None)\n return false;\n int64_t OffLo = AddiImmOp.getImm();\n MachineInstr &OffsetLui =\n *MRI->getVRegDef(OffsetTail.getOperand(1).getReg());\n MachineOperand &LuiImmOp = OffsetLui.getOperand(1);\n if (OffsetLui.getOpcode() != RISCV::LUI ||\n LuiImmOp.getTargetFlags() != RISCVII::MO_None ||\n !MRI->hasOneUse(OffsetLui.getOperand(0).getReg()))\n return false;\n int64_t OffHi = OffsetLui.getOperand(1).getImm();\n Offset = (OffHi << 12) + OffLo;\n LLVM_DEBUG(dbgs() << \" Offset Instrs: \" << OffsetTail\n << \" \" << OffsetLui);\n DeadInstrs.insert(&OffsetTail);\n DeadInstrs.insert(&OffsetLui);\n return true;\n } else if (OffsetTail.getOpcode() == RISCV::LUI) {\n \/\/ The offset value has all zero bits in the lower 12 bits. Only LUI\n \/\/ exists.\n LLVM_DEBUG(dbgs() << \" Offset Instr: \" << OffsetTail);\n Offset = OffsetTail.getOperand(1).getImm() << 12;\n DeadInstrs.insert(&OffsetTail);\n return true;\n }\n return false;\n}\n\nbool RISCVMergeBaseOffsetOpt::detectAndFoldOffset(MachineInstr &HiLUI,\n MachineInstr &LoADDI) {\n unsigned DestReg = LoADDI.getOperand(0).getReg();\n assert(MRI->hasOneUse(DestReg) && \"expected one use for LoADDI\");\n \/\/ LoADDI has only one use.\n MachineInstr &Tail = *MRI->use_begin(DestReg)->getParent();\n switch (Tail.getOpcode()) {\n default:\n LLVM_DEBUG(dbgs() << \"Don't know how to get offset from this instr:\"\n << Tail);\n return false;\n case RISCV::ADDI: {\n \/\/ Offset is simply an immediate operand.\n int64_t Offset = Tail.getOperand(2).getImm();\n LLVM_DEBUG(dbgs() << \" Offset Instr: \" << Tail);\n foldOffset(HiLUI, LoADDI, Tail, Offset);\n return true;\n } break;\n case RISCV::ADD: {\n \/\/ The offset is too large to fit in the immediate field of ADDI.\n \/\/ This can be in two forms:\n \/\/ 1) LUI hi_Offset followed by:\n \/\/ ADDI lo_offset\n \/\/ This happens in case the offset has non zero bits in\n \/\/ both hi 20 and lo 12 bits.\n \/\/ 2) LUI (offset20)\n \/\/ This happens in case the lower 12 bits of the offset are zeros.\n int64_t Offset;\n if (!matchLargeOffset(Tail, DestReg, Offset))\n return false;\n foldOffset(HiLUI, LoADDI, Tail, Offset);\n return true;\n } break;\n case RISCV::LB:\n case RISCV::LH:\n case RISCV::LW:\n case RISCV::LBU:\n case RISCV::LHU:\n case RISCV::LWU:\n case RISCV::LD:\n case RISCV::FLW:\n case RISCV::FLD:\n case RISCV::SB:\n case RISCV::SH:\n case RISCV::SW:\n case RISCV::SD:\n case RISCV::FSW:\n case RISCV::FSD: {\n \/\/ Transforms the sequence: Into:\n \/\/ HiLUI: lui vreg1, %hi(foo) ---> lui vreg1, %hi(foo+8)\n \/\/ LoADDI: addi vreg2, vreg1, %lo(foo) ---> lw vreg3, lo(foo+8)(vreg1)\n \/\/ Tail: lw vreg3, 8(vreg2)\n if (Tail.getOperand(1).isFI())\n return false;\n \/\/ Register defined by LoADDI should be used in the base part of the\n \/\/ load\\store instruction. Otherwise, no folding possible.\n unsigned BaseAddrReg = Tail.getOperand(1).getReg();\n if (DestReg != BaseAddrReg)\n return false;\n MachineOperand &TailImmOp = Tail.getOperand(2);\n int64_t Offset = TailImmOp.getImm();\n \/\/ Update the offsets in global address lowering.\n HiLUI.getOperand(1).setOffset(Offset);\n \/\/ Update the immediate in the Tail instruction to add the offset.\n Tail.RemoveOperand(2);\n MachineOperand &ImmOp = LoADDI.getOperand(2);\n ImmOp.setOffset(Offset);\n Tail.addOperand(ImmOp);\n \/\/ Update the base reg in the Tail instruction to feed from LUI.\n \/\/ Output of HiLUI is only used in LoADDI, no need to use\n \/\/ MRI->replaceRegWith().\n Tail.getOperand(1).setReg(HiLUI.getOperand(0).getReg());\n DeadInstrs.insert(&LoADDI);\n return true;\n } break;\n }\n return false;\n}\n\nbool RISCVMergeBaseOffsetOpt::runOnMachineFunction(MachineFunction &Fn) {\n if (skipFunction(Fn.getFunction()))\n return false;\n\n DeadInstrs.clear();\n MRI = &Fn.getRegInfo();\n for (MachineBasicBlock &MBB : Fn) {\n LLVM_DEBUG(dbgs() << \"MBB: \" << MBB.getName() << \"\\n\");\n for (MachineInstr &HiLUI : MBB) {\n MachineInstr *LoADDI = nullptr;\n if (!detectLuiAddiGlobal(HiLUI, LoADDI))\n continue;\n LLVM_DEBUG(dbgs() << \" Found lowered global address with one use: \"\n << *LoADDI->getOperand(2).getGlobal() << \"\\n\");\n \/\/ If the use count is only one, merge the offset\n detectAndFoldOffset(HiLUI, *LoADDI);\n }\n }\n \/\/ Delete dead instructions.\n for (auto *MI : DeadInstrs)\n MI->eraseFromParent();\n return true;\n}\n\n\/\/\/ Returns an instance of the Merge Base Offset Optimization pass.\nFunctionPass *llvm::createRISCVMergeBaseOffsetOptPass() {\n return new RISCVMergeBaseOffsetOpt();\n}\n<|endoftext|>"} {"text":"\/\/===-- StructRetPromotion.cpp - Promote sret arguments ------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass finds functions that return a struct (using a pointer to the struct\n\/\/ as the first argument of the function, marked with the 'sret' attribute) and\n\/\/ replaces them with a new function that simply returns each of the elements of\n\/\/ that struct (using multiple return values).\n\/\/\n\/\/ This pass works under a number of conditions:\n\/\/ 1. The returned struct must not contain other structs\n\/\/ 2. The returned struct must only be used to load values from\n\/\/ 3. The placeholder struct passed in is the result of an alloca\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sretpromotion\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nSTATISTIC(NumRejectedSRETUses , \"Number of sret rejected due to unexpected uses\");\nSTATISTIC(NumSRET , \"Number of sret promoted\");\nnamespace {\n \/\/\/ SRETPromotion - This pass removes sret parameter and updates\n \/\/\/ function to use multiple return value.\n \/\/\/\n struct SRETPromotion : public CallGraphSCCPass {\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n virtual bool runOnSCC(CallGraphSCC &SCC);\n static char ID; \/\/ Pass identification, replacement for typeid\n SRETPromotion() : CallGraphSCCPass(&ID) {}\n\n private:\n CallGraphNode *PromoteReturn(CallGraphNode *CGN);\n bool isSafeToUpdateAllCallers(Function *F);\n Function *cloneFunctionBody(Function *F, const StructType *STy);\n CallGraphNode *updateCallSites(Function *F, Function *NF);\n bool nestedStructType(const StructType *STy);\n };\n}\n\nchar SRETPromotion::ID = 0;\nstatic RegisterPass\nX(\"sretpromotion\", \"Promote sret arguments to multiple ret values\");\n\nPass *llvm::createStructRetPromotionPass() {\n return new SRETPromotion();\n}\n\nbool SRETPromotion::runOnSCC(CallGraphSCC &SCC) {\n bool Changed = false;\n\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n if (CallGraphNode *NewNode = PromoteReturn(*I)) {\n SCC.ReplaceNode(*I, NewNode);\n Changed = true;\n }\n\n return Changed;\n}\n\n\/\/\/ PromoteReturn - This method promotes function that uses StructRet paramater \n\/\/\/ into a function that uses multiple return values.\nCallGraphNode *SRETPromotion::PromoteReturn(CallGraphNode *CGN) {\n Function *F = CGN->getFunction();\n\n if (!F || F->isDeclaration() || !F->hasLocalLinkage())\n return 0;\n\n \/\/ Make sure that function returns struct.\n if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())\n return 0;\n\n DEBUG(dbgs() << \"SretPromotion: Looking at sret function \" \n << F->getName() << \"\\n\");\n\n assert(F->getReturnType()->isVoidTy() && \"Invalid function return type\");\n Function::arg_iterator AI = F->arg_begin();\n const llvm::PointerType *FArgType = dyn_cast(AI->getType());\n assert(FArgType && \"Invalid sret parameter type\");\n const llvm::StructType *STy = \n dyn_cast(FArgType->getElementType());\n assert(STy && \"Invalid sret parameter element type\");\n\n \/\/ Check if it is ok to perform this promotion.\n if (isSafeToUpdateAllCallers(F) == false) {\n DEBUG(dbgs() << \"SretPromotion: Not all callers can be updated\\n\");\n ++NumRejectedSRETUses;\n return 0;\n }\n\n DEBUG(dbgs() << \"SretPromotion: sret argument will be promoted\\n\");\n ++NumSRET;\n \/\/ [1] Replace use of sret parameter \n AllocaInst *TheAlloca = new AllocaInst(STy, NULL, \"mrv\", \n F->getEntryBlock().begin());\n Value *NFirstArg = F->arg_begin();\n NFirstArg->replaceAllUsesWith(TheAlloca);\n\n \/\/ [2] Find and replace ret instructions\n for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) \n for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {\n Instruction *I = BI;\n ++BI;\n if (isa(I)) {\n Value *NV = new LoadInst(TheAlloca, \"mrv.ld\", I);\n ReturnInst *NR = ReturnInst::Create(F->getContext(), NV, I);\n I->replaceAllUsesWith(NR);\n I->eraseFromParent();\n }\n }\n\n \/\/ [3] Create the new function body and insert it into the module.\n Function *NF = cloneFunctionBody(F, STy);\n\n \/\/ [4] Update all call sites to use new function\n CallGraphNode *NF_CFN = updateCallSites(F, NF);\n\n CallGraph &CG = getAnalysis();\n NF_CFN->stealCalledFunctionsFrom(CG[F]);\n\n delete CG.removeFunctionFromModule(F);\n return NF_CFN;\n}\n\n\/\/ Check if it is ok to perform this promotion.\nbool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {\n\n if (F->use_empty())\n \/\/ No users. OK to modify signature.\n return true;\n\n for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();\n FnUseI != FnUseE; ++FnUseI) {\n \/\/ The function is passed in as an argument to (possibly) another function,\n \/\/ we can't change it!\n CallSite CS = CallSite::get(*FnUseI);\n Instruction *Call = CS.getInstruction();\n \/\/ The function is used by something else than a call or invoke instruction,\n \/\/ we can't change it!\n if (!Call || !CS.isCallee(FnUseI))\n return false;\n CallSite::arg_iterator AI = CS.arg_begin();\n Value *FirstArg = *AI;\n\n if (!isa(FirstArg))\n return false;\n\n \/\/ Check FirstArg's users.\n for (Value::use_iterator ArgI = FirstArg->use_begin(), \n ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {\n\n \/\/ If FirstArg user is a CallInst that does not correspond to current\n \/\/ call site then this function F is not suitable for sret promotion.\n if (CallInst *CI = dyn_cast(ArgI)) {\n if (CI != Call)\n return false;\n }\n \/\/ If FirstArg user is a GEP whose all users are not LoadInst then\n \/\/ this function F is not suitable for sret promotion.\n else if (GetElementPtrInst *GEP = dyn_cast(ArgI)) {\n \/\/ TODO : Use dom info and insert PHINodes to collect get results\n \/\/ from multiple call sites for this GEP.\n if (GEP->getParent() != Call->getParent())\n return false;\n for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();\n GEPI != GEPE; ++GEPI) \n if (!isa(GEPI))\n return false;\n } \n \/\/ Any other FirstArg users make this function unsuitable for sret \n \/\/ promotion.\n else\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/ cloneFunctionBody - Create a new function based on F and\n\/\/\/ insert it into module. Remove first argument. Use STy as\n\/\/\/ the return type for new function.\nFunction *SRETPromotion::cloneFunctionBody(Function *F, \n const StructType *STy) {\n\n const FunctionType *FTy = F->getFunctionType();\n std::vector Params;\n\n \/\/ Attributes - Keep track of the parameter attributes for the arguments.\n SmallVector AttributesVec;\n const AttrListPtr &PAL = F->getAttributes();\n\n \/\/ Add any return attributes.\n if (Attributes attrs = PAL.getRetAttributes())\n AttributesVec.push_back(AttributeWithIndex::get(0, attrs));\n\n \/\/ Skip first argument.\n Function::arg_iterator I = F->arg_begin(), E = F->arg_end();\n ++I;\n \/\/ 0th parameter attribute is reserved for return type.\n \/\/ 1th parameter attribute is for first 1st sret argument.\n unsigned ParamIndex = 2; \n while (I != E) {\n Params.push_back(I->getType());\n if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))\n AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));\n ++I;\n ++ParamIndex;\n }\n\n \/\/ Add any fn attributes.\n if (Attributes attrs = PAL.getFnAttributes())\n AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));\n\n\n FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());\n Function *NF = Function::Create(NFTy, F->getLinkage());\n NF->takeName(F);\n NF->copyAttributesFrom(F);\n NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));\n F->getParent()->getFunctionList().insert(F, NF);\n NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());\n\n \/\/ Replace arguments\n I = F->arg_begin();\n E = F->arg_end();\n Function::arg_iterator NI = NF->arg_begin();\n ++I;\n while (I != E) {\n I->replaceAllUsesWith(NI);\n NI->takeName(I);\n ++I;\n ++NI;\n }\n\n return NF;\n}\n\n\/\/\/ updateCallSites - Update all sites that call F to use NF.\nCallGraphNode *SRETPromotion::updateCallSites(Function *F, Function *NF) {\n CallGraph &CG = getAnalysis();\n SmallVector Args;\n\n \/\/ Attributes - Keep track of the parameter attributes for the arguments.\n SmallVector ArgAttrsVec;\n\n \/\/ Get a new callgraph node for NF.\n CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);\n\n while (!F->use_empty()) {\n CallSite CS = CallSite::get(*F->use_begin());\n Instruction *Call = CS.getInstruction();\n\n const AttrListPtr &PAL = F->getAttributes();\n \/\/ Add any return attributes.\n if (Attributes attrs = PAL.getRetAttributes())\n ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));\n\n \/\/ Copy arguments, however skip first one.\n CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();\n Value *FirstCArg = *AI;\n ++AI;\n \/\/ 0th parameter attribute is reserved for return type.\n \/\/ 1th parameter attribute is for first 1st sret argument.\n unsigned ParamIndex = 2; \n while (AI != AE) {\n Args.push_back(*AI); \n if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))\n ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));\n ++ParamIndex;\n ++AI;\n }\n\n \/\/ Add any function attributes.\n if (Attributes attrs = PAL.getFnAttributes())\n ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));\n \n AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());\n \n \/\/ Build new call instruction.\n Instruction *New;\n if (InvokeInst *II = dyn_cast(Call)) {\n New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),\n Args.begin(), Args.end(), \"\", Call);\n cast(New)->setCallingConv(CS.getCallingConv());\n cast(New)->setAttributes(NewPAL);\n } else {\n New = CallInst::Create(NF, Args.begin(), Args.end(), \"\", Call);\n cast(New)->setCallingConv(CS.getCallingConv());\n cast(New)->setAttributes(NewPAL);\n if (cast(Call)->isTailCall())\n cast(New)->setTailCall();\n }\n Args.clear();\n ArgAttrsVec.clear();\n New->takeName(Call);\n\n \/\/ Update the callgraph to know that the callsite has been transformed.\n CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];\n CalleeNode->removeCallEdgeFor(Call);\n CalleeNode->addCalledFunction(New, NF_CGN);\n \n \/\/ Update all users of sret parameter to extract value using extractvalue.\n for (Value::use_iterator UI = FirstCArg->use_begin(), \n UE = FirstCArg->use_end(); UI != UE; ) {\n User *U2 = *UI++;\n CallInst *C2 = dyn_cast(U2);\n if (C2 && (C2 == Call))\n continue;\n \n GetElementPtrInst *UGEP = cast(U2);\n ConstantInt *Idx = cast(UGEP->getOperand(2));\n Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),\n \"evi\", UGEP);\n while(!UGEP->use_empty()) {\n \/\/ isSafeToUpdateAllCallers has checked that all GEP uses are\n \/\/ LoadInsts\n LoadInst *L = cast(*UGEP->use_begin());\n L->replaceAllUsesWith(GR);\n L->eraseFromParent();\n }\n UGEP->eraseFromParent();\n continue;\n }\n Call->eraseFromParent();\n }\n \n return NF_CGN;\n}\n\n\/\/\/ nestedStructType - Return true if STy includes any\n\/\/\/ other aggregate types\nbool SRETPromotion::nestedStructType(const StructType *STy) {\n unsigned Num = STy->getNumElements();\n for (unsigned i = 0; i < Num; i++) {\n const Type *Ty = STy->getElementType(i);\n if (!Ty->isSingleValueType() && !Ty->isVoidTy())\n return true;\n }\n return false;\n}\ncache dereferenced iterators\/\/===-- StructRetPromotion.cpp - Promote sret arguments ------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass finds functions that return a struct (using a pointer to the struct\n\/\/ as the first argument of the function, marked with the 'sret' attribute) and\n\/\/ replaces them with a new function that simply returns each of the elements of\n\/\/ that struct (using multiple return values).\n\/\/\n\/\/ This pass works under a number of conditions:\n\/\/ 1. The returned struct must not contain other structs\n\/\/ 2. The returned struct must only be used to load values from\n\/\/ 3. The placeholder struct passed in is the result of an alloca\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sretpromotion\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Support\/CallSite.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nSTATISTIC(NumRejectedSRETUses , \"Number of sret rejected due to unexpected uses\");\nSTATISTIC(NumSRET , \"Number of sret promoted\");\nnamespace {\n \/\/\/ SRETPromotion - This pass removes sret parameter and updates\n \/\/\/ function to use multiple return value.\n \/\/\/\n struct SRETPromotion : public CallGraphSCCPass {\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n virtual bool runOnSCC(CallGraphSCC &SCC);\n static char ID; \/\/ Pass identification, replacement for typeid\n SRETPromotion() : CallGraphSCCPass(&ID) {}\n\n private:\n CallGraphNode *PromoteReturn(CallGraphNode *CGN);\n bool isSafeToUpdateAllCallers(Function *F);\n Function *cloneFunctionBody(Function *F, const StructType *STy);\n CallGraphNode *updateCallSites(Function *F, Function *NF);\n bool nestedStructType(const StructType *STy);\n };\n}\n\nchar SRETPromotion::ID = 0;\nstatic RegisterPass\nX(\"sretpromotion\", \"Promote sret arguments to multiple ret values\");\n\nPass *llvm::createStructRetPromotionPass() {\n return new SRETPromotion();\n}\n\nbool SRETPromotion::runOnSCC(CallGraphSCC &SCC) {\n bool Changed = false;\n\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n if (CallGraphNode *NewNode = PromoteReturn(*I)) {\n SCC.ReplaceNode(*I, NewNode);\n Changed = true;\n }\n\n return Changed;\n}\n\n\/\/\/ PromoteReturn - This method promotes function that uses StructRet paramater \n\/\/\/ into a function that uses multiple return values.\nCallGraphNode *SRETPromotion::PromoteReturn(CallGraphNode *CGN) {\n Function *F = CGN->getFunction();\n\n if (!F || F->isDeclaration() || !F->hasLocalLinkage())\n return 0;\n\n \/\/ Make sure that function returns struct.\n if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())\n return 0;\n\n DEBUG(dbgs() << \"SretPromotion: Looking at sret function \" \n << F->getName() << \"\\n\");\n\n assert(F->getReturnType()->isVoidTy() && \"Invalid function return type\");\n Function::arg_iterator AI = F->arg_begin();\n const llvm::PointerType *FArgType = dyn_cast(AI->getType());\n assert(FArgType && \"Invalid sret parameter type\");\n const llvm::StructType *STy = \n dyn_cast(FArgType->getElementType());\n assert(STy && \"Invalid sret parameter element type\");\n\n \/\/ Check if it is ok to perform this promotion.\n if (isSafeToUpdateAllCallers(F) == false) {\n DEBUG(dbgs() << \"SretPromotion: Not all callers can be updated\\n\");\n ++NumRejectedSRETUses;\n return 0;\n }\n\n DEBUG(dbgs() << \"SretPromotion: sret argument will be promoted\\n\");\n ++NumSRET;\n \/\/ [1] Replace use of sret parameter \n AllocaInst *TheAlloca = new AllocaInst(STy, NULL, \"mrv\", \n F->getEntryBlock().begin());\n Value *NFirstArg = F->arg_begin();\n NFirstArg->replaceAllUsesWith(TheAlloca);\n\n \/\/ [2] Find and replace ret instructions\n for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) \n for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {\n Instruction *I = BI;\n ++BI;\n if (isa(I)) {\n Value *NV = new LoadInst(TheAlloca, \"mrv.ld\", I);\n ReturnInst *NR = ReturnInst::Create(F->getContext(), NV, I);\n I->replaceAllUsesWith(NR);\n I->eraseFromParent();\n }\n }\n\n \/\/ [3] Create the new function body and insert it into the module.\n Function *NF = cloneFunctionBody(F, STy);\n\n \/\/ [4] Update all call sites to use new function\n CallGraphNode *NF_CFN = updateCallSites(F, NF);\n\n CallGraph &CG = getAnalysis();\n NF_CFN->stealCalledFunctionsFrom(CG[F]);\n\n delete CG.removeFunctionFromModule(F);\n return NF_CFN;\n}\n\n\/\/ Check if it is ok to perform this promotion.\nbool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {\n\n if (F->use_empty())\n \/\/ No users. OK to modify signature.\n return true;\n\n for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();\n FnUseI != FnUseE; ++FnUseI) {\n \/\/ The function is passed in as an argument to (possibly) another function,\n \/\/ we can't change it!\n CallSite CS = CallSite::get(*FnUseI);\n Instruction *Call = CS.getInstruction();\n \/\/ The function is used by something else than a call or invoke instruction,\n \/\/ we can't change it!\n if (!Call || !CS.isCallee(FnUseI))\n return false;\n CallSite::arg_iterator AI = CS.arg_begin();\n Value *FirstArg = *AI;\n\n if (!isa(FirstArg))\n return false;\n\n \/\/ Check FirstArg's users.\n for (Value::use_iterator ArgI = FirstArg->use_begin(), \n ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {\n User *U = *ArgI;\n \/\/ If FirstArg user is a CallInst that does not correspond to current\n \/\/ call site then this function F is not suitable for sret promotion.\n if (CallInst *CI = dyn_cast(U)) {\n if (CI != Call)\n return false;\n }\n \/\/ If FirstArg user is a GEP whose all users are not LoadInst then\n \/\/ this function F is not suitable for sret promotion.\n else if (GetElementPtrInst *GEP = dyn_cast(U)) {\n \/\/ TODO : Use dom info and insert PHINodes to collect get results\n \/\/ from multiple call sites for this GEP.\n if (GEP->getParent() != Call->getParent())\n return false;\n for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();\n GEPI != GEPE; ++GEPI) \n if (!isa(GEPI))\n return false;\n } \n \/\/ Any other FirstArg users make this function unsuitable for sret \n \/\/ promotion.\n else\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/ cloneFunctionBody - Create a new function based on F and\n\/\/\/ insert it into module. Remove first argument. Use STy as\n\/\/\/ the return type for new function.\nFunction *SRETPromotion::cloneFunctionBody(Function *F, \n const StructType *STy) {\n\n const FunctionType *FTy = F->getFunctionType();\n std::vector Params;\n\n \/\/ Attributes - Keep track of the parameter attributes for the arguments.\n SmallVector AttributesVec;\n const AttrListPtr &PAL = F->getAttributes();\n\n \/\/ Add any return attributes.\n if (Attributes attrs = PAL.getRetAttributes())\n AttributesVec.push_back(AttributeWithIndex::get(0, attrs));\n\n \/\/ Skip first argument.\n Function::arg_iterator I = F->arg_begin(), E = F->arg_end();\n ++I;\n \/\/ 0th parameter attribute is reserved for return type.\n \/\/ 1th parameter attribute is for first 1st sret argument.\n unsigned ParamIndex = 2; \n while (I != E) {\n Params.push_back(I->getType());\n if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))\n AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));\n ++I;\n ++ParamIndex;\n }\n\n \/\/ Add any fn attributes.\n if (Attributes attrs = PAL.getFnAttributes())\n AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));\n\n\n FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());\n Function *NF = Function::Create(NFTy, F->getLinkage());\n NF->takeName(F);\n NF->copyAttributesFrom(F);\n NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));\n F->getParent()->getFunctionList().insert(F, NF);\n NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());\n\n \/\/ Replace arguments\n I = F->arg_begin();\n E = F->arg_end();\n Function::arg_iterator NI = NF->arg_begin();\n ++I;\n while (I != E) {\n I->replaceAllUsesWith(NI);\n NI->takeName(I);\n ++I;\n ++NI;\n }\n\n return NF;\n}\n\n\/\/\/ updateCallSites - Update all sites that call F to use NF.\nCallGraphNode *SRETPromotion::updateCallSites(Function *F, Function *NF) {\n CallGraph &CG = getAnalysis();\n SmallVector Args;\n\n \/\/ Attributes - Keep track of the parameter attributes for the arguments.\n SmallVector ArgAttrsVec;\n\n \/\/ Get a new callgraph node for NF.\n CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);\n\n while (!F->use_empty()) {\n CallSite CS = CallSite::get(*F->use_begin());\n Instruction *Call = CS.getInstruction();\n\n const AttrListPtr &PAL = F->getAttributes();\n \/\/ Add any return attributes.\n if (Attributes attrs = PAL.getRetAttributes())\n ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));\n\n \/\/ Copy arguments, however skip first one.\n CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();\n Value *FirstCArg = *AI;\n ++AI;\n \/\/ 0th parameter attribute is reserved for return type.\n \/\/ 1th parameter attribute is for first 1st sret argument.\n unsigned ParamIndex = 2; \n while (AI != AE) {\n Args.push_back(*AI); \n if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))\n ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));\n ++ParamIndex;\n ++AI;\n }\n\n \/\/ Add any function attributes.\n if (Attributes attrs = PAL.getFnAttributes())\n ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));\n \n AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());\n \n \/\/ Build new call instruction.\n Instruction *New;\n if (InvokeInst *II = dyn_cast(Call)) {\n New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),\n Args.begin(), Args.end(), \"\", Call);\n cast(New)->setCallingConv(CS.getCallingConv());\n cast(New)->setAttributes(NewPAL);\n } else {\n New = CallInst::Create(NF, Args.begin(), Args.end(), \"\", Call);\n cast(New)->setCallingConv(CS.getCallingConv());\n cast(New)->setAttributes(NewPAL);\n if (cast(Call)->isTailCall())\n cast(New)->setTailCall();\n }\n Args.clear();\n ArgAttrsVec.clear();\n New->takeName(Call);\n\n \/\/ Update the callgraph to know that the callsite has been transformed.\n CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];\n CalleeNode->removeCallEdgeFor(Call);\n CalleeNode->addCalledFunction(New, NF_CGN);\n \n \/\/ Update all users of sret parameter to extract value using extractvalue.\n for (Value::use_iterator UI = FirstCArg->use_begin(), \n UE = FirstCArg->use_end(); UI != UE; ) {\n User *U2 = *UI++;\n CallInst *C2 = dyn_cast(U2);\n if (C2 && (C2 == Call))\n continue;\n \n GetElementPtrInst *UGEP = cast(U2);\n ConstantInt *Idx = cast(UGEP->getOperand(2));\n Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),\n \"evi\", UGEP);\n while(!UGEP->use_empty()) {\n \/\/ isSafeToUpdateAllCallers has checked that all GEP uses are\n \/\/ LoadInsts\n LoadInst *L = cast(*UGEP->use_begin());\n L->replaceAllUsesWith(GR);\n L->eraseFromParent();\n }\n UGEP->eraseFromParent();\n continue;\n }\n Call->eraseFromParent();\n }\n \n return NF_CGN;\n}\n\n\/\/\/ nestedStructType - Return true if STy includes any\n\/\/\/ other aggregate types\nbool SRETPromotion::nestedStructType(const StructType *STy) {\n unsigned Num = STy->getNumElements();\n for (unsigned i = 0; i < Num; i++) {\n const Type *Ty = STy->getElementType(i);\n if (!Ty->isSingleValueType() && !Ty->isVoidTy())\n return true;\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nBOOST_FIXTURE_TEST_SUITE(getarg_tests, BasicTestingSetup)\n\nstatic void ResetArgs(const std::string& strArg)\n{\n std::vector vecArg;\n if (strArg.size())\n boost::split(vecArg, strArg, IsSpace, boost::token_compress_on);\n\n \/\/ Insert dummy executable name:\n vecArg.insert(vecArg.begin(), \"testbitcoin\");\n\n \/\/ Convert to char*:\n std::vector vecChar;\n for (const std::string& s : vecArg)\n vecChar.push_back(s.c_str());\n\n std::string error;\n BOOST_CHECK(gArgs.ParseParameters(vecChar.size(), vecChar.data(), error));\n}\n\nstatic void SetupArgs(const std::vector>& args)\n{\n gArgs.ClearArgs();\n for (const auto& arg : args) {\n gArgs.AddArg(arg.first, \"\", arg.second, OptionsCategory::OPTIONS);\n }\n}\n\nBOOST_AUTO_TEST_CASE(boolarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo});\n ResetArgs(\"-foo\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n BOOST_CHECK(!gArgs.GetBoolArg(\"-fo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-fo\", true));\n\n BOOST_CHECK(!gArgs.GetBoolArg(\"-fooo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-fooo\", true));\n\n ResetArgs(\"-foo=0\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=1\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n \/\/ New 0.6 feature: auto-map -nosomething to !-something:\n ResetArgs(\"-nofoo\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo -nofoo\"); \/\/ -nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=1 -nofoo=1\"); \/\/ -nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=0 -nofoo=0\"); \/\/ -nofoo=0 should win\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n \/\/ New 0.6 feature: treat -- same as -:\n ResetArgs(\"--foo=1\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"--nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n}\n\nBOOST_AUTO_TEST_CASE(stringarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"eleven\");\n\n ResetArgs(\"-foo -bar\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"\");\n\n ResetArgs(\"-foo=\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"\");\n\n ResetArgs(\"-foo=11\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"11\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"11\");\n\n ResetArgs(\"-foo=eleven\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"eleven\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"eleven\");\n\n}\n\nBOOST_AUTO_TEST_CASE(intarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 11), 11);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 0), 0);\n\n ResetArgs(\"-foo -bar\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 11), 0);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 0);\n\n ResetArgs(\"-foo=11 -bar=12\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 0), 11);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 12);\n\n ResetArgs(\"-foo=NaN -bar=NotANumber\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 1), 0);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 0);\n}\n\nBOOST_AUTO_TEST_CASE(doubledash)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"--foo\");\n BOOST_CHECK_EQUAL(gArgs.GetBoolArg(\"-foo\", false), true);\n\n ResetArgs(\"--foo=verbose --bar=1\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"verbose\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 0), 1);\n}\n\nBOOST_AUTO_TEST_CASE(boolargno)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"-nofoo\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo=0\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-foo --nofoo\"); \/\/ --nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo -foo\"); \/\/ foo always wins:\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n}\n\nBOOST_AUTO_TEST_CASE(logargs)\n{\n const auto okaylog_bool = std::make_pair(\"-okaylog-bool\", ArgsManager::ALLOW_BOOL);\n const auto okaylog_negbool = std::make_pair(\"-okaylog-negbool\", ArgsManager::ALLOW_BOOL);\n const auto okaylog = std::make_pair(\"-okaylog\", ArgsManager::ALLOW_ANY);\n const auto dontlog = std::make_pair(\"-dontlog\", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE);\n SetupArgs({okaylog_bool, okaylog_negbool, okaylog, dontlog});\n ResetArgs(\"-okaylog-bool -nookaylog-negbool -okaylog=public -dontlog=private\");\n\n \/\/ Everything logged to debug.log will also append to str\n std::string str;\n auto print_connection = LogInstance().PushBackCallback(\n [&str](const std::string& s) {\n str += s;\n });\n\n \/\/ Log the arguments\n gArgs.LogArgs();\n\n LogInstance().DeleteCallback(print_connection);\n \/\/ Check that what should appear does, and what shouldn't doesn't.\n BOOST_CHECK(str.find(\"Command-line arg: okaylog-bool=\\\"\\\"\") != std::string::npos);\n BOOST_CHECK(str.find(\"Command-line arg: okaylog-negbool=false\") != std::string::npos);\n BOOST_CHECK(str.find(\"Command-line arg: okaylog=\\\"public\\\"\") != std::string::npos);\n BOOST_CHECK(str.find(\"dontlog=****\") != std::string::npos);\n BOOST_CHECK(str.find(\"private\") == std::string::npos);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nCreate a local class inherited from BasicTestingSetup with a localized args manager and put it into the getarg_tests namespace\/\/ Copyright (c) 2012-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace getarg_tests{\n class LocalTestingSetup : BasicTestingSetup {\n protected:\n void SetupArgs(const std::vector>& args);\n void ResetArgs(const std::string& strArg);\n ArgsManager m_args;\n };\n}\n\nBOOST_FIXTURE_TEST_SUITE(getarg_tests, LocalTestingSetup)\n\nvoid LocalTestingSetup :: ResetArgs(const std::string& strArg)\n{\n std::vector vecArg;\n if (strArg.size())\n boost::split(vecArg, strArg, IsSpace, boost::token_compress_on);\n\n \/\/ Insert dummy executable name:\n vecArg.insert(vecArg.begin(), \"testbitcoin\");\n\n \/\/ Convert to char*:\n std::vector vecChar;\n for (const std::string& s : vecArg)\n vecChar.push_back(s.c_str());\n\n std::string error;\n BOOST_CHECK(gArgs.ParseParameters(vecChar.size(), vecChar.data(), error));\n}\n\nvoid LocalTestingSetup :: SetupArgs(const std::vector>& args)\n{\n gArgs.ClearArgs();\n for (const auto& arg : args) {\n gArgs.AddArg(arg.first, \"\", arg.second, OptionsCategory::OPTIONS);\n }\n}\n\nBOOST_AUTO_TEST_CASE(boolarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo});\n ResetArgs(\"-foo\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n BOOST_CHECK(!gArgs.GetBoolArg(\"-fo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-fo\", true));\n\n BOOST_CHECK(!gArgs.GetBoolArg(\"-fooo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-fooo\", true));\n\n ResetArgs(\"-foo=0\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=1\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n \/\/ New 0.6 feature: auto-map -nosomething to !-something:\n ResetArgs(\"-nofoo\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo -nofoo\"); \/\/ -nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=1 -nofoo=1\"); \/\/ -nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"-foo=0 -nofoo=0\"); \/\/ -nofoo=0 should win\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n \/\/ New 0.6 feature: treat -- same as -:\n ResetArgs(\"--foo=1\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n\n ResetArgs(\"--nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n\n}\n\nBOOST_AUTO_TEST_CASE(stringarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"eleven\");\n\n ResetArgs(\"-foo -bar\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"\");\n\n ResetArgs(\"-foo=\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"\");\n\n ResetArgs(\"-foo=11\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"11\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"11\");\n\n ResetArgs(\"-foo=eleven\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"eleven\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"eleven\"), \"eleven\");\n\n}\n\nBOOST_AUTO_TEST_CASE(intarg)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 11), 11);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 0), 0);\n\n ResetArgs(\"-foo -bar\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 11), 0);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 0);\n\n ResetArgs(\"-foo=11 -bar=12\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 0), 11);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 12);\n\n ResetArgs(\"-foo=NaN -bar=NotANumber\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", 1), 0);\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 11), 0);\n}\n\nBOOST_AUTO_TEST_CASE(doubledash)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"--foo\");\n BOOST_CHECK_EQUAL(gArgs.GetBoolArg(\"-foo\", false), true);\n\n ResetArgs(\"--foo=verbose --bar=1\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-foo\", \"\"), \"verbose\");\n BOOST_CHECK_EQUAL(gArgs.GetArg(\"-bar\", 0), 1);\n}\n\nBOOST_AUTO_TEST_CASE(boolargno)\n{\n const auto foo = std::make_pair(\"-foo\", ArgsManager::ALLOW_ANY);\n const auto bar = std::make_pair(\"-bar\", ArgsManager::ALLOW_ANY);\n SetupArgs({foo, bar});\n ResetArgs(\"-nofoo\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo=1\");\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo=0\");\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-foo --nofoo\"); \/\/ --nofoo should win\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(!gArgs.GetBoolArg(\"-foo\", false));\n\n ResetArgs(\"-nofoo -foo\"); \/\/ foo always wins:\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", true));\n BOOST_CHECK(gArgs.GetBoolArg(\"-foo\", false));\n}\n\nBOOST_AUTO_TEST_CASE(logargs)\n{\n const auto okaylog_bool = std::make_pair(\"-okaylog-bool\", ArgsManager::ALLOW_BOOL);\n const auto okaylog_negbool = std::make_pair(\"-okaylog-negbool\", ArgsManager::ALLOW_BOOL);\n const auto okaylog = std::make_pair(\"-okaylog\", ArgsManager::ALLOW_ANY);\n const auto dontlog = std::make_pair(\"-dontlog\", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE);\n SetupArgs({okaylog_bool, okaylog_negbool, okaylog, dontlog});\n ResetArgs(\"-okaylog-bool -nookaylog-negbool -okaylog=public -dontlog=private\");\n\n \/\/ Everything logged to debug.log will also append to str\n std::string str;\n auto print_connection = LogInstance().PushBackCallback(\n [&str](const std::string& s) {\n str += s;\n });\n\n \/\/ Log the arguments\n gArgs.LogArgs();\n\n LogInstance().DeleteCallback(print_connection);\n \/\/ Check that what should appear does, and what shouldn't doesn't.\n BOOST_CHECK(str.find(\"Command-line arg: okaylog-bool=\\\"\\\"\") != std::string::npos);\n BOOST_CHECK(str.find(\"Command-line arg: okaylog-negbool=false\") != std::string::npos);\n BOOST_CHECK(str.find(\"Command-line arg: okaylog=\\\"public\\\"\") != std::string::npos);\n BOOST_CHECK(str.find(\"dontlog=****\") != std::string::npos);\n BOOST_CHECK(str.find(\"private\") == std::string::npos);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/===- ChangeAllocations.cpp - Modify %malloc & %free calls -----------------=\/\/\n\/\/\n\/\/ This file defines two passes that convert malloc and free instructions to\n\/\/ calls to and from %malloc & %free function calls. The LowerAllocations\n\/\/ transformation is a target dependant tranformation because it depends on the\n\/\/ size of data types and alignment constraints.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/ChangeAllocations.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/ConstantVals.h\"\n#include \"TransformInternals.h\"\nusing std::vector;\n\n\n\/\/ doInitialization - For the lower allocations pass, this ensures that a\n\/\/ module contains a declaration for a malloc and a free function.\n\/\/\n\/\/ This function is always successful.\n\/\/\nbool LowerAllocations::doInitialization(Module *M) {\n bool Changed = false;\n const MethodType *MallocType = \n MethodType::get(PointerType::get(Type::SByteTy),\n vector(1, Type::UIntTy), false);\n\n SymbolTable *SymTab = M->getSymbolTableSure();\n \n \/\/ Check for a definition of malloc\n if (Value *V = SymTab->lookup(PointerType::get(MallocType), \"malloc\")) {\n MallocMeth = cast(V); \/\/ Yup, got it\n } else { \/\/ Nope, add one\n M->getMethodList().push_back(MallocMeth = new Method(MallocType, false, \n \"malloc\"));\n Changed = true;\n }\n\n const MethodType *FreeType = \n MethodType::get(Type::VoidTy,\n vector(1, PointerType::get(Type::SByteTy)),\n\t\t false);\n\n \/\/ Check for a definition of free\n if (Value *V = SymTab->lookup(PointerType::get(FreeType), \"free\")) {\n FreeMeth = cast(V); \/\/ Yup, got it\n } else { \/\/ Nope, add one\n M->getMethodList().push_back(FreeMeth = new Method(FreeType, false,\"free\"));\n Changed = true;\n }\n\n return Changed;\n}\n\n\/\/ runOnBasicBlock - This method does the actual work of converting\n\/\/ instructions over, assuming that the pass has already been initialized.\n\/\/\nbool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {\n bool Changed = false;\n assert(MallocMeth && FreeMeth && BB && \"Pass not initialized!\");\n\n \/\/ Loop over all of the instructions, looking for malloc or free instructions\n for (unsigned i = 0; i < BB->size(); ++i) {\n BasicBlock::InstListType &BBIL = BB->getInstList();\n if (MallocInst *MI = dyn_cast(*(BBIL.begin()+i))) {\n BBIL.remove(BBIL.begin()+i); \/\/ remove the malloc instr...\n \n const Type *AllocTy =cast(MI->getType())->getElementType();\n \n \/\/ Get the number of bytes to be allocated for one element of the\n \/\/ requested type...\n unsigned Size = DataLayout.getTypeSize(AllocTy);\n \n \/\/ malloc(type) becomes sbyte *malloc(constint)\n Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);\n if (MI->getNumOperands() && Size == 1) {\n MallocArg = MI->getOperand(0); \/\/ Operand * 1 = Operand\n } else if (MI->getNumOperands()) {\n \/\/ Multiply it by the array size if neccesary...\n MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),\n MallocArg);\n BBIL.insert(BBIL.begin()+i++, cast(MallocArg));\n }\n \n \/\/ Create the call to Malloc...\n CallInst *MCall = new CallInst(MallocMeth,\n vector(1, MallocArg));\n BBIL.insert(BBIL.begin()+i, MCall);\n \n \/\/ Create a cast instruction to convert to the right type...\n CastInst *MCast = new CastInst(MCall, MI->getType());\n BBIL.insert(BBIL.begin()+i+1, MCast);\n \n \/\/ Replace all uses of the old malloc inst with the cast inst\n MI->replaceAllUsesWith(MCast);\n delete MI; \/\/ Delete the malloc inst\n Changed = true;\n } else if (FreeInst *FI = dyn_cast(*(BBIL.begin()+i))) {\n BBIL.remove(BB->getInstList().begin()+i);\n \n \/\/ Cast the argument to free into a ubyte*...\n CastInst *MCast = new CastInst(FI->getOperand(0), \n PointerType::get(Type::UByteTy));\n BBIL.insert(BBIL.begin()+i, MCast);\n \n \/\/ Insert a call to the free function...\n CallInst *FCall = new CallInst(FreeMeth,\n vector(1, MCast));\n BBIL.insert(BBIL.begin()+i+1, FCall);\n \n \/\/ Delete the old free instruction\n delete FI;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\nbool RaiseAllocations::doInitialization(Module *M) {\n SymbolTable *ST = M->getSymbolTable();\n if (!ST) return false;\n\n \/\/ If the module has a symbol table, they might be referring to the malloc\n \/\/ and free functions. If this is the case, grab the method pointers that \n \/\/ the module is using.\n \/\/\n \/\/ Lookup %malloc and %free in the symbol table, for later use. If they\n \/\/ don't exist, or are not external, we do not worry about converting calls\n \/\/ to that function into the appropriate instruction.\n \/\/\n const PointerType *MallocType = \/\/ Get the type for malloc\n PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),\n vector(1, Type::UIntTy), false));\n MallocMeth = cast_or_null(ST->lookup(MallocType, \"malloc\"));\n if (MallocMeth && !MallocMeth->isExternal())\n MallocMeth = 0; \/\/ Don't mess with locally defined versions of the fn\n\n const PointerType *FreeType = \/\/ Get the type for free\n PointerType::get(MethodType::get(Type::VoidTy,\n vector(1, PointerType::get(Type::SByteTy)), false));\n FreeMeth = cast_or_null(ST->lookup(FreeType, \"free\"));\n if (FreeMeth && !FreeMeth->isExternal())\n FreeMeth = 0; \/\/ Don't mess with locally defined versions of the fn\n\n return false;\n}\n\n\/\/ doOneCleanupPass - Do one pass over the input method, fixing stuff up.\n\/\/\nbool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {\n bool Changed = false;\n BasicBlock::InstListType &BIL = BB->getInstList();\n\n for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {\n Instruction *I = *BI;\n\n if (CallInst *CI = dyn_cast(I)) {\n if (CI->getCalledValue() == MallocMeth) { \/\/ Replace call to malloc?\n const Type *PtrSByte = PointerType::get(Type::SByteTy);\n MallocInst *MallocI = new MallocInst(PtrSByte, CI->getOperand(1),\n CI->getName());\n CI->setName(\"\");\n BI = BIL.insert(BI, MallocI)+1;\n ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));\n Changed = true;\n continue; \/\/ Skip the ++BI\n } else if (CI->getCalledValue() == FreeMeth) { \/\/ Replace call to free?\n ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));\n Changed = true;\n continue; \/\/ Skip the ++BI\n }\n }\n\n ++BI;\n }\n\n return Changed;\n}\nDon't insert a useless cast\/\/===- ChangeAllocations.cpp - Modify %malloc & %free calls -----------------=\/\/\n\/\/\n\/\/ This file defines two passes that convert malloc and free instructions to\n\/\/ calls to and from %malloc & %free function calls. The LowerAllocations\n\/\/ transformation is a target dependant tranformation because it depends on the\n\/\/ size of data types and alignment constraints.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/ChangeAllocations.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/ConstantVals.h\"\n#include \"TransformInternals.h\"\nusing std::vector;\n\n\n\/\/ doInitialization - For the lower allocations pass, this ensures that a\n\/\/ module contains a declaration for a malloc and a free function.\n\/\/\n\/\/ This function is always successful.\n\/\/\nbool LowerAllocations::doInitialization(Module *M) {\n bool Changed = false;\n const MethodType *MallocType = \n MethodType::get(PointerType::get(Type::SByteTy),\n vector(1, Type::UIntTy), false);\n\n SymbolTable *SymTab = M->getSymbolTableSure();\n \n \/\/ Check for a definition of malloc\n if (Value *V = SymTab->lookup(PointerType::get(MallocType), \"malloc\")) {\n MallocMeth = cast(V); \/\/ Yup, got it\n } else { \/\/ Nope, add one\n M->getMethodList().push_back(MallocMeth = new Method(MallocType, false, \n \"malloc\"));\n Changed = true;\n }\n\n const MethodType *FreeType = \n MethodType::get(Type::VoidTy,\n vector(1, PointerType::get(Type::SByteTy)),\n\t\t false);\n\n \/\/ Check for a definition of free\n if (Value *V = SymTab->lookup(PointerType::get(FreeType), \"free\")) {\n FreeMeth = cast(V); \/\/ Yup, got it\n } else { \/\/ Nope, add one\n M->getMethodList().push_back(FreeMeth = new Method(FreeType, false,\"free\"));\n Changed = true;\n }\n\n return Changed;\n}\n\n\/\/ runOnBasicBlock - This method does the actual work of converting\n\/\/ instructions over, assuming that the pass has already been initialized.\n\/\/\nbool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {\n bool Changed = false;\n assert(MallocMeth && FreeMeth && BB && \"Pass not initialized!\");\n\n \/\/ Loop over all of the instructions, looking for malloc or free instructions\n for (unsigned i = 0; i < BB->size(); ++i) {\n BasicBlock::InstListType &BBIL = BB->getInstList();\n if (MallocInst *MI = dyn_cast(*(BBIL.begin()+i))) {\n BBIL.remove(BBIL.begin()+i); \/\/ remove the malloc instr...\n \n const Type *AllocTy =cast(MI->getType())->getElementType();\n \n \/\/ Get the number of bytes to be allocated for one element of the\n \/\/ requested type...\n unsigned Size = DataLayout.getTypeSize(AllocTy);\n \n \/\/ malloc(type) becomes sbyte *malloc(constint)\n Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);\n if (MI->getNumOperands() && Size == 1) {\n MallocArg = MI->getOperand(0); \/\/ Operand * 1 = Operand\n } else if (MI->getNumOperands()) {\n \/\/ Multiply it by the array size if neccesary...\n MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),\n MallocArg);\n BBIL.insert(BBIL.begin()+i++, cast(MallocArg));\n }\n \n \/\/ Create the call to Malloc...\n CallInst *MCall = new CallInst(MallocMeth,\n vector(1, MallocArg));\n BBIL.insert(BBIL.begin()+i, MCall);\n \n \/\/ Create a cast instruction to convert to the right type...\n CastInst *MCast = new CastInst(MCall, MI->getType());\n BBIL.insert(BBIL.begin()+i+1, MCast);\n \n \/\/ Replace all uses of the old malloc inst with the cast inst\n MI->replaceAllUsesWith(MCast);\n delete MI; \/\/ Delete the malloc inst\n Changed = true;\n } else if (FreeInst *FI = dyn_cast(*(BBIL.begin()+i))) {\n BBIL.remove(BB->getInstList().begin()+i);\n \n \/\/ Cast the argument to free into a ubyte*...\n CastInst *MCast = new CastInst(FI->getOperand(0), \n PointerType::get(Type::UByteTy));\n BBIL.insert(BBIL.begin()+i, MCast);\n \n \/\/ Insert a call to the free function...\n CallInst *FCall = new CallInst(FreeMeth,\n vector(1, MCast));\n BBIL.insert(BBIL.begin()+i+1, FCall);\n \n \/\/ Delete the old free instruction\n delete FI;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\nbool RaiseAllocations::doInitialization(Module *M) {\n SymbolTable *ST = M->getSymbolTable();\n if (!ST) return false;\n\n \/\/ If the module has a symbol table, they might be referring to the malloc\n \/\/ and free functions. If this is the case, grab the method pointers that \n \/\/ the module is using.\n \/\/\n \/\/ Lookup %malloc and %free in the symbol table, for later use. If they\n \/\/ don't exist, or are not external, we do not worry about converting calls\n \/\/ to that function into the appropriate instruction.\n \/\/\n const PointerType *MallocType = \/\/ Get the type for malloc\n PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),\n vector(1, Type::UIntTy), false));\n MallocMeth = cast_or_null(ST->lookup(MallocType, \"malloc\"));\n if (MallocMeth && !MallocMeth->isExternal())\n MallocMeth = 0; \/\/ Don't mess with locally defined versions of the fn\n\n const PointerType *FreeType = \/\/ Get the type for free\n PointerType::get(MethodType::get(Type::VoidTy,\n vector(1, PointerType::get(Type::SByteTy)), false));\n FreeMeth = cast_or_null(ST->lookup(FreeType, \"free\"));\n if (FreeMeth && !FreeMeth->isExternal())\n FreeMeth = 0; \/\/ Don't mess with locally defined versions of the fn\n\n return false;\n}\n\n\/\/ doOneCleanupPass - Do one pass over the input method, fixing stuff up.\n\/\/\nbool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {\n bool Changed = false;\n BasicBlock::InstListType &BIL = BB->getInstList();\n\n for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {\n Instruction *I = *BI;\n\n if (CallInst *CI = dyn_cast(I)) {\n if (CI->getCalledValue() == MallocMeth) { \/\/ Replace call to malloc?\n const Type *PtrSByte = PointerType::get(Type::SByteTy);\n MallocInst *MallocI = new MallocInst(PtrSByte, CI->getOperand(1),\n CI->getName());\n CI->setName(\"\");\n ReplaceInstWithInst(BIL, BI, MallocI);\n Changed = true;\n continue; \/\/ Skip the ++BI\n } else if (CI->getCalledValue() == FreeMeth) { \/\/ Replace call to free?\n ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));\n Changed = true;\n continue; \/\/ Skip the ++BI\n }\n }\n\n ++BI;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Sergey Lisitsyn\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \"preprocessor\/LocallyLinearEmbedding.h\"\n#ifdef HAVE_LAPACK\n#include \"lib\/lapack.h\"\n#include \"lib\/common.h\"\n#include \"lib\/Mathematics.h\"\n#include \"lib\/io.h\"\n#include \"distance\/EuclidianDistance.h\"\n#include \"lib\/Signal.h\"\n\nusing namespace shogun;\n\nCLocallyLinearEmbedding::CLocallyLinearEmbedding() : CSimplePreprocessor(), m_target_dim(1), m_k(1)\n{\n}\n\nCLocallyLinearEmbedding::~CLocallyLinearEmbedding()\n{\n}\n\nbool CLocallyLinearEmbedding::init(CFeatures* data)\n{\n\treturn true;\n}\n\nvoid CLocallyLinearEmbedding::cleanup()\n{\n}\n\nfloat64_t* CLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* data)\n{\n\t\/\/ shorthand for simplefeatures data\n\tCSimpleFeatures* pdata = (CSimpleFeatures*) data;\n\tASSERT(pdata);\n\n\t\/\/ get dimensionality and number of vectors of data\n\tint32_t dim = pdata->get_num_features();\n\tASSERT(m_target_dim<=dim);\n\tint32_t N = pdata->get_num_vectors();\n\tASSERT(m_kget_distance_matrix(&distance_matrix,&N,&N);\n\tdelete distance;\n\n\t\/\/ init matrices to be used\n\tint32_t* neighborhood_matrix = new int32_t[N*m_k];\n\tint32_t* local_neighbors_idxs = new int32_t[N];\n\n\t\/\/ construct neighborhood matrix (contains idxs of neighbors for\n\t\/\/ i-th object in i-th column)\n\tfor (i=0; i feature_matrix = pdata->get_feature_matrix();\n\n\t\t\/\/ compute local feature matrix containing neighbors of i-th vector\n\t\tfor (j=0; jdim)\n\t\t{\n\t\t\t\/\/ compute tr(C)\n\t\t\tfloat64_t trace = 0.0;\n\t\t\tfor (j=0; j features(new_feature_matrix,m_target_dim,N);\n\tpdata->set_feature_matrix(features);\n\n\treturn features.matrix;\n}\n\nfloat64_t* CLocallyLinearEmbedding::apply_to_feature_vector(float64_t* f, int32_t &len)\n{\n\tSG_NOTIMPLEMENTED;\n}\n\n#endif \/* HAVE_LAPACK *\/\nFixes for LLE\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Sergey Lisitsyn\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \"preprocessor\/LocallyLinearEmbedding.h\"\n#ifdef HAVE_LAPACK\n#include \"lib\/lapack.h\"\n#include \"lib\/common.h\"\n#include \"lib\/Mathematics.h\"\n#include \"lib\/io.h\"\n#include \"distance\/EuclidianDistance.h\"\n#include \"lib\/Signal.h\"\n\nusing namespace shogun;\n\nCLocallyLinearEmbedding::CLocallyLinearEmbedding() : CSimplePreprocessor(), m_target_dim(1), m_k(1)\n{\n}\n\nCLocallyLinearEmbedding::~CLocallyLinearEmbedding()\n{\n}\n\nbool CLocallyLinearEmbedding::init(CFeatures* data)\n{\n\treturn true;\n}\n\nvoid CLocallyLinearEmbedding::cleanup()\n{\n}\n\nfloat64_t* CLocallyLinearEmbedding::apply_to_feature_matrix(CFeatures* data)\n{\n\t\/\/ shorthand for simplefeatures data\n\tCSimpleFeatures* pdata = (CSimpleFeatures*) data;\n\tASSERT(pdata);\n\n\t\/\/ get dimensionality and number of vectors of data\n\tint32_t dim = pdata->get_num_features();\n\tASSERT(m_target_dim<=dim);\n\tint32_t N = pdata->get_num_vectors();\n\tASSERT(m_kget_distance_matrix(&distance_matrix,&N,&N);\n\tdelete distance;\n\n\t\/\/ init matrices to be used\n\tint32_t* neighborhood_matrix = new int32_t[N*m_k];\n\tint32_t* local_neighbors_idxs = new int32_t[N];\n\n\t\/\/ construct neighborhood matrix (contains idxs of neighbors for\n\t\/\/ i-th object in i-th column)\n\tfor (i=0; i feature_matrix = pdata->get_feature_matrix();\n\n\tfor (i=0; idim)\n\t\t{\n\t\t\t\/\/ compute tr(C)\n\t\t\tfloat64_t trace = 0.0;\n\t\t\tfor (j=0; j features(new_feature_matrix,m_target_dim,N);\n\tpdata->set_feature_matrix(features);\n\n\treturn features.matrix;\n}\n\nfloat64_t* CLocallyLinearEmbedding::apply_to_feature_vector(float64_t* f, int32_t &len)\n{\n\tSG_NOTIMPLEMENTED;\n}\n\n#endif \/* HAVE_LAPACK *\/\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"AllMetaDefinitions.h\"\n\n#include \"MacroDefinitions.h\"\n#include \"MacroExpansion.h\"\n#include \"MacroExpansions.h\"\n\n#include \"NodeHelpers.h\"\n#include \"..\/ClangHelpers.h\"\n\n#include \"OOModel\/src\/allOOModelNodes.h\"\n\nnamespace CppImport {\n\nAllMetaDefinitions::AllMetaDefinitions(OOModel::Project* root, ClangHelpers& clangHelper,\n\t\t\t\t\t\t\t\t\t const MacroDefinitions& macroDefinitions, MacroExpansions& macroExpansions)\n\t: root_{root}, clang_{clangHelper}, macroDefinitions_{macroDefinitions}, macroExpansions_{macroExpansions},\n\t standardMetaDefinitions_{clangHelper, macroDefinitions, macroExpansions} {}\n\nvoid AllMetaDefinitions::createMetaDef(QList nodes, MacroExpansion* expansion, NodeToCloneMap& mapping,\n\t\t\t\t\t\t\t\t\t\t\t QList& arguments)\n{\n\tif (auto metaDef = standardMetaDefinitions_.createMetaDef(expansion->definition()))\n\t{\n\t\tauto metaDefParent = metaDefinitionParent(expansion->definition());\n\n\t\t\/\/ check whether this expansion is not a potential partial begin macro specialization\n\t\tif (auto beginChild = partialBeginChild(expansion))\n\t\t\thandlePartialBeginSpecialization(metaDefParent, metaDef, expansion, beginChild);\n\t\telse\n\t\t\tstandardMetaDefinitions_.createMetaDefinitionBody(metaDef, nodes, expansion, mapping, arguments);\n\n\t\tclang_.insertDeclarationInFolder(metaDef, expansion->definition()->getMacroInfo()->getDefinitionLoc(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tmetaDefParent);\n\t}\n}\n\nOOModel::Declaration* AllMetaDefinitions::metaDefinitionParent(const clang::MacroDirective* md)\n{\n\tOOModel::Declaration* result = clang_.projectForLocation(md->getLocation());\n\tif (result == clang_.rootProject())\n\t{\n\t\tresult = NodeHelpers::findDeclaration(root_->modules(), \"ExternalMacro\");\n\n\t\tif (!result)\n\t\t{\n\t\t\tresult = new OOModel::Module{\"ExternalMacro\", OOModel::Module::ModuleKind::Folder};\n\t\t\troot_->modules()->append(result);\n\t\t}\n\t}\n\n\tQ_ASSERT(result);\n\treturn result;\n}\n\nvoid AllMetaDefinitions::handlePartialBeginSpecialization(OOModel::Declaration* metaDefParent,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OOModel::MetaDefinition* metaDef,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* expansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* beginChild)\n{\n\tQList statements = macroExpansions_.topLevelNodes(expansion, MacroExpansions::NodeOriginType::Direct);\n\n\tif (!statements.empty())\n\t{\n\t\t\/\/ create a new list containing all the additional statements defined in expansion (the specialization)\n\t\tauto list = new Model::List{};\n\t\tfor (auto stmt : statements) list->append(stmt->clone());\n\n\t\tauto childDef = standardMetaDefinitions_.metaDefinition(beginChild->definition());\n\t\tQ_ASSERT(childDef);\n\n\t\tif (metaDefParent->name().endsWith(\"_CPP\"))\n\t\t{\n\t\t\tQString cppSpecializationSpliceName = \"cppSpecSplice\";\n\n\t\t\tif (!NodeHelpers::findDeclaration(childDef->arguments(), cppSpecializationSpliceName))\n\t\t\t{\n\t\t\t\tchildDef->arguments()->append(new OOModel::FormalMetaArgument{cppSpecializationSpliceName});\n\n\t\t\t\tauto classContext = DCast(childDef->context());\n\t\t\t\tQ_ASSERT(classContext);\n\n\t\t\t\tif (classContext->methods()->size() > 0)\n\t\t\t\t\tclassContext->methods()->last()->items()->append(\n\t\t\t\t\t\t\t\tnew OOModel::ExpressionStatement{new OOModel::ReferenceExpression{cppSpecializationSpliceName}});\n\t\t\t}\n\t\t}\n\n\t\tbeginChild->metaCall()->arguments()->append(list);\n\t\tspecializations_.insert(macroDefinitions_.signature(expansion->definition()), list);\n\t}\n\n\tmetaDef->context()->metaCalls()->append(beginChild->metaCall());\n}\n\nvoid AllMetaDefinitions::applyPartialBeginSpecializationTransformation(MacroExpansion* hExpansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMacroExpansion* cppExpansion)\n{\n\tauto hMetaDefinition = standardMetaDefinitions_.metaDefinition(hExpansion->definition());\n\n\t\/\/ if the metaBindingInput was not yet added to this header xMacro begin meta definition then add it\n\tif (!NodeHelpers::findDeclaration(hMetaDefinition->arguments(), \"metaBindingInput\"))\n\t\thMetaDefinition->arguments()->append(new OOModel::FormalMetaArgument{\"metaBindingInput\"});\n\n\t\/*\n\t * try to find a child meta call of this meta definition and modify it according to the specialization.\n\t * we have to do it over the tree because the inner meta call might originate from an expansion of a\n\t * translation unit prior to this one.\n\t *\/\n\tauto specHash = macroDefinitions_.signature(cppExpansion->definition());\n\n\tauto it = specializations_.find(specHash);\n\tif (it != specializations_.end())\n\t\tfor (auto expr : *hMetaDefinition->context()->metaCalls())\n\t\t\tif (auto metaCall = DCast(expr))\n\t\t\t\tif (auto callee = DCast(metaCall->callee()))\n\t\t\t\t\tif (callee->name().startsWith(\"BEGIN_\"))\n\t\t\t\t\t\tif (!specialized_.contains(metaCall))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ avoid multiple specialization transformations\n\t\t\t\t\t\t\tspecialized_.insert(metaCall);\n\n\t\t\t\t\t\t\t\/\/ apply specialization transformations\n\t\t\t\t\t\t\tmetaCall->arguments()->append((*it)->clone());\n\t\t\t\t\t\t\tmetaCall->arguments()->append(new OOModel::ReferenceExpression{\"metaBindingInput\"});\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n}\n\nvoid AllMetaDefinitions::handleXMacros()\n{\n\tfor (auto expansion : macroExpansions_.expansions())\n\t\tif (!expansion->xMacroChildren().empty())\n\t\t{\n\t\t\t\/\/ case: expansion is a xMacro parent\n\n\t\t\t\/\/ find the .cpp counterpart\n\t\t\tfor (auto node : macroExpansions_.topLevelNodes(expansion, MacroExpansions::NodeOriginType::Transitive))\n\t\t\t\tif (auto other = matchingXMacroExpansion(node))\n\t\t\t\t{\n\t\t\t\t\t\/\/ case: expansion is a .h xMacro parent and other is a .cpp xMacro parent\n\n\t\t\t\t\tapplyPartialBeginSpecializationTransformation(expansion, other);\n\n\t\t\t\t\t\/\/ remove the .cpp xMacro meta call from the original tree\n\t\t\t\t\tNodeHelpers::removeNodeFromParent(other->metaCall(), true);\n\n\t\t\t\t\t\/\/ create the meta call that also contains unbound xMacro children\n\t\t\t\t\tauto merged = new OOModel::MetaCallExpression{};\n\t\t\t\t\tmerged->setCallee(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\tmacroDefinitions_.definitionName(expansion->definition())});\n\n\t\t\t\t\tfor (auto arg : *expansion->metaCall()->arguments())\n\t\t\t\t\t\tmerged->arguments()->append(arg->clone());\n\n\t\t\t\t\t\/\/ create the unbound xMacro children list\n\t\t\t\t\tauto list = new Model::List{};\n\t\t\t\t\tfor (auto xMacroChild : expansion->xMacroChildren())\n\t\t\t\t\t{\n\t\t\t\t\t\tauto unbound = new OOModel::MetaCallExpression{\n\t\t\t\t\t\t\t\t\tmacroDefinitions_.definitionName(xMacroChild->definition())};\n\t\t\t\t\t\tfor (auto arg : *xMacroChild->metaCall()->arguments())\n\t\t\t\t\t\t\tunbound->arguments()->append(arg->clone());\n\n\t\t\t\t\t\tlist->append(unbound);\n\t\t\t\t\t}\n\t\t\t\t\tmerged->arguments()->append(list);\n\n\t\t\t\t\t\/\/ replace the .h xMacro meta call with the newly created merged meta call\n\t\t\t\t\texpansion->metaCall()->parent()->replaceChild(expansion->metaCall(), merged);\n\n\t\t\t\t\tauto metaDef = createXMacroMetaDef(expansion, other);\n\n\t\t\t\t\t\/\/ check whether to insert meta bindings for all xMacro children\n\t\t\t\t\tfor (auto i = 0; i < expansion->xMacroChildren().size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto xMacroChildH = expansion->xMacroChildren().at(i);\n\t\t\t\t\t\tauto xMacroChildCpp = other->xMacroChildren().at(i);\n\n\t\t\t\t\t\tauto unboundName = macroDefinitions_.definitionName(xMacroChildH->definition());\n\n\t\t\t\t\t\tauto binding1 = metaDef->metaBindings()->at(0);\n\t\t\t\t\t\tauto binding2 = metaDef->metaBindings()->at(1);\n\n\t\t\t\t\t\t\/\/ if the binding for this xMacro child already exists do nothing\n\t\t\t\t\t\tif (NodeHelpers::findDeclaration(binding1->mappings(), unboundName)) continue;\n\n\t\t\t\t\t\t\/\/ insert meta bindings for this xMacro child\n\t\t\t\t\t\tauto mapping1 = new OOModel::MetaCallMapping{unboundName};\n\t\t\t\t\t\tmapping1->setValue(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\t\t macroDefinitions_.definitionName(xMacroChildH->definition())});\n\t\t\t\t\t\tbinding1->mappings()->append(mapping1);\n\n\t\t\t\t\t\tauto mapping2 = new OOModel::MetaCallMapping{unboundName};\n\t\t\t\t\t\tmapping2->setValue(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\t\t macroDefinitions_.definitionName(xMacroChildCpp->definition())});\n\t\t\t\t\t\tbinding2->mappings()->append(mapping2);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n}\n\nOOModel::MetaDefinition* AllMetaDefinitions::createXMacroMetaDef(MacroExpansion* hExpansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* cppExpansion)\n{\n\tauto hBaseExpansion = basePartialBegin(hExpansion);\n\tauto cppBaseExpansion = basePartialBegin(cppExpansion);\n\n\tauto mergedMetaDef = xMacroMetaDefinition(hBaseExpansion->definition());\n\tif (!mergedMetaDef)\n\t{\n\t\tauto hBaseMetaDef = standardMetaDefinitions_.metaDefinition(hBaseExpansion->definition());\n\t\tauto cppBaseMetaDef = standardMetaDefinitions_.metaDefinition(cppBaseExpansion->definition());\n\n\t\tmergedMetaDef = hBaseMetaDef->clone();\n\t\tmergedMetaDef->setName(macroDefinitions_.definitionName(hBaseExpansion->definition()));\n\t\txMacrometaDefinitions_.insert(macroDefinitions_.definitionName(hBaseExpansion->definition()), mergedMetaDef);\n\n\t\tfor (auto cppArg : *cppBaseMetaDef->arguments())\n\t\t\tif (!NodeHelpers::findDeclaration(mergedMetaDef->arguments(), cppArg->name()))\n\t\t\t\tmergedMetaDef->arguments()->append(cppArg->clone());\n\n\t\t\/* assumptions:\n\t\t * - the context of hBaseMetaDef is a Module\n\t\t * - the context module of hBaseMetaDef contains exactly one class\n\t\t * - the context of cppBaseMetaDef is a Class\n\t\t * - the merged MetaDefinition is correct if we merge those 2 classes\n\t\t *\/\n\t\tauto mergedClass = DCast(DCast(mergedMetaDef->context())->classes()->first());\n\t\tauto cppBaseClass = DCast(cppBaseMetaDef->context());\n\n\t\tmergeClasses(mergedClass, cppBaseClass);\n\n\t\tQString metaBindingInputName = \"metaBindingInput\";\n\t\tQString declarationSpliceName = \"list1\";\n\t\tQString statementSpliceName = \"list2\";\n\n\t\t\/\/ add an argument for the input to the MetaBindings\n\t\tmergedMetaDef->arguments()->append(new OOModel::FormalMetaArgument{metaBindingInputName});\n\n\t\t\/\/ add splices for the MetaBinding results\n\t\tmergedClass->metaCalls()->append(new OOModel::ReferenceExpression{declarationSpliceName});\n\t\tmergedClass->methods()->last()->items()->append(new OOModel::ExpressionStatement{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew OOModel::ReferenceExpression{statementSpliceName}});\n\n\t\t\/\/ MetaBinding for declarations splice\n\t\tauto declarationsSpliceMetaBinding = new OOModel::MetaBinding{declarationSpliceName};\n\t\tdeclarationsSpliceMetaBinding->setInput(new OOModel::ReferenceExpression{metaBindingInputName});\n\t\tmergedMetaDef->metaBindings()->append(declarationsSpliceMetaBinding);\n\n\t\t\/\/ MetaBinding for statements splice\n\t\tauto statementsSpliceMetaBinding = new OOModel::MetaBinding{statementSpliceName};\n\t\tstatementsSpliceMetaBinding->setInput(new OOModel::ReferenceExpression{metaBindingInputName});\n\t\tmergedMetaDef->metaBindings()->append(statementsSpliceMetaBinding);\n\n\t\t\/\/ add the merged MetaDefinition to the tree\n\t\thBaseMetaDef->parent()->replaceChild(hBaseMetaDef, mergedMetaDef);\n\t}\n\n\tNodeHelpers::removeNodeFromParent(standardMetaDefinitions_.metaDefinition(cppExpansion->definition()), true);\n\tNodeHelpers::removeNodeFromParent(standardMetaDefinitions_.metaDefinition(cppBaseExpansion->definition()), true);\n\n\treturn mergedMetaDef;\n}\n\n\nMacroExpansion* AllMetaDefinitions::basePartialBegin(MacroExpansion* partialBeginExpansion)\n{\n\tQ_ASSERT(macroDefinitions_.isPartialBegin(partialBeginExpansion->definition()));\n\n\tfor (auto child : partialBeginExpansion->children())\n\t\tif (macroDefinitions_.isPartialBegin(child->definition()))\n\t\t return basePartialBegin(child);\n\n\treturn partialBeginExpansion;\n}\n\nvoid AllMetaDefinitions::mergeClasses(OOModel::Class* merged, OOModel::Class* mergee)\n{\n\tfor (auto metaCall : *mergee->metaCalls())\n\t\tmerged->metaCalls()->append(metaCall->clone());\n\n\tfor (auto mergedMethod : *merged->methods())\n\t\tfor (auto mergeeMethod : *mergee->methods())\n\t\t{\n\t\t\tif (mergedMethod->name() == mergeeMethod->name())\n\t\t\t{\n\t\t\t\tfor (auto k = 0; k < mergeeMethod->items()->size(); k++)\n\t\t\t\t\tmergedMethod->items()->append(mergeeMethod->items()->at(k)->clone());\n\n\t\t\t\tmergedMethod->memberInitializers()->clear();\n\t\t\t\tfor (auto memberInitializer : *mergeeMethod->memberInitializers())\n\t\t\t\t\tmergedMethod->memberInitializers()->append(memberInitializer->clone());\n\t\t\t}\n\t\t}\n\n}\n\nMacroExpansion* AllMetaDefinitions::partialBeginChild(MacroExpansion* expansion)\n{\n\tfor (auto child : expansion->children())\n\t\tif (macroDefinitions_.isPartialBegin(child->definition()))\n\t\t\treturn child;\n\n\treturn nullptr;\n}\n\nOOModel::MetaDefinition* AllMetaDefinitions::xMacroMetaDefinition(const clang::MacroDirective* md)\n{\n\tQString h = macroDefinitions_.definitionName(md);\n\n\tauto it = xMacrometaDefinitions_.find(h);\n\n\treturn it != xMacrometaDefinitions_.end() ? *it : nullptr;\n}\n\nMacroExpansion* AllMetaDefinitions::matchingXMacroExpansion(Model::Node* node)\n{\n\tif (auto metaCall = DCast(node))\n\t\tfor (auto expansion : macroExpansions_.expansions())\n\t\t\tif (!expansion->xMacroChildren().empty())\n\t\t\t\tif (expansion->metaCall() == metaCall)\n\t\t\t\t\treturn expansion;\n\n\tfor (auto child : node->children())\n\t\tif (auto expansion = matchingXMacroExpansion(child))\n\t\t\treturn expansion;\n\n\treturn nullptr;\n}\n\n}\nremove condition targetung old model structure\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"AllMetaDefinitions.h\"\n\n#include \"MacroDefinitions.h\"\n#include \"MacroExpansion.h\"\n#include \"MacroExpansions.h\"\n\n#include \"NodeHelpers.h\"\n#include \"..\/ClangHelpers.h\"\n\n#include \"OOModel\/src\/allOOModelNodes.h\"\n\nnamespace CppImport {\n\nAllMetaDefinitions::AllMetaDefinitions(OOModel::Project* root, ClangHelpers& clangHelper,\n\t\t\t\t\t\t\t\t\t const MacroDefinitions& macroDefinitions, MacroExpansions& macroExpansions)\n\t: root_{root}, clang_{clangHelper}, macroDefinitions_{macroDefinitions}, macroExpansions_{macroExpansions},\n\t standardMetaDefinitions_{clangHelper, macroDefinitions, macroExpansions} {}\n\nvoid AllMetaDefinitions::createMetaDef(QList nodes, MacroExpansion* expansion, NodeToCloneMap& mapping,\n\t\t\t\t\t\t\t\t\t\t\t QList& arguments)\n{\n\tif (auto metaDef = standardMetaDefinitions_.createMetaDef(expansion->definition()))\n\t{\n\t\tauto metaDefParent = metaDefinitionParent(expansion->definition());\n\n\t\t\/\/ check whether this expansion is not a potential partial begin macro specialization\n\t\tif (auto beginChild = partialBeginChild(expansion))\n\t\t\thandlePartialBeginSpecialization(metaDefParent, metaDef, expansion, beginChild);\n\t\telse\n\t\t\tstandardMetaDefinitions_.createMetaDefinitionBody(metaDef, nodes, expansion, mapping, arguments);\n\n\t\tclang_.insertDeclarationInFolder(metaDef, expansion->definition()->getMacroInfo()->getDefinitionLoc(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tmetaDefParent);\n\t}\n}\n\nOOModel::Declaration* AllMetaDefinitions::metaDefinitionParent(const clang::MacroDirective* md)\n{\n\tOOModel::Declaration* result = clang_.projectForLocation(md->getLocation());\n\tif (result == clang_.rootProject())\n\t{\n\t\tresult = NodeHelpers::findDeclaration(root_->modules(), \"ExternalMacro\");\n\n\t\tif (!result)\n\t\t{\n\t\t\tresult = new OOModel::Module{\"ExternalMacro\", OOModel::Module::ModuleKind::Folder};\n\t\t\troot_->modules()->append(result);\n\t\t}\n\t}\n\n\tQ_ASSERT(result);\n\treturn result;\n}\n\nvoid AllMetaDefinitions::handlePartialBeginSpecialization(OOModel::Declaration* metaDefParent,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t OOModel::MetaDefinition* metaDef,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* expansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* beginChild)\n{\n\tQList statements = macroExpansions_.topLevelNodes(expansion, MacroExpansions::NodeOriginType::Direct);\n\n\tif (!statements.empty())\n\t{\n\t\t\/\/ create a new list containing all the additional statements defined in expansion (the specialization)\n\t\tauto list = new Model::List{};\n\t\tfor (auto stmt : statements) list->append(stmt->clone());\n\n\t\tauto childDef = standardMetaDefinitions_.metaDefinition(beginChild->definition());\n\t\tQ_ASSERT(childDef);\n\n\t\tQString cppSpecializationSpliceName = \"cppSpecSplice\";\n\n\t\tif (!NodeHelpers::findDeclaration(childDef->arguments(), cppSpecializationSpliceName))\n\t\t{\n\t\t\tchildDef->arguments()->append(new OOModel::FormalMetaArgument{cppSpecializationSpliceName});\n\n\t\t\tauto classContext = DCast(childDef->context());\n\t\t\tQ_ASSERT(classContext);\n\n\t\t\tif (classContext->methods()->size() > 0)\n\t\t\t\tclassContext->methods()->last()->items()->append(\n\t\t\t\t\t\t\tnew OOModel::ExpressionStatement{new OOModel::ReferenceExpression{cppSpecializationSpliceName}});\n\t\t}\n\n\t\tbeginChild->metaCall()->arguments()->append(list);\n\t\tspecializations_.insert(macroDefinitions_.signature(expansion->definition()), list);\n\t}\n\n\tmetaDef->context()->metaCalls()->append(beginChild->metaCall());\n}\n\nvoid AllMetaDefinitions::applyPartialBeginSpecializationTransformation(MacroExpansion* hExpansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMacroExpansion* cppExpansion)\n{\n\tauto hMetaDefinition = standardMetaDefinitions_.metaDefinition(hExpansion->definition());\n\n\t\/\/ if the metaBindingInput was not yet added to this header xMacro begin meta definition then add it\n\tif (!NodeHelpers::findDeclaration(hMetaDefinition->arguments(), \"metaBindingInput\"))\n\t\thMetaDefinition->arguments()->append(new OOModel::FormalMetaArgument{\"metaBindingInput\"});\n\n\t\/*\n\t * try to find a child meta call of this meta definition and modify it according to the specialization.\n\t * we have to do it over the tree because the inner meta call might originate from an expansion of a\n\t * translation unit prior to this one.\n\t *\/\n\tauto specHash = macroDefinitions_.signature(cppExpansion->definition());\n\n\tauto it = specializations_.find(specHash);\n\tif (it != specializations_.end())\n\t\tfor (auto expr : *hMetaDefinition->context()->metaCalls())\n\t\t\tif (auto metaCall = DCast(expr))\n\t\t\t\tif (auto callee = DCast(metaCall->callee()))\n\t\t\t\t\tif (callee->name().startsWith(\"BEGIN_\"))\n\t\t\t\t\t\tif (!specialized_.contains(metaCall))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ avoid multiple specialization transformations\n\t\t\t\t\t\t\tspecialized_.insert(metaCall);\n\n\t\t\t\t\t\t\t\/\/ apply specialization transformations\n\t\t\t\t\t\t\tmetaCall->arguments()->append((*it)->clone());\n\t\t\t\t\t\t\tmetaCall->arguments()->append(new OOModel::ReferenceExpression{\"metaBindingInput\"});\n\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n}\n\nvoid AllMetaDefinitions::handleXMacros()\n{\n\tfor (auto expansion : macroExpansions_.expansions())\n\t\tif (!expansion->xMacroChildren().empty())\n\t\t{\n\t\t\t\/\/ case: expansion is a xMacro parent\n\n\t\t\t\/\/ find the .cpp counterpart\n\t\t\tfor (auto node : macroExpansions_.topLevelNodes(expansion, MacroExpansions::NodeOriginType::Transitive))\n\t\t\t\tif (auto other = matchingXMacroExpansion(node))\n\t\t\t\t{\n\t\t\t\t\t\/\/ case: expansion is a .h xMacro parent and other is a .cpp xMacro parent\n\n\t\t\t\t\tapplyPartialBeginSpecializationTransformation(expansion, other);\n\n\t\t\t\t\t\/\/ remove the .cpp xMacro meta call from the original tree\n\t\t\t\t\tNodeHelpers::removeNodeFromParent(other->metaCall(), true);\n\n\t\t\t\t\t\/\/ create the meta call that also contains unbound xMacro children\n\t\t\t\t\tauto merged = new OOModel::MetaCallExpression{};\n\t\t\t\t\tmerged->setCallee(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\tmacroDefinitions_.definitionName(expansion->definition())});\n\n\t\t\t\t\tfor (auto arg : *expansion->metaCall()->arguments())\n\t\t\t\t\t\tmerged->arguments()->append(arg->clone());\n\n\t\t\t\t\t\/\/ create the unbound xMacro children list\n\t\t\t\t\tauto list = new Model::List{};\n\t\t\t\t\tfor (auto xMacroChild : expansion->xMacroChildren())\n\t\t\t\t\t{\n\t\t\t\t\t\tauto unbound = new OOModel::MetaCallExpression{\n\t\t\t\t\t\t\t\t\tmacroDefinitions_.definitionName(xMacroChild->definition())};\n\t\t\t\t\t\tfor (auto arg : *xMacroChild->metaCall()->arguments())\n\t\t\t\t\t\t\tunbound->arguments()->append(arg->clone());\n\n\t\t\t\t\t\tlist->append(unbound);\n\t\t\t\t\t}\n\t\t\t\t\tmerged->arguments()->append(list);\n\n\t\t\t\t\t\/\/ replace the .h xMacro meta call with the newly created merged meta call\n\t\t\t\t\texpansion->metaCall()->parent()->replaceChild(expansion->metaCall(), merged);\n\n\t\t\t\t\tauto metaDef = createXMacroMetaDef(expansion, other);\n\n\t\t\t\t\t\/\/ check whether to insert meta bindings for all xMacro children\n\t\t\t\t\tfor (auto i = 0; i < expansion->xMacroChildren().size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto xMacroChildH = expansion->xMacroChildren().at(i);\n\t\t\t\t\t\tauto xMacroChildCpp = other->xMacroChildren().at(i);\n\n\t\t\t\t\t\tauto unboundName = macroDefinitions_.definitionName(xMacroChildH->definition());\n\n\t\t\t\t\t\tauto binding1 = metaDef->metaBindings()->at(0);\n\t\t\t\t\t\tauto binding2 = metaDef->metaBindings()->at(1);\n\n\t\t\t\t\t\t\/\/ if the binding for this xMacro child already exists do nothing\n\t\t\t\t\t\tif (NodeHelpers::findDeclaration(binding1->mappings(), unboundName)) continue;\n\n\t\t\t\t\t\t\/\/ insert meta bindings for this xMacro child\n\t\t\t\t\t\tauto mapping1 = new OOModel::MetaCallMapping{unboundName};\n\t\t\t\t\t\tmapping1->setValue(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\t\t macroDefinitions_.definitionName(xMacroChildH->definition())});\n\t\t\t\t\t\tbinding1->mappings()->append(mapping1);\n\n\t\t\t\t\t\tauto mapping2 = new OOModel::MetaCallMapping{unboundName};\n\t\t\t\t\t\tmapping2->setValue(new OOModel::ReferenceExpression{\n\t\t\t\t\t\t\t\t\t\t\t\t\t macroDefinitions_.definitionName(xMacroChildCpp->definition())});\n\t\t\t\t\t\tbinding2->mappings()->append(mapping2);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n}\n\nOOModel::MetaDefinition* AllMetaDefinitions::createXMacroMetaDef(MacroExpansion* hExpansion,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t MacroExpansion* cppExpansion)\n{\n\tauto hBaseExpansion = basePartialBegin(hExpansion);\n\tauto cppBaseExpansion = basePartialBegin(cppExpansion);\n\n\tauto mergedMetaDef = xMacroMetaDefinition(hBaseExpansion->definition());\n\tif (!mergedMetaDef)\n\t{\n\t\tauto hBaseMetaDef = standardMetaDefinitions_.metaDefinition(hBaseExpansion->definition());\n\t\tauto cppBaseMetaDef = standardMetaDefinitions_.metaDefinition(cppBaseExpansion->definition());\n\n\t\tmergedMetaDef = hBaseMetaDef->clone();\n\t\tmergedMetaDef->setName(macroDefinitions_.definitionName(hBaseExpansion->definition()));\n\t\txMacrometaDefinitions_.insert(macroDefinitions_.definitionName(hBaseExpansion->definition()), mergedMetaDef);\n\n\t\tfor (auto cppArg : *cppBaseMetaDef->arguments())\n\t\t\tif (!NodeHelpers::findDeclaration(mergedMetaDef->arguments(), cppArg->name()))\n\t\t\t\tmergedMetaDef->arguments()->append(cppArg->clone());\n\n\t\t\/* assumptions:\n\t\t * - the context of hBaseMetaDef is a Module\n\t\t * - the context module of hBaseMetaDef contains exactly one class\n\t\t * - the context of cppBaseMetaDef is a Class\n\t\t * - the merged MetaDefinition is correct if we merge those 2 classes\n\t\t *\/\n\t\tauto mergedClass = DCast(DCast(mergedMetaDef->context())->classes()->first());\n\t\tauto cppBaseClass = DCast(cppBaseMetaDef->context());\n\n\t\tmergeClasses(mergedClass, cppBaseClass);\n\n\t\tQString metaBindingInputName = \"metaBindingInput\";\n\t\tQString declarationSpliceName = \"list1\";\n\t\tQString statementSpliceName = \"list2\";\n\n\t\t\/\/ add an argument for the input to the MetaBindings\n\t\tmergedMetaDef->arguments()->append(new OOModel::FormalMetaArgument{metaBindingInputName});\n\n\t\t\/\/ add splices for the MetaBinding results\n\t\tmergedClass->metaCalls()->append(new OOModel::ReferenceExpression{declarationSpliceName});\n\t\tmergedClass->methods()->last()->items()->append(new OOModel::ExpressionStatement{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew OOModel::ReferenceExpression{statementSpliceName}});\n\n\t\t\/\/ MetaBinding for declarations splice\n\t\tauto declarationsSpliceMetaBinding = new OOModel::MetaBinding{declarationSpliceName};\n\t\tdeclarationsSpliceMetaBinding->setInput(new OOModel::ReferenceExpression{metaBindingInputName});\n\t\tmergedMetaDef->metaBindings()->append(declarationsSpliceMetaBinding);\n\n\t\t\/\/ MetaBinding for statements splice\n\t\tauto statementsSpliceMetaBinding = new OOModel::MetaBinding{statementSpliceName};\n\t\tstatementsSpliceMetaBinding->setInput(new OOModel::ReferenceExpression{metaBindingInputName});\n\t\tmergedMetaDef->metaBindings()->append(statementsSpliceMetaBinding);\n\n\t\t\/\/ add the merged MetaDefinition to the tree\n\t\thBaseMetaDef->parent()->replaceChild(hBaseMetaDef, mergedMetaDef);\n\t}\n\n\tNodeHelpers::removeNodeFromParent(standardMetaDefinitions_.metaDefinition(cppExpansion->definition()), true);\n\tNodeHelpers::removeNodeFromParent(standardMetaDefinitions_.metaDefinition(cppBaseExpansion->definition()), true);\n\n\treturn mergedMetaDef;\n}\n\n\nMacroExpansion* AllMetaDefinitions::basePartialBegin(MacroExpansion* partialBeginExpansion)\n{\n\tQ_ASSERT(macroDefinitions_.isPartialBegin(partialBeginExpansion->definition()));\n\n\tfor (auto child : partialBeginExpansion->children())\n\t\tif (macroDefinitions_.isPartialBegin(child->definition()))\n\t\t return basePartialBegin(child);\n\n\treturn partialBeginExpansion;\n}\n\nvoid AllMetaDefinitions::mergeClasses(OOModel::Class* merged, OOModel::Class* mergee)\n{\n\tfor (auto metaCall : *mergee->metaCalls())\n\t\tmerged->metaCalls()->append(metaCall->clone());\n\n\tfor (auto mergedMethod : *merged->methods())\n\t\tfor (auto mergeeMethod : *mergee->methods())\n\t\t{\n\t\t\tif (mergedMethod->name() == mergeeMethod->name())\n\t\t\t{\n\t\t\t\tfor (auto k = 0; k < mergeeMethod->items()->size(); k++)\n\t\t\t\t\tmergedMethod->items()->append(mergeeMethod->items()->at(k)->clone());\n\n\t\t\t\tmergedMethod->memberInitializers()->clear();\n\t\t\t\tfor (auto memberInitializer : *mergeeMethod->memberInitializers())\n\t\t\t\t\tmergedMethod->memberInitializers()->append(memberInitializer->clone());\n\t\t\t}\n\t\t}\n\n}\n\nMacroExpansion* AllMetaDefinitions::partialBeginChild(MacroExpansion* expansion)\n{\n\tfor (auto child : expansion->children())\n\t\tif (macroDefinitions_.isPartialBegin(child->definition()))\n\t\t\treturn child;\n\n\treturn nullptr;\n}\n\nOOModel::MetaDefinition* AllMetaDefinitions::xMacroMetaDefinition(const clang::MacroDirective* md)\n{\n\tQString h = macroDefinitions_.definitionName(md);\n\n\tauto it = xMacrometaDefinitions_.find(h);\n\n\treturn it != xMacrometaDefinitions_.end() ? *it : nullptr;\n}\n\nMacroExpansion* AllMetaDefinitions::matchingXMacroExpansion(Model::Node* node)\n{\n\tif (auto metaCall = DCast(node))\n\t\tfor (auto expansion : macroExpansions_.expansions())\n\t\t\tif (!expansion->xMacroChildren().empty())\n\t\t\t\tif (expansion->metaCall() == metaCall)\n\t\t\t\t\treturn expansion;\n\n\tfor (auto child : node->children())\n\t\tif (auto expansion = matchingXMacroExpansion(child))\n\t\t\treturn expansion;\n\n\treturn nullptr;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016, Justin Carpentier, LAAS-CNRS\n *\n * This file is part of eigenpy.\n * eigenpy is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n * eigenpy is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details. You should\n * have received a copy of the GNU Lesser General Public License along\n * with eigenpy. If not, see .\n *\/\n\n#ifndef __eigenpy_memory_hpp__\n#define __eigenpy_memory_hpp__\n\n#include \n\n\/**\n * This section contains a convenience MACRO which allows an easy specialization of\n * Boost Python Object allocator for struct data types containing Eigen objects and requiring\n * strict alignment.\n *\n * This code was proposed as an stackoverflow answer:\n * http:\/\/stackoverflow.com\/questions\/13177573\/how-to-expose-aligned-class-with-boost-python\/29694518\n * Leading to this page proposing the solution:\n * http:\/\/fhtagn.net\/prog\/2015\/04\/16\/quaternion_boost_python.html\n *\n *\/\n#define EIGENPY_DEFINE_STRUCT_ALLOCATOR_SPECIALIZATION(...) \\\nnamespace boost { namespace python { namespace objects { \\\n template<> \\\n struct instance< value_holder<__VA_ARGS__> > \\\n { \\\n typedef value_holder<__VA_ARGS__> Data; \\\n PyObject_VAR_HEAD \\\n PyObject* dict; \\\n PyObject* weakrefs; \\\n instance_holder* objects; \\\n \\\n typedef type_with_alignment< \\\n ::boost::alignment_of::value \\\n >::type align_t; \\\n \\\n union \\\n { \\\n align_t align; \\\n char bytes[sizeof(Data) + 16]; \\\n } storage; \\\n }; \\\n \\\n template \\\n struct make_instance_impl<__VA_ARGS__, value_holder<__VA_ARGS__>, Derived> \\\n { \\\n typedef __VA_ARGS__ T; \\\n typedef value_holder<__VA_ARGS__> Holder; \\\n typedef objects::instance instance_t; \\\n \\\n template \\\n static inline PyObject* execute(Arg & x) \\\n { \\\n BOOST_MPL_ASSERT((mpl::or_, is_union >)); \\\n \\\n PyTypeObject* type = Derived::get_class_object(x); \\\n \\\n if (type == 0) \\\n return python::detail::none(); \\\n \\\n PyObject* raw_result = type->tp_alloc(type, objects::additional_instance_size::value); \\\n if (raw_result != 0) \\\n { \\\n python::detail::decref_guard protect(raw_result); \\\n instance_t* instance = (instance_t*)(void*)raw_result; \\\n Holder* holder = Derived::construct(&instance->storage, (PyObject*)instance, x); \\\n holder->install(raw_result); \\\n \\\n Py_ssize_t holder_offset = reinterpret_cast(holder) \\\n - reinterpret_cast(&instance->storage) \\\n + offsetof(instance_t, storage); \\\n Py_SIZE(instance) = holder_offset; \\\n \\\n protect.cancel(); \\\n } \\\n return raw_result; \\\n } \\\n }; \\\n \\\n template<> \\\n struct make_instance<__VA_ARGS__, value_holder<__VA_ARGS__> > \\\n : make_instance_impl<__VA_ARGS__, value_holder<__VA_ARGS__>, make_instance<__VA_ARGS__,value_holder<__VA_ARGS__> > > \\\n { \\\n template \\\n static inline PyTypeObject* get_class_object(U &) \\\n { \\\n return converter::registered<__VA_ARGS__>::converters.get_class_object(); \\\n } \\\n \\\n static inline value_holder<__VA_ARGS__>* construct(void* storage, PyObject* instance, reference_wrapper<__VA_ARGS__ const> x) \\\n { \\\n void* aligned_storage = reinterpret_cast((reinterpret_cast(storage) & ~(size_t(15))) + 16); \\\n value_holder<__VA_ARGS__>* new_holder = new (aligned_storage) value_holder<__VA_ARGS__>(instance, x); \\\n return new_holder; \\\n } \\\n }; \\\n }}}\n\n#endif \/\/ __eigenpy_memory_hpp__\n[Memory] Remove useless warning\/*\n * Copyright 2016, Justin Carpentier, LAAS-CNRS\n *\n * This file is part of eigenpy.\n * eigenpy is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n * eigenpy is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details. You should\n * have received a copy of the GNU Lesser General Public License along\n * with eigenpy. If not, see .\n *\/\n\n#ifndef __eigenpy_memory_hpp__\n#define __eigenpy_memory_hpp__\n\n#include \n\n\/**\n * This section contains a convenience MACRO which allows an easy specialization of\n * Boost Python Object allocator for struct data types containing Eigen objects and requiring\n * strict alignment.\n *\n * This code was proposed as an stackoverflow answer:\n * http:\/\/stackoverflow.com\/questions\/13177573\/how-to-expose-aligned-class-with-boost-python\/29694518\n * Leading to this page proposing the solution:\n * http:\/\/fhtagn.net\/prog\/2015\/04\/16\/quaternion_boost_python.html\n *\n *\/\n#define EIGENPY_DEFINE_STRUCT_ALLOCATOR_SPECIALIZATION(...) \\\nnamespace boost { namespace python { namespace objects { \\\n template<> \\\n struct instance< value_holder<__VA_ARGS__> > \\\n { \\\n typedef value_holder<__VA_ARGS__> Data; \\\n PyObject_VAR_HEAD \\\n PyObject* dict; \\\n PyObject* weakrefs; \\\n instance_holder* objects; \\\n \\\n typedef type_with_alignment< \\\n ::boost::alignment_of::value \\\n >::type align_t; \\\n \\\n union \\\n { \\\n align_t align; \\\n char bytes[sizeof(Data) + 16]; \\\n } storage; \\\n }; \\\n \\\n template \\\n struct make_instance_impl<__VA_ARGS__, value_holder<__VA_ARGS__>, Derived> \\\n { \\\n typedef __VA_ARGS__ T; \\\n typedef value_holder<__VA_ARGS__> Holder; \\\n typedef objects::instance instance_t; \\\n \\\n template \\\n static inline PyObject* execute(Arg & x) \\\n { \\\n BOOST_MPL_ASSERT((mpl::or_, is_union >)); \\\n \\\n PyTypeObject* type = Derived::get_class_object(x); \\\n \\\n if (type == 0) \\\n return python::detail::none(); \\\n \\\n PyObject* raw_result = type->tp_alloc(type, objects::additional_instance_size::value); \\\n if (raw_result != 0) \\\n { \\\n python::detail::decref_guard protect(raw_result); \\\n instance_t* instance = (instance_t*)(void*)raw_result; \\\n Holder* holder = Derived::construct(&instance->storage, (PyObject*)instance, x); \\\n holder->install(raw_result); \\\n \\\n Py_ssize_t holder_offset = reinterpret_cast(holder) \\\n - reinterpret_cast(&instance->storage) \\\n + static_cast(offsetof(instance_t, storage)); \\\n Py_SIZE(instance) = holder_offset; \\\n \\\n protect.cancel(); \\\n } \\\n return raw_result; \\\n } \\\n }; \\\n \\\n template<> \\\n struct make_instance<__VA_ARGS__, value_holder<__VA_ARGS__> > \\\n : make_instance_impl<__VA_ARGS__, value_holder<__VA_ARGS__>, make_instance<__VA_ARGS__,value_holder<__VA_ARGS__> > > \\\n { \\\n template \\\n static inline PyTypeObject* get_class_object(U &) \\\n { \\\n return converter::registered<__VA_ARGS__>::converters.get_class_object(); \\\n } \\\n \\\n static inline value_holder<__VA_ARGS__>* construct(void* storage, PyObject* instance, reference_wrapper<__VA_ARGS__ const> x) \\\n { \\\n void* aligned_storage = reinterpret_cast((reinterpret_cast(storage) & ~(size_t(15))) + 16); \\\n value_holder<__VA_ARGS__>* new_holder = new (aligned_storage) value_holder<__VA_ARGS__>(instance, x); \\\n return new_holder; \\\n } \\\n }; \\\n }}}\n\n#endif \/\/ __eigenpy_memory_hpp__\n<|endoftext|>"} {"text":"\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/jxl\/modular\/transform\/squeeze.h\"\n\n#include \n\n#include \"lib\/jxl\/base\/data_parallel.h\"\n#include \"lib\/jxl\/common.h\"\n#include \"lib\/jxl\/modular\/modular_image.h\"\n#include \"lib\/jxl\/modular\/transform\/transform.h\"\n\nnamespace jxl {\n\nvoid InvHSqueeze(Image &input, int c, int rc, ThreadPool *pool) {\n const Channel &chin = input.channel[c];\n const Channel &chin_residual = input.channel[rc];\n \/\/ These must be valid since we ran MetaApply already.\n JXL_ASSERT(chin.w == DivCeil(chin.w + chin_residual.w, 2));\n JXL_ASSERT(chin.h == chin_residual.h);\n\n if (chin_residual.w == 0 || chin_residual.h == 0) {\n input.channel[c].hshift--;\n return;\n }\n\n Channel chout(chin.w + chin_residual.w, chin.h, chin.hshift - 1, chin.vshift);\n JXL_DEBUG_V(4,\n \"Undoing horizontal squeeze of channel %i using residuals in \"\n \"channel %i (going from width %zu to %zu)\",\n c, rc, chin.w, chout.w);\n RunOnPool(\n pool, 0, chin.h, ThreadPool::SkipInit(),\n [&](const int task, const int thread) {\n const size_t y = task;\n const pixel_type *JXL_RESTRICT p_residual = chin_residual.Row(y);\n const pixel_type *JXL_RESTRICT p_avg = chin.Row(y);\n pixel_type *JXL_RESTRICT p_out = chout.Row(y);\n\n \/\/ special case for x=0 so we don't have to check x>0\n pixel_type_w avg = p_avg[0];\n pixel_type_w next_avg = (1 < chin.w ? p_avg[1] : avg);\n pixel_type_w tendency = SmoothTendency(avg, avg, next_avg);\n pixel_type_w diff = p_residual[0] + tendency;\n pixel_type_w A =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n pixel_type_w B = A - diff;\n p_out[0] = A;\n p_out[1] = B;\n\n for (size_t x = 1; x < chin_residual.w; x++) {\n pixel_type_w diff_minus_tendency = p_residual[x];\n pixel_type_w avg = p_avg[x];\n pixel_type_w next_avg = (x + 1 < chin.w ? p_avg[x + 1] : avg);\n pixel_type_w left = p_out[(x << 1) - 1];\n pixel_type_w tendency = SmoothTendency(left, avg, next_avg);\n pixel_type_w diff = diff_minus_tendency + tendency;\n pixel_type_w A =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n p_out[x << 1] = A;\n pixel_type_w B = A - diff;\n p_out[(x << 1) + 1] = B;\n }\n if (chout.w & 1) p_out[chout.w - 1] = p_avg[chin.w - 1];\n },\n \"InvHorizontalSqueeze\");\n input.channel[c] = std::move(chout);\n}\n\nvoid InvVSqueeze(Image &input, int c, int rc, ThreadPool *pool) {\n const Channel &chin = input.channel[c];\n const Channel &chin_residual = input.channel[rc];\n \/\/ These must be valid since we ran MetaApply already.\n JXL_ASSERT(chin.h == DivCeil(chin.h + chin_residual.h, 2));\n JXL_ASSERT(chin.w == chin_residual.w);\n\n if (chin_residual.w == 0 || chin_residual.h == 0) {\n input.channel[c].vshift--;\n return;\n }\n\n \/\/ Note: chin.h >= chin_residual.h and at most 1 different.\n Channel chout(chin.w, chin.h + chin_residual.h, chin.hshift, chin.vshift - 1);\n JXL_DEBUG_V(\n 4,\n \"Undoing vertical squeeze of channel %i using residuals in channel \"\n \"%i (going from height %zu to %zu)\",\n c, rc, chin.h, chout.h);\n\n intptr_t onerow_in = chin.plane.PixelsPerRow();\n intptr_t onerow_out = chout.plane.PixelsPerRow();\n constexpr int kColsPerThread = 64;\n RunOnPool(\n pool, 0, DivCeil(chin.w, kColsPerThread), ThreadPool::SkipInit(),\n [&](const int task, const int thread) {\n const size_t x0 = task * kColsPerThread;\n const size_t x1 = std::min((size_t)(task + 1) * kColsPerThread, chin.w);\n \/\/ We only iterate up to std::min(chin_residual.h, chin.h) which is\n \/\/ always chin_residual.h.\n for (size_t y = 0; y < chin_residual.h; y++) {\n const pixel_type *JXL_RESTRICT p_residual = chin_residual.Row(y);\n const pixel_type *JXL_RESTRICT p_avg = chin.Row(y);\n pixel_type *JXL_RESTRICT p_out = chout.Row(y << 1);\n for (size_t x = x0; x < x1; x++) {\n pixel_type_w diff_minus_tendency = p_residual[x];\n pixel_type_w avg = p_avg[x];\n\n pixel_type_w next_avg = avg;\n if (y + 1 < chin.h) next_avg = p_avg[x + onerow_in];\n pixel_type_w top =\n (y > 0 ? p_out[static_cast(x) - onerow_out] : avg);\n pixel_type_w tendency = SmoothTendency(top, avg, next_avg);\n pixel_type_w diff = diff_minus_tendency + tendency;\n pixel_type_w out =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n\n p_out[x] = out;\n \/\/ If the chin_residual.h == chin.h, the output has an even number\n \/\/ of rows so the next line is fine. Otherwise, this loop won't\n \/\/ write to the last output row which is handled separately.\n p_out[x + onerow_out] = p_out[x] - diff;\n }\n }\n },\n \"InvVertSqueeze\");\n\n if (chout.h & 1) {\n size_t y = chin.h - 1;\n const pixel_type *p_avg = chin.Row(y);\n pixel_type *p_out = chout.Row(y << 1);\n for (size_t x = 0; x < chin.w; x++) {\n p_out[x] = p_avg[x];\n }\n }\n input.channel[c] = std::move(chout);\n}\n\nvoid DefaultSqueezeParameters(std::vector *parameters,\n const Image &image) {\n int nb_channels = image.nb_channels;\n \/\/ maybe other transforms have been applied before, but let's assume the first\n \/\/ nb_channels channels still contain the 'main' data\n\n parameters->clear();\n size_t w = image.channel[image.nb_meta_channels].w;\n size_t h = image.channel[image.nb_meta_channels].h;\n JXL_DEBUG_V(7, \"Default squeeze parameters for %zux%zu image: \", w, h);\n\n bool wide =\n (w >\n h); \/\/ do horizontal first on wide images; vertical first on tall images\n\n if (nb_channels > 2 && image.channel[image.nb_meta_channels + 1].w == w &&\n image.channel[image.nb_meta_channels + 1].h == h) {\n \/\/ assume channels 1 and 2 are chroma, and can be squeezed first for 4:2:0\n \/\/ previews\n JXL_DEBUG_V(7, \"(4:2:0 chroma), %zux%zu image\", w, h);\n \/\/ if (!wide) {\n \/\/ parameters.push_back(0+2); \/\/ vertical chroma squeeze\n \/\/ parameters.push_back(image.nb_meta_channels+1);\n \/\/ parameters.push_back(image.nb_meta_channels+2);\n \/\/ }\n SqueezeParams params;\n \/\/ horizontal chroma squeeze\n params.horizontal = true;\n params.in_place = false;\n params.begin_c = image.nb_meta_channels + 1;\n params.num_c = 2;\n parameters->push_back(params);\n params.horizontal = false;\n \/\/ vertical chroma squeeze\n parameters->push_back(params);\n }\n SqueezeParams params;\n params.begin_c = image.nb_meta_channels;\n params.num_c = nb_channels;\n params.in_place = true;\n\n if (!wide) {\n if (h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = false;\n parameters->push_back(params);\n h = (h + 1) \/ 2;\n JXL_DEBUG_V(7, \"Vertical (%zux%zu), \", w, h);\n }\n }\n while (w > JXL_MAX_FIRST_PREVIEW_SIZE || h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n if (w > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = true;\n parameters->push_back(params);\n w = (w + 1) \/ 2;\n JXL_DEBUG_V(7, \"Horizontal (%zux%zu), \", w, h);\n }\n if (h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = false;\n parameters->push_back(params);\n h = (h + 1) \/ 2;\n JXL_DEBUG_V(7, \"Vertical (%zux%zu), \", w, h);\n }\n }\n JXL_DEBUG_V(7, \"that's it\");\n}\n\nStatus CheckMetaSqueezeParams(const std::vector ¶meters,\n int num_channels) {\n for (size_t i = 0; i < parameters.size(); i++) {\n int c1 = parameters[i].begin_c;\n int c2 = parameters[i].begin_c + parameters[i].num_c - 1;\n if (c1 < 0 || c1 > num_channels || c2 < 0 || c2 >= num_channels ||\n c2 < c1) {\n return JXL_FAILURE(\"Invalid channel range\");\n }\n }\n return true;\n}\n\nStatus MetaSqueeze(Image &image, std::vector *parameters) {\n if (parameters->empty()) {\n DefaultSqueezeParameters(parameters, image);\n }\n JXL_RETURN_IF_ERROR(\n CheckMetaSqueezeParams(*parameters, image.channel.size()));\n\n for (size_t i = 0; i < parameters->size(); i++) {\n bool horizontal = (*parameters)[i].horizontal;\n bool in_place = (*parameters)[i].in_place;\n uint32_t beginc = (*parameters)[i].begin_c;\n uint32_t endc = (*parameters)[i].begin_c + (*parameters)[i].num_c - 1;\n\n uint32_t offset;\n if (in_place) {\n offset = endc + 1;\n } else {\n offset = image.channel.size();\n }\n for (uint32_t c = beginc; c <= endc; c++) {\n if (image.channel[c].hshift > 30 || image.channel[c].vshift > 30) {\n return JXL_FAILURE(\"Too many squeezes: shift > 30\");\n }\n size_t w = image.channel[c].w;\n size_t h = image.channel[c].h;\n if (horizontal) {\n image.channel[c].w = (w + 1) \/ 2;\n image.channel[c].hshift++;\n w = w - (w + 1) \/ 2;\n } else {\n image.channel[c].h = (h + 1) \/ 2;\n image.channel[c].vshift++;\n h = h - (h + 1) \/ 2;\n }\n image.channel[c].shrink();\n Channel dummy(w, h);\n dummy.hshift = image.channel[c].hshift;\n dummy.vshift = image.channel[c].vshift;\n\n image.channel.insert(image.channel.begin() + offset + (c - beginc),\n std::move(dummy));\n }\n }\n return true;\n}\n\nStatus InvSqueeze(Image &input, std::vector parameters,\n ThreadPool *pool) {\n if (parameters.empty()) {\n DefaultSqueezeParameters(¶meters, input);\n }\n JXL_RETURN_IF_ERROR(CheckMetaSqueezeParams(parameters, input.channel.size()));\n\n for (int i = parameters.size() - 1; i >= 0; i--) {\n bool horizontal = parameters[i].horizontal;\n bool in_place = parameters[i].in_place;\n uint32_t beginc = parameters[i].begin_c;\n uint32_t endc = parameters[i].begin_c + parameters[i].num_c - 1;\n uint32_t offset;\n if (in_place) {\n offset = endc + 1;\n } else {\n offset = input.channel.size() + beginc - endc - 1;\n }\n for (uint32_t c = beginc; c <= endc; c++) {\n uint32_t rc = offset + c - beginc;\n if ((input.channel[c].w < input.channel[rc].w) ||\n (input.channel[c].h < input.channel[rc].h)) {\n return JXL_FAILURE(\"Corrupted squeeze transform\");\n }\n if (horizontal) {\n InvHSqueeze(input, c, rc, pool);\n } else {\n InvVSqueeze(input, c, rc, pool);\n }\n }\n input.channel.erase(input.channel.begin() + offset,\n input.channel.begin() + offset + (endc - beginc + 1));\n }\n return true;\n}\n\n} \/\/ namespace jxl\nfix default squeeze params\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/jxl\/modular\/transform\/squeeze.h\"\n\n#include \n\n#include \"lib\/jxl\/base\/data_parallel.h\"\n#include \"lib\/jxl\/common.h\"\n#include \"lib\/jxl\/modular\/modular_image.h\"\n#include \"lib\/jxl\/modular\/transform\/transform.h\"\n\nnamespace jxl {\n\nvoid InvHSqueeze(Image &input, int c, int rc, ThreadPool *pool) {\n const Channel &chin = input.channel[c];\n const Channel &chin_residual = input.channel[rc];\n \/\/ These must be valid since we ran MetaApply already.\n JXL_ASSERT(chin.w == DivCeil(chin.w + chin_residual.w, 2));\n JXL_ASSERT(chin.h == chin_residual.h);\n\n if (chin_residual.w == 0 || chin_residual.h == 0) {\n input.channel[c].hshift--;\n return;\n }\n\n Channel chout(chin.w + chin_residual.w, chin.h, chin.hshift - 1, chin.vshift);\n JXL_DEBUG_V(4,\n \"Undoing horizontal squeeze of channel %i using residuals in \"\n \"channel %i (going from width %zu to %zu)\",\n c, rc, chin.w, chout.w);\n RunOnPool(\n pool, 0, chin.h, ThreadPool::SkipInit(),\n [&](const int task, const int thread) {\n const size_t y = task;\n const pixel_type *JXL_RESTRICT p_residual = chin_residual.Row(y);\n const pixel_type *JXL_RESTRICT p_avg = chin.Row(y);\n pixel_type *JXL_RESTRICT p_out = chout.Row(y);\n\n \/\/ special case for x=0 so we don't have to check x>0\n pixel_type_w avg = p_avg[0];\n pixel_type_w next_avg = (1 < chin.w ? p_avg[1] : avg);\n pixel_type_w tendency = SmoothTendency(avg, avg, next_avg);\n pixel_type_w diff = p_residual[0] + tendency;\n pixel_type_w A =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n pixel_type_w B = A - diff;\n p_out[0] = A;\n p_out[1] = B;\n\n for (size_t x = 1; x < chin_residual.w; x++) {\n pixel_type_w diff_minus_tendency = p_residual[x];\n pixel_type_w avg = p_avg[x];\n pixel_type_w next_avg = (x + 1 < chin.w ? p_avg[x + 1] : avg);\n pixel_type_w left = p_out[(x << 1) - 1];\n pixel_type_w tendency = SmoothTendency(left, avg, next_avg);\n pixel_type_w diff = diff_minus_tendency + tendency;\n pixel_type_w A =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n p_out[x << 1] = A;\n pixel_type_w B = A - diff;\n p_out[(x << 1) + 1] = B;\n }\n if (chout.w & 1) p_out[chout.w - 1] = p_avg[chin.w - 1];\n },\n \"InvHorizontalSqueeze\");\n input.channel[c] = std::move(chout);\n}\n\nvoid InvVSqueeze(Image &input, int c, int rc, ThreadPool *pool) {\n const Channel &chin = input.channel[c];\n const Channel &chin_residual = input.channel[rc];\n \/\/ These must be valid since we ran MetaApply already.\n JXL_ASSERT(chin.h == DivCeil(chin.h + chin_residual.h, 2));\n JXL_ASSERT(chin.w == chin_residual.w);\n\n if (chin_residual.w == 0 || chin_residual.h == 0) {\n input.channel[c].vshift--;\n return;\n }\n\n \/\/ Note: chin.h >= chin_residual.h and at most 1 different.\n Channel chout(chin.w, chin.h + chin_residual.h, chin.hshift, chin.vshift - 1);\n JXL_DEBUG_V(\n 4,\n \"Undoing vertical squeeze of channel %i using residuals in channel \"\n \"%i (going from height %zu to %zu)\",\n c, rc, chin.h, chout.h);\n\n intptr_t onerow_in = chin.plane.PixelsPerRow();\n intptr_t onerow_out = chout.plane.PixelsPerRow();\n constexpr int kColsPerThread = 64;\n RunOnPool(\n pool, 0, DivCeil(chin.w, kColsPerThread), ThreadPool::SkipInit(),\n [&](const int task, const int thread) {\n const size_t x0 = task * kColsPerThread;\n const size_t x1 = std::min((size_t)(task + 1) * kColsPerThread, chin.w);\n \/\/ We only iterate up to std::min(chin_residual.h, chin.h) which is\n \/\/ always chin_residual.h.\n for (size_t y = 0; y < chin_residual.h; y++) {\n const pixel_type *JXL_RESTRICT p_residual = chin_residual.Row(y);\n const pixel_type *JXL_RESTRICT p_avg = chin.Row(y);\n pixel_type *JXL_RESTRICT p_out = chout.Row(y << 1);\n for (size_t x = x0; x < x1; x++) {\n pixel_type_w diff_minus_tendency = p_residual[x];\n pixel_type_w avg = p_avg[x];\n\n pixel_type_w next_avg = avg;\n if (y + 1 < chin.h) next_avg = p_avg[x + onerow_in];\n pixel_type_w top =\n (y > 0 ? p_out[static_cast(x) - onerow_out] : avg);\n pixel_type_w tendency = SmoothTendency(top, avg, next_avg);\n pixel_type_w diff = diff_minus_tendency + tendency;\n pixel_type_w out =\n ((avg * 2) + diff + (diff > 0 ? -(diff & 1) : (diff & 1))) >> 1;\n\n p_out[x] = out;\n \/\/ If the chin_residual.h == chin.h, the output has an even number\n \/\/ of rows so the next line is fine. Otherwise, this loop won't\n \/\/ write to the last output row which is handled separately.\n p_out[x + onerow_out] = p_out[x] - diff;\n }\n }\n },\n \"InvVertSqueeze\");\n\n if (chout.h & 1) {\n size_t y = chin.h - 1;\n const pixel_type *p_avg = chin.Row(y);\n pixel_type *p_out = chout.Row(y << 1);\n for (size_t x = 0; x < chin.w; x++) {\n p_out[x] = p_avg[x];\n }\n }\n input.channel[c] = std::move(chout);\n}\n\nvoid DefaultSqueezeParameters(std::vector *parameters,\n const Image &image) {\n int nb_channels = image.channel.size() - image.nb_meta_channels;\n\n parameters->clear();\n size_t w = image.channel[image.nb_meta_channels].w;\n size_t h = image.channel[image.nb_meta_channels].h;\n JXL_DEBUG_V(7, \"Default squeeze parameters for %zux%zu image: \", w, h);\n\n bool wide =\n (w >\n h); \/\/ do horizontal first on wide images; vertical first on tall images\n\n if (nb_channels > 2 && image.channel[image.nb_meta_channels + 1].w == w &&\n image.channel[image.nb_meta_channels + 1].h == h) {\n \/\/ assume channels 1 and 2 are chroma, and can be squeezed first for 4:2:0\n \/\/ previews\n JXL_DEBUG_V(7, \"(4:2:0 chroma), %zux%zu image\", w, h);\n \/\/ if (!wide) {\n \/\/ parameters.push_back(0+2); \/\/ vertical chroma squeeze\n \/\/ parameters.push_back(image.nb_meta_channels+1);\n \/\/ parameters.push_back(image.nb_meta_channels+2);\n \/\/ }\n SqueezeParams params;\n \/\/ horizontal chroma squeeze\n params.horizontal = true;\n params.in_place = false;\n params.begin_c = image.nb_meta_channels + 1;\n params.num_c = 2;\n parameters->push_back(params);\n params.horizontal = false;\n \/\/ vertical chroma squeeze\n parameters->push_back(params);\n }\n SqueezeParams params;\n params.begin_c = image.nb_meta_channels;\n params.num_c = nb_channels;\n params.in_place = true;\n\n if (!wide) {\n if (h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = false;\n parameters->push_back(params);\n h = (h + 1) \/ 2;\n JXL_DEBUG_V(7, \"Vertical (%zux%zu), \", w, h);\n }\n }\n while (w > JXL_MAX_FIRST_PREVIEW_SIZE || h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n if (w > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = true;\n parameters->push_back(params);\n w = (w + 1) \/ 2;\n JXL_DEBUG_V(7, \"Horizontal (%zux%zu), \", w, h);\n }\n if (h > JXL_MAX_FIRST_PREVIEW_SIZE) {\n params.horizontal = false;\n parameters->push_back(params);\n h = (h + 1) \/ 2;\n JXL_DEBUG_V(7, \"Vertical (%zux%zu), \", w, h);\n }\n }\n JXL_DEBUG_V(7, \"that's it\");\n}\n\nStatus CheckMetaSqueezeParams(const std::vector ¶meters,\n int num_channels) {\n for (size_t i = 0; i < parameters.size(); i++) {\n int c1 = parameters[i].begin_c;\n int c2 = parameters[i].begin_c + parameters[i].num_c - 1;\n if (c1 < 0 || c1 > num_channels || c2 < 0 || c2 >= num_channels ||\n c2 < c1) {\n return JXL_FAILURE(\"Invalid channel range\");\n }\n }\n return true;\n}\n\nStatus MetaSqueeze(Image &image, std::vector *parameters) {\n if (parameters->empty()) {\n DefaultSqueezeParameters(parameters, image);\n }\n JXL_RETURN_IF_ERROR(\n CheckMetaSqueezeParams(*parameters, image.channel.size()));\n\n for (size_t i = 0; i < parameters->size(); i++) {\n bool horizontal = (*parameters)[i].horizontal;\n bool in_place = (*parameters)[i].in_place;\n uint32_t beginc = (*parameters)[i].begin_c;\n uint32_t endc = (*parameters)[i].begin_c + (*parameters)[i].num_c - 1;\n\n uint32_t offset;\n if (in_place) {\n offset = endc + 1;\n } else {\n offset = image.channel.size();\n }\n for (uint32_t c = beginc; c <= endc; c++) {\n if (image.channel[c].hshift > 30 || image.channel[c].vshift > 30) {\n return JXL_FAILURE(\"Too many squeezes: shift > 30\");\n }\n size_t w = image.channel[c].w;\n size_t h = image.channel[c].h;\n if (horizontal) {\n image.channel[c].w = (w + 1) \/ 2;\n image.channel[c].hshift++;\n w = w - (w + 1) \/ 2;\n } else {\n image.channel[c].h = (h + 1) \/ 2;\n image.channel[c].vshift++;\n h = h - (h + 1) \/ 2;\n }\n image.channel[c].shrink();\n Channel dummy(w, h);\n dummy.hshift = image.channel[c].hshift;\n dummy.vshift = image.channel[c].vshift;\n\n image.channel.insert(image.channel.begin() + offset + (c - beginc),\n std::move(dummy));\n }\n }\n return true;\n}\n\nStatus InvSqueeze(Image &input, std::vector parameters,\n ThreadPool *pool) {\n if (parameters.empty()) {\n DefaultSqueezeParameters(¶meters, input);\n }\n JXL_RETURN_IF_ERROR(CheckMetaSqueezeParams(parameters, input.channel.size()));\n\n for (int i = parameters.size() - 1; i >= 0; i--) {\n bool horizontal = parameters[i].horizontal;\n bool in_place = parameters[i].in_place;\n uint32_t beginc = parameters[i].begin_c;\n uint32_t endc = parameters[i].begin_c + parameters[i].num_c - 1;\n uint32_t offset;\n if (in_place) {\n offset = endc + 1;\n } else {\n offset = input.channel.size() + beginc - endc - 1;\n }\n for (uint32_t c = beginc; c <= endc; c++) {\n uint32_t rc = offset + c - beginc;\n if ((input.channel[c].w < input.channel[rc].w) ||\n (input.channel[c].h < input.channel[rc].h)) {\n return JXL_FAILURE(\"Corrupted squeeze transform\");\n }\n if (horizontal) {\n InvHSqueeze(input, c, rc, pool);\n } else {\n InvVSqueeze(input, c, rc, pool);\n }\n }\n input.channel.erase(input.channel.begin() + offset,\n input.channel.begin() + offset + (endc - beginc + 1));\n }\n return true;\n}\n\n} \/\/ namespace jxl\n<|endoftext|>"} {"text":"#include \"math\/Compression.h\"\n\n#include \"Test.h\"\n\nusing namespace PR;\n\nPR_BEGIN_TESTCASE(Compression)\nPR_TEST(\"unorm16\")\n{\n\tfloat f = 0.5f;\n\tunorm16 s = to_unorm16(f);\n\tfloat r = from_unorm16(s);\n\n\tPR_CHECK_NEARLY_EQ(r, f);\n}\n\nPR_TEST(\"snorm16\")\n{\n\tfloat f = -0.25f;\n\tsnorm16 s = to_snorm16(f);\n\tfloat r = from_snorm16(s);\n\n\tPR_CHECK_NEARLY_EQ(r, f);\n}\n\nPR_TEST(\"oct 1\")\n{\n\tVector3f d(1, 0, 0);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_TEST(\"oct 2\")\n{\n\tVector3f d(0, -1, 0);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_TEST(\"oct 3\")\n{\n\tVector3f d(0.707107f, 0, 0.707107f);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_END_TESTCASE()\n\n\/\/ MAIN\nPRT_BEGIN_MAIN\nPRT_TESTCASE(Compression);\nPRT_END_MAINfixed test error#include \"math\/Compression.h\"\n\n#define PRT_EPSILON (0.00001f)\n#include \"Test.h\"\n\nusing namespace PR;\n\nPR_BEGIN_TESTCASE(Compression)\nPR_TEST(\"unorm16\")\n{\n\tfloat f = 0.5f;\n\tunorm16 s = to_unorm16(f);\n\tfloat r = from_unorm16(s);\n\n\tPR_CHECK_NEARLY_EQ(r, f);\n}\n\nPR_TEST(\"snorm16\")\n{\n\tfloat f = -0.25f;\n\tsnorm16 s = to_snorm16(f);\n\tfloat r = from_snorm16(s);\n\n\tPR_CHECK_NEARLY_EQ(r, f);\n}\n\nPR_TEST(\"oct 1\")\n{\n\tVector3f d(1, 0, 0);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_TEST(\"oct 2\")\n{\n\tVector3f d(0, -1, 0);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_TEST(\"oct 3\")\n{\n\tVector3f d(0.707107f, 0, 0.707107f);\n\tVector2f o = to_oct(d);\n\tVector3f r = from_oct(o);\n\n\tPR_CHECK_NEARLY_EQ(r, d);\n}\n\nPR_END_TESTCASE()\n\n\/\/ MAIN\nPRT_BEGIN_MAIN\nPRT_TESTCASE(Compression);\nPRT_END_MAIN<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"configurator\/configurator.hpp\"\n\n#include \"tests\/environment.hpp\"\n#include \"tests\/filter.hpp\"\n\nusing std::list;\nusing std::string;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ A simple test event listener that makes sure to resume the clock\n\/\/ after each test even if the previous test had a partial result\n\/\/ (i.e., an ASSERT_* failed).\nclass ClockTestEventListener : public ::testing::EmptyTestEventListener\n{\npublic:\n virtual void OnTestEnd(const ::testing::TestInfo&)\n {\n if (process::Clock::paused()) {\n process::Clock::resume();\n }\n }\n};\n\n\n\/\/ Returns true if we should enable the provided test. Similar to how\n\/\/ tests can be disabled using the 'DISABLED_' prefix on a test case\n\/\/ name or test name, we use 'ROOT_' and 'CGROUPS_' prefixes to only\n\/\/ enable tests based on whether or not the current user is root or\n\/\/ cgroups support is detected. Both 'ROOT_' and 'CGROUPS_' can be\n\/\/ composed in any order, but must come after 'DISABLED_'. In\n\/\/ addition, we disable tests that attempt to use the CgroupsIsolator\n\/\/ type parameter if the current user is not root or cgroups is not\n\/\/ supported.\n\/\/ TODO(benh): Provide a generic way to enable\/disable tests by\n\/\/ registering \"filter\" functions.\nstatic bool enable(const ::testing::TestInfo& test)\n{\n \/\/ First check the test case name and test name.\n list names;\n names.push_back(test.test_case_name());\n names.push_back(test.name());\n\n foreach (const string& name, names) {\n if (strings::contains(name, \"ROOT_\") && os::user() != \"root\") {\n return false;\n }\n\n if (strings::contains(name, \"CGROUPS_\") && !os::exists(\"\/proc\/cgroups\")) {\n return false;\n }\n }\n\n \/\/ Now check the type parameter.\n if (test.type_param() != NULL) {\n const string& type = test.type_param();\n if (strings::contains(type, \"CgroupsIsolator\") &&\n (os::user() != \"root\" || !os::exists(\"\/proc\/cgroups\"))) {\n return false;\n }\n }\n\n return true;\n}\n\n\n\/\/ We use the constructor to setup specific tests by updating the\n\/\/ gtest filter. We do this so that we can selectively run tests that\n\/\/ require root or specific OS support (e.g., cgroups). Note that this\n\/\/ should not effect any other filters that have been put in place\n\/\/ either on the command line or via an environment variable.\n\/\/ N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.\nEnvironment::Environment()\n{\n \/\/ First we split the current filter into positive and negative\n \/\/ components (which are separated by a '-').\n const string& filter = ::testing::GTEST_FLAG(filter);\n string positive;\n string negative;\n\n size_t dash = filter.find('-');\n if (dash != string::npos) {\n positive = filter.substr(0, dash);\n negative = filter.substr(dash + 1);\n } else {\n positive = filter;\n }\n\n \/\/ Use universal filter if not specified.\n if (positive.empty()) {\n positive = \"*\";\n }\n\n \/\/ Construct the filter string to handle system or platform specific tests.\n ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();\n for (int i = 0; i < unitTest->total_test_case_count(); i++) {\n const ::testing::TestCase* testCase = unitTest->GetTestCase(i);\n for (int j = 0; j < testCase->total_test_count(); j++) {\n const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);\n\n if (!enable(*testCase->GetTestInfo(j))) {\n \/\/ Append 'TestCase.TestName:'.\n negative.append(testInfo->test_case_name());\n negative.append(\".\");\n negative.append(testInfo->name());\n negative.append(\":\");\n }\n }\n }\n\n \/\/ Now update the gtest flag.\n ::testing::GTEST_FLAG(filter) = positive + \"-\" + negative;\n}\n\n\nvoid Environment::SetUp()\n{\n \/\/ Clear any MESOS_ environment variables so they don't affect our tests.\n Configurator::clearMesosEnvironmentVars();\n\n \/\/ Add our test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(new FilterTestEventListener());\n listeners.Append(new ClockTestEventListener());\n}\n\n\nvoid Environment::TearDown() {}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\nFixed a bug where a filter specified via --gtest_filter (or GTEST_FILTER) was not properly included in the filter we construct based on the environment.\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"configurator\/configurator.hpp\"\n\n#include \"tests\/environment.hpp\"\n#include \"tests\/filter.hpp\"\n\nusing std::list;\nusing std::string;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ A simple test event listener that makes sure to resume the clock\n\/\/ after each test even if the previous test had a partial result\n\/\/ (i.e., an ASSERT_* failed).\nclass ClockTestEventListener : public ::testing::EmptyTestEventListener\n{\npublic:\n virtual void OnTestEnd(const ::testing::TestInfo&)\n {\n if (process::Clock::paused()) {\n process::Clock::resume();\n }\n }\n};\n\n\n\/\/ Returns true if we should enable the provided test. Similar to how\n\/\/ tests can be disabled using the 'DISABLED_' prefix on a test case\n\/\/ name or test name, we use 'ROOT_' and 'CGROUPS_' prefixes to only\n\/\/ enable tests based on whether or not the current user is root or\n\/\/ cgroups support is detected. Both 'ROOT_' and 'CGROUPS_' can be\n\/\/ composed in any order, but must come after 'DISABLED_'. In\n\/\/ addition, we disable tests that attempt to use the CgroupsIsolator\n\/\/ type parameter if the current user is not root or cgroups is not\n\/\/ supported.\n\/\/ TODO(benh): Provide a generic way to enable\/disable tests by\n\/\/ registering \"filter\" functions.\nstatic bool enable(const ::testing::TestInfo& test)\n{\n \/\/ First check the test case name and test name.\n list names;\n names.push_back(test.test_case_name());\n names.push_back(test.name());\n\n foreach (const string& name, names) {\n if (strings::contains(name, \"ROOT_\") && os::user() != \"root\") {\n return false;\n }\n\n if (strings::contains(name, \"CGROUPS_\") && !os::exists(\"\/proc\/cgroups\")) {\n return false;\n }\n }\n\n \/\/ Now check the type parameter.\n if (test.type_param() != NULL) {\n const string& type = test.type_param();\n if (strings::contains(type, \"CgroupsIsolator\") &&\n (os::user() != \"root\" || !os::exists(\"\/proc\/cgroups\"))) {\n return false;\n }\n }\n\n return true;\n}\n\n\n\/\/ We use the constructor to setup specific tests by updating the\n\/\/ gtest filter. We do this so that we can selectively run tests that\n\/\/ require root or specific OS support (e.g., cgroups). Note that this\n\/\/ should not effect any other filters that have been put in place\n\/\/ either on the command line or via an environment variable.\n\/\/ N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.\nEnvironment::Environment()\n{\n \/\/ First we split the current filter into enabled and disabled tests\n \/\/ (which are separated by a '-').\n const string& filter = ::testing::GTEST_FLAG(filter);\n string enabled;\n string disabled;\n\n size_t dash = filter.find('-');\n if (dash != string::npos) {\n enabled = filter.substr(0, dash);\n disabled = filter.substr(dash + 1);\n } else {\n enabled = filter;\n }\n\n \/\/ Use universal filter if not specified.\n if (enabled.empty()) {\n enabled = \"*\";\n }\n\n \/\/ Ensure disabled tests end with \":\" separator before we add more.\n if (!disabled.empty() && !strings::endsWith(disabled, \":\")) {\n disabled += \":\";\n }\n\n \/\/ Construct the filter string to handle system or platform specific tests.\n ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();\n for (int i = 0; i < unitTest->total_test_case_count(); i++) {\n const ::testing::TestCase* testCase = unitTest->GetTestCase(i);\n for (int j = 0; j < testCase->total_test_count(); j++) {\n const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);\n\n if (!enable(*testCase->GetTestInfo(j))) {\n \/\/ Append 'TestCase.TestName:'.\n disabled.append(testInfo->test_case_name());\n disabled.append(\".\");\n disabled.append(testInfo->name());\n disabled.append(\":\");\n }\n }\n }\n\n \/\/ Now update the gtest flag.\n ::testing::GTEST_FLAG(filter) = enabled + \"-\" + disabled;\n}\n\n\nvoid Environment::SetUp()\n{\n \/\/ Clear any MESOS_ environment variables so they don't affect our tests.\n Configurator::clearMesosEnvironmentVars();\n\n \/\/ Add our test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(new FilterTestEventListener());\n listeners.Append(new ClockTestEventListener());\n}\n\n\nvoid Environment::TearDown() {}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n<|endoftext|>"} {"text":"\/* OpenSceneGraph example, osgdrawinstanced.\r\n*\r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n*\r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\/\/\r\n\/\/ This code is copyright (c) 2008 Skew Matrix Software LLC. You may use\r\n\/\/ the code under the licensing terms described above.\r\n\/\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n\r\nvoid\r\ncreateDAIGeometry( osg::Geometry& geom, int nInstances=1 )\r\n{\r\n const float halfDimX( .5 );\r\n const float halfDimZ( .5 );\r\n\r\n osg::Vec3Array* v = new osg::Vec3Array;\r\n v->resize( 4 );\r\n geom.setVertexArray( v );\r\n\r\n \/\/ Geometry for a single quad.\r\n (*v)[ 0 ] = osg::Vec3( -halfDimX, 0., -halfDimZ );\r\n (*v)[ 1 ] = osg::Vec3( halfDimX, 0., -halfDimZ );\r\n (*v)[ 2 ] = osg::Vec3( halfDimX, 0., halfDimZ );\r\n (*v)[ 3 ] = osg::Vec3( -halfDimX, 0., halfDimZ );\r\n\r\n \/\/ Use the DrawArraysInstanced PrimitiveSet and tell it to draw 1024 instances.\r\n geom.addPrimitiveSet( new osg::DrawArrays( GL_QUADS, 0, 4, nInstances ) );\r\n}\r\n\r\n\r\nosg::StateSet*\r\ncreateStateSet()\r\n{\r\n osg::ref_ptr< osg::StateSet > ss = new osg::StateSet;\r\n\r\n \/\/ Create a vertex program that references the gl_InstanceID to\r\n \/\/ render each instance uniquely. gl_InstanceID will be in the range\r\n \/\/ 0 to numInstances-1 (1023 in our case).\r\n std::string vertexSource =\r\n \"uniform sampler2D osgLogo; \\n\"\r\n \"uniform float osg_SimulationTime; \\n\"\r\n\r\n \"void main() \\n\"\r\n \"{ \\n\"\r\n \/\/ Using the instance ID, generate \"texture coords\" for this instance.\r\n \"vec2 tC; \\n\"\r\n \"const float r = gl_InstanceID \/ 32.; \\n\"\r\n \"tC.s = fract( r ); tC.t = floor( r ) \/ 32.; \\n\"\r\n \/\/ Get the color from the OSG logo.\r\n \"gl_FrontColor = texture2D( osgLogo, tC ); \\n\"\r\n\r\n \/\/ Use the (scaled) tex coord to translate the position of the vertices.\r\n \"vec4 pos = vec4( tC.s * 48., 0., tC.t * 48., 1. ); \\n\"\r\n\r\n \/\/ Compute a rotation angle from the instanceID and elapsed time.\r\n \"float timeOffset = gl_InstanceID \/ (32. * 32.); \\n\"\r\n \"float angle = ( osg_SimulationTime - timeOffset ) * 6.283; \\n\"\r\n \"float sa = sin( angle ); \\n\"\r\n \"float ca = cos( angle ); \\n\"\r\n \/\/ New orientation, rotate around z axis.\r\n \"vec4 newX = vec4( ca, sa, 0., 0. ); \\n\"\r\n \"vec4 newY = vec4( sa, ca, 0., 0. ); \\n\"\r\n \"vec4 newZ = vec4( 0., 0., 1., 0. ); \\n\"\r\n \"mat4 mV = mat4( newX, newY, newZ, pos ); \\n\"\r\n \"gl_Position = ( gl_ModelViewProjectionMatrix * mV * gl_Vertex ); \\n\"\r\n \"} \\n\";\r\n\r\n osg::ref_ptr< osg::Shader > vertexShader = new osg::Shader();\r\n vertexShader->setType( osg::Shader::VERTEX );\r\n vertexShader->setShaderSource( vertexSource );\r\n\r\n osg::ref_ptr< osg::Program > program = new osg::Program();\r\n program->addShader( vertexShader.get() );\r\n\r\n ss->setAttribute( program.get(),\r\n osg::StateAttribute::ON | osg::StateAttribute::PROTECTED );\r\n\r\n osg::ref_ptr< osg::Image> iLogo = osgDB::readImageFile( \"Images\/osg128.png\" );\r\n if( !iLogo.valid() )\r\n {\r\n osg::notify( osg::ALWAYS ) << \"Can't open image file osg128.png\" << std::endl;\r\n return( NULL );\r\n }\r\n osg::Texture2D* texLogo = new osg::Texture2D( iLogo.get() );\r\n texLogo->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );\r\n texLogo->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );\r\n\r\n ss->setTextureAttribute( 0, texLogo );\r\n\r\n osg::ref_ptr< osg::Uniform > texLogoUniform =\r\n new osg::Uniform( \"osgLogo\", 0 );\r\n ss->addUniform( texLogoUniform.get() );\r\n\r\n return( ss.release() );\r\n}\r\n\r\n\r\nint main( int argc, char **argv )\r\n{\r\n osg::ArgumentParser arguments(&argc, argv);\r\n\r\n \/\/ Make a scene graph consisting of a single Geode, containing\r\n \/\/ a single Geometry, and a single PrimitiveSet.\r\n osg::ref_ptr< osg::Geode > geode = new osg::Geode;\r\n\r\n osg::ref_ptr< osg::Geometry > geom = new osg::Geometry;\r\n \/\/ Configure the Geometry for use with EXT_draw_arrays:\r\n \/\/ DL off and buffer objects on.\r\n geom->setUseDisplayList( false );\r\n geom->setUseVertexBufferObjects( true );\r\n \/\/ OSG has no clue where out vertex shader will place the geometric data,\r\n \/\/ so specify an initial bound to allow proper culling and near\/far computation.\r\n osg::BoundingBox bb( -1., -.1, -1., 49., 1., 49. );\r\n geom->setInitialBound( bb );\r\n \/\/ Add geometric data and the PrimitiveSet. Specify numInstances as 32*32 or 1024.\r\n createDAIGeometry( *geom, 32*32 );\r\n geode->addDrawable( geom.get() );\r\n\r\n \/\/ Create a StateSet to render the instanced Geometry.\r\n osg::ref_ptr< osg::StateSet > ss = createStateSet();\r\n geode->setStateSet( ss.get() );\r\n\r\n \/\/ osgDB::writeNodeFile(*geode, \"instanced.osg\");\r\n\r\n osgViewer::Viewer viewer(arguments);\r\n viewer.setSceneData( geode.get() );\r\n return viewer.run();\r\n}\r\nTweaks to shader to fix warnings on with ATI drivers\/* OpenSceneGraph example, osgdrawinstanced.\r\n*\r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n*\r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\/\/\r\n\/\/ This code is copyright (c) 2008 Skew Matrix Software LLC. You may use\r\n\/\/ the code under the licensing terms described above.\r\n\/\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n\r\nvoid\r\ncreateDAIGeometry( osg::Geometry& geom, int nInstances=1 )\r\n{\r\n const float halfDimX( .5 );\r\n const float halfDimZ( .5 );\r\n\r\n osg::Vec3Array* v = new osg::Vec3Array;\r\n v->resize( 4 );\r\n geom.setVertexArray( v );\r\n\r\n \/\/ Geometry for a single quad.\r\n (*v)[ 0 ] = osg::Vec3( -halfDimX, 0., -halfDimZ );\r\n (*v)[ 1 ] = osg::Vec3( halfDimX, 0., -halfDimZ );\r\n (*v)[ 2 ] = osg::Vec3( halfDimX, 0., halfDimZ );\r\n (*v)[ 3 ] = osg::Vec3( -halfDimX, 0., halfDimZ );\r\n\r\n \/\/ Use the DrawArraysInstanced PrimitiveSet and tell it to draw 1024 instances.\r\n geom.addPrimitiveSet( new osg::DrawArrays( GL_QUADS, 0, 4, nInstances ) );\r\n}\r\n\r\n\r\nosg::StateSet*\r\ncreateStateSet()\r\n{\r\n osg::ref_ptr< osg::StateSet > ss = new osg::StateSet;\r\n\r\n \/\/ Create a vertex program that references the gl_InstanceID to\r\n \/\/ render each instance uniquely. gl_InstanceID will be in the range\r\n \/\/ 0 to numInstances-1 (1023 in our case).\r\n std::string vertexSource =\r\n \"uniform sampler2D osgLogo; \\n\"\r\n \"uniform float osg_SimulationTime; \\n\"\r\n\r\n \"void main() \\n\"\r\n \"{ \\n\"\r\n \/\/ Using the instance ID, generate \"texture coords\" for this instance.\r\n \"vec2 tC; \\n\"\r\n \"float r = float(gl_InstanceID) \/ 32.; \\n\"\r\n \"tC.s = fract( r ); tC.t = floor( r ) \/ 32.; \\n\"\r\n \/\/ Get the color from the OSG logo.\r\n \"gl_FrontColor = texture2D( osgLogo, tC ); \\n\"\r\n\r\n \/\/ Use the (scaled) tex coord to translate the position of the vertices.\r\n \"vec4 pos = vec4( tC.s * 48., 0., tC.t * 48., 1. ); \\n\"\r\n\r\n \/\/ Compute a rotation angle from the instanceID and elapsed time.\r\n \"float timeOffset = gl_InstanceID \/ (32. * 32.); \\n\"\r\n \"float angle = ( osg_SimulationTime - timeOffset ) * 6.283; \\n\"\r\n \"float sa = sin( angle ); \\n\"\r\n \"float ca = cos( angle ); \\n\"\r\n \/\/ New orientation, rotate around z axis.\r\n \"vec4 newX = vec4( ca, sa, 0., 0. ); \\n\"\r\n \"vec4 newY = vec4( sa, ca, 0., 0. ); \\n\"\r\n \"vec4 newZ = vec4( 0., 0., 1., 0. ); \\n\"\r\n \"mat4 mV = mat4( newX, newY, newZ, pos ); \\n\"\r\n \"gl_Position = ( gl_ModelViewProjectionMatrix * mV * gl_Vertex ); \\n\"\r\n \"} \\n\";\r\n\r\n osg::ref_ptr< osg::Shader > vertexShader = new osg::Shader();\r\n vertexShader->setType( osg::Shader::VERTEX );\r\n vertexShader->setShaderSource( vertexSource );\r\n\r\n osg::ref_ptr< osg::Program > program = new osg::Program();\r\n program->addShader( vertexShader.get() );\r\n\r\n ss->setAttribute( program.get(),\r\n osg::StateAttribute::ON | osg::StateAttribute::PROTECTED );\r\n\r\n osg::ref_ptr< osg::Image> iLogo = osgDB::readImageFile( \"Images\/osg128.png\" );\r\n if( !iLogo.valid() )\r\n {\r\n osg::notify( osg::ALWAYS ) << \"Can't open image file osg128.png\" << std::endl;\r\n return( NULL );\r\n }\r\n osg::Texture2D* texLogo = new osg::Texture2D( iLogo.get() );\r\n texLogo->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );\r\n texLogo->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );\r\n\r\n ss->setTextureAttribute( 0, texLogo );\r\n\r\n osg::ref_ptr< osg::Uniform > texLogoUniform =\r\n new osg::Uniform( \"osgLogo\", 0 );\r\n ss->addUniform( texLogoUniform.get() );\r\n\r\n return( ss.release() );\r\n}\r\n\r\n\r\nint main( int argc, char **argv )\r\n{\r\n osg::ArgumentParser arguments(&argc, argv);\r\n\r\n \/\/ Make a scene graph consisting of a single Geode, containing\r\n \/\/ a single Geometry, and a single PrimitiveSet.\r\n osg::ref_ptr< osg::Geode > geode = new osg::Geode;\r\n\r\n osg::ref_ptr< osg::Geometry > geom = new osg::Geometry;\r\n \/\/ Configure the Geometry for use with EXT_draw_arrays:\r\n \/\/ DL off and buffer objects on.\r\n geom->setUseDisplayList( false );\r\n geom->setUseVertexBufferObjects( true );\r\n \/\/ OSG has no clue where out vertex shader will place the geometric data,\r\n \/\/ so specify an initial bound to allow proper culling and near\/far computation.\r\n osg::BoundingBox bb( -1., -.1, -1., 49., 1., 49. );\r\n geom->setInitialBound( bb );\r\n \/\/ Add geometric data and the PrimitiveSet. Specify numInstances as 32*32 or 1024.\r\n createDAIGeometry( *geom, 32*32 );\r\n geode->addDrawable( geom.get() );\r\n\r\n \/\/ Create a StateSet to render the instanced Geometry.\r\n osg::ref_ptr< osg::StateSet > ss = createStateSet();\r\n geode->setStateSet( ss.get() );\r\n\r\n \/\/ osgDB::writeNodeFile(*geode, \"instanced.osg\");\r\n\r\n osgViewer::Viewer viewer(arguments);\r\n viewer.setSceneData( geode.get() );\r\n return viewer.run();\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * Author: Michael Camilleri\n * \n * Copyright (c) 2016, University Of Edinburgh \n * All rights reserved. \n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met: \n * \n * * Redistributions of source code must retain the above copyright notice, \n * this list of conditions and the following disclaimer. \n * * Redistributions in binary form must reproduce the above copyright \n * notice, this list of conditions and the following disclaimer in the \n * documentation and\/or other materials provided with the distribution. \n * * Neither the name of nor the names of its contributors may be used to \n * endorse or promote products derived from this software without specific \n * prior written permission. \n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n * POSSIBILITY OF SUCH DAMAGE. \n *\n *\/\n\n#include \"Identity.h\"\n\nREGISTER_TASKMAP_TYPE(\"Identity\", exotica::Identity);\n\nnamespace exotica\n{\n Identity::Identity()\n {\n\n }\n\n void Identity::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)\n {\n if(phi.rows() != jointMap.size()) throw_named(\"Wrong size of phi!\");\n for(int i=0;igetSolver().getNumJoints();\n if(init_.JointRef.rows()>0)\n {\n jointRef = init_.JointRef;\n if(init_.JointMap.size()>0)\n {\n jointMap = init_.JointMap;\n if(jointMap.size()!=jointRef.rows()) throw_named(\"Incorrect joint map size!\");\n }\n else\n {\n jointMap.resize(jointRef.rows());\n for (int i = 0; i < jointRef.rows(); i++) jointMap[i] = i;\n }\n }\n else\n {\n jointRef = Eigen::VectorXd::Zero(N);\n jointMap.resize(N);\n for (int i = 0; i < N; i++) jointMap[i] = i;\n }\n }\n\n int Identity::taskSpaceDim()\n {\n return jointMap.size();\n }\n}\nFixed Identity initialization\/*\n * Author: Michael Camilleri\n * \n * Copyright (c) 2016, University Of Edinburgh \n * All rights reserved. \n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met: \n * \n * * Redistributions of source code must retain the above copyright notice, \n * this list of conditions and the following disclaimer. \n * * Redistributions in binary form must reproduce the above copyright \n * notice, this list of conditions and the following disclaimer in the \n * documentation and\/or other materials provided with the distribution. \n * * Neither the name of nor the names of its contributors may be used to \n * endorse or promote products derived from this software without specific \n * prior written permission. \n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE \n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n * POSSIBILITY OF SUCH DAMAGE. \n *\n *\/\n\n#include \"Identity.h\"\n\nREGISTER_TASKMAP_TYPE(\"Identity\", exotica::Identity);\n\nnamespace exotica\n{\n Identity::Identity()\n {\n\n }\n\n void Identity::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)\n {\n if(phi.rows() != jointMap.size()) throw_named(\"Wrong size of phi!\");\n for(int i=0;igetSolver().getNumJoints(), (int)init_.JointMap.size());\n if(init_.JointMap.size()>0)\n {\n jointMap = init_.JointMap;\n }\n else\n {\n jointMap.resize(N);\n for (int i = 0; i < N; i++) jointMap[i] = i;\n }\n\n if(init_.JointRef.rows()>0)\n {\n jointRef = init_.JointRef;\n if(jointRef.rows()!=N) throw_named(\"Invalid joint reference size! Expecting \" << N);\n }\n else\n {\n jointRef = Eigen::VectorXd::Zero(N);\n }\n\n }\n\n int Identity::taskSpaceDim()\n {\n return jointMap.size();\n }\n}\n<|endoftext|>"} {"text":"#include \"OI.h\"\n\n#include \"Commands\/Shooter\/ToggleShooter.h\"\n#include \"Commands\/Shooter\/KillShooter.h\"\n#include \"Commands\/TurHop\/AltitudeDirCont.h\"\n#include \"Commands\/TurHop\/Fire.h\"\n#include \"Commands\/TurHop\/Load.h\"\n#include \"Commands\/TurHop\/RotateHopper.h\"\n\nOI::OI() {\n\t\/\/ Process operator interface input here.\n\tstick = new Joystick(1);\n\t\n\traiseTur = new JoystickButton(stick, 2);\n\tlowerTur = new JoystickButton(stick, 1);\n\tfire = new JoystickButton(stick, 6);\n\tloader = new JoystickButton(stick, 5);\n\tspeedToggler = new JoystickButton(stick, 4);\n\tkillShooter = new JoystickButton(stick, 3);\n\t\t\n\traiseTur->WhileHeld(new AltitudeDirCont(true));\n\tlowerTur->WhileHeld(new AltitudeDirCont(false));\n\tfire->WhileHeld(new Fire());\n\tload->WhenPressed(new Load());\n\tspeedToggler->WhenPressed(new ToggleShooter());\n\tkillShooter->WhenPressed(new KillShooter());\n}\ndouble OI::GetStick(int stickNum)\n{\n\tswitch(stickNum)\n\t{\n\tdefault:\n\t\treturn stick->GetRawAxis(2);\n\tcase 1:\n\t\treturn stick->GetRawAxis(2);\n\tcase 2:\n\t\treturn stick->GetRawAxis(5);\n\t}\n}\nfixed typo#include \"OI.h\"\n\n#include \"Commands\/Shooter\/ToggleShooter.h\"\n#include \"Commands\/Shooter\/KillShooter.h\"\n#include \"Commands\/TurHop\/AltitudeDirCont.h\"\n#include \"Commands\/TurHop\/Fire.h\"\n#include \"Commands\/TurHop\/Load.h\"\n#include \"Commands\/TurHop\/RotateHopper.h\"\n\nOI::OI() {\n\t\/\/ Process operator interface input here.\n\tstick = new Joystick(1);\n\t\n\traiseTur = new JoystickButton(stick, 2);\n\tlowerTur = new JoystickButton(stick, 1);\n\tfire = new JoystickButton(stick, 6);\n\tloader = new JoystickButton(stick, 5);\n\tspeedToggler = new JoystickButton(stick, 4);\n\tkillShooter = new JoystickButton(stick, 3);\n\t\t\n\traiseTur->WhileHeld(new AltitudeDirCont(true));\n\tlowerTur->WhileHeld(new AltitudeDirCont(false));\n\tfire->WhileHeld(new Fire());\n\tloader->WhenPressed(new Load());\n\tspeedToggler->WhenPressed(new ToggleShooter());\n\tkillShooter->WhenPressed(new KillShooter());\n}\ndouble OI::GetStick(int stickNum)\n{\n\tswitch(stickNum)\n\t{\n\tdefault:\n\t\treturn stick->GetRawAxis(2);\n\tcase 1:\n\t\treturn stick->GetRawAxis(2);\n\tcase 2:\n\t\treturn stick->GetRawAxis(5);\n\t}\n}\n<|endoftext|>"} {"text":"#include \"tag-database-sqlite.h\"\n#include \n#include \n#include \n#include \n#include \"logger.h\"\n\n\nTagDatabaseSqlite::TagDatabaseSqlite(QString typeFile, QString tagFile)\n\t: TagDatabase(typeFile), m_tagFile(tagFile)\n{}\n\nbool TagDatabaseSqlite::load()\n{\n\t\/\/ Don't reload databases\n\tif (m_database.isOpen())\n\t\treturn true;\n\n\t\/\/ Load tag types\n\tif (!TagDatabase::load())\n\t\treturn false;\n\n\t\/\/ Load and connect to the database\n\tm_database = QSqlDatabase::addDatabase(\"QSQLITE\");\n\tm_database.setDatabaseName(\"release\/sites\/Danbooru\/e621.net\/tags.db\");\n\tif (!m_database.open())\n\t\treturn false;\n\n\t\/\/ Create schema if necessary\n\tQSqlQuery createQuery(m_database);\n\tcreateQuery.prepare(\"CREATE TABLE IF NOT EXISTS tags (tag VARCHAR(255), ttype INT);\");\n\tif (!createQuery.exec())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool TagDatabaseSqlite::save()\n{\n\treturn true;\n}\n\nvoid TagDatabaseSqlite::setTags(const QList &tags)\n{\n\t\/\/ Inverted tag type map to get the tag type ID from its name\n\tQMap tagTypes;\n\tfor (int typeId : m_tagTypes.keys())\n\t\ttagTypes.insert(m_tagTypes[typeId].name(), typeId);\n\n\tQSqlQuery clearQuery(m_database);\n\tclearQuery.prepare(\"DELETE FROM tags\");\n\tif (!clearQuery.exec())\n\t{\n\t\tlog(QString(\"SQL error when clearing tags: %1\").arg(clearQuery.lastError().text()), Logger::Error);\n\t\treturn;\n\t}\n\n\tif (!m_database.transaction())\n\t\treturn;\n\n\tQSqlQuery addQuery(m_database);\n\taddQuery.prepare(\"INSERT INTO tags (tag, ttype) VALUES (:tag, :ttype)\");\n\n\tfor (Tag tag : tags)\n\t{\n\t\tQString type = tag.type().name();\n\t\taddQuery.bindValue(\":tag\", tag.text());\n\t\taddQuery.bindValue(\":ttype\", tagTypes.contains(type) ? tagTypes[type] : -1);\n\t\tif (!addQuery.exec())\n\t\t{\n\t\t\tlog(QString(\"SQL error when adding tag: %1\").arg(addQuery.lastError().text()), Logger::Error);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (!m_database.commit())\n\t\treturn;\n}\n\nTagType TagDatabaseSqlite::getTagType(QString tag) const\n{\n\tQSqlQuery query(m_database);\n\tquery.prepare(\"SELECT tag, ttype FROM tags WHERE tag IN (:tags)\");\n\tquery.bindValue(\":tags\", QStringList() << tag);\n\tif (!query.exec())\n\t{\n\t\tlog(QString(\"SQL error when getting tags: %1\").arg(query.lastError().text()), Logger::Error);\n\t\treturn TagType(\"unknown\");\n\t}\n\n\tint idTtype = query.record().indexOf(\"ttype\");\n\tif (!query.first())\n\t\treturn TagType(\"unknown\");\n\n\treturn m_tagTypes[query.value(idTtype).toInt()];\n}\nLoad correct tag file for Sqlite#include \"tag-database-sqlite.h\"\n#include \n#include \n#include \n#include \n#include \"logger.h\"\n\n\nTagDatabaseSqlite::TagDatabaseSqlite(QString typeFile, QString tagFile)\n\t: TagDatabase(typeFile), m_tagFile(tagFile)\n{}\n\nbool TagDatabaseSqlite::load()\n{\n\t\/\/ Don't reload databases\n\tif (m_database.isOpen())\n\t\treturn true;\n\n\t\/\/ Load tag types\n\tif (!TagDatabase::load())\n\t\treturn false;\n\n\t\/\/ Load and connect to the database\n\tm_database = QSqlDatabase::addDatabase(\"QSQLITE\");\n\tm_database.setDatabaseName(m_tagFile);\n\tif (!m_database.open())\n\t\treturn false;\n\n\t\/\/ Create schema if necessary\n\tQSqlQuery createQuery(m_database);\n\tcreateQuery.prepare(\"CREATE TABLE IF NOT EXISTS tags (tag VARCHAR(255), ttype INT);\");\n\tif (!createQuery.exec())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool TagDatabaseSqlite::save()\n{\n\treturn true;\n}\n\nvoid TagDatabaseSqlite::setTags(const QList &tags)\n{\n\t\/\/ Inverted tag type map to get the tag type ID from its name\n\tQMap tagTypes;\n\tfor (int typeId : m_tagTypes.keys())\n\t\ttagTypes.insert(m_tagTypes[typeId].name(), typeId);\n\n\tQSqlQuery clearQuery(m_database);\n\tclearQuery.prepare(\"DELETE FROM tags\");\n\tif (!clearQuery.exec())\n\t{\n\t\tlog(QString(\"SQL error when clearing tags: %1\").arg(clearQuery.lastError().text()), Logger::Error);\n\t\treturn;\n\t}\n\n\tif (!m_database.transaction())\n\t\treturn;\n\n\tQSqlQuery addQuery(m_database);\n\taddQuery.prepare(\"INSERT INTO tags (tag, ttype) VALUES (:tag, :ttype)\");\n\n\tfor (Tag tag : tags)\n\t{\n\t\tQString type = tag.type().name();\n\t\taddQuery.bindValue(\":tag\", tag.text());\n\t\taddQuery.bindValue(\":ttype\", tagTypes.contains(type) ? tagTypes[type] : -1);\n\t\tif (!addQuery.exec())\n\t\t{\n\t\t\tlog(QString(\"SQL error when adding tag: %1\").arg(addQuery.lastError().text()), Logger::Error);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (!m_database.commit())\n\t\treturn;\n}\n\nTagType TagDatabaseSqlite::getTagType(QString tag) const\n{\n\tQSqlQuery query(m_database);\n\tquery.prepare(\"SELECT tag, ttype FROM tags WHERE tag IN (:tags)\");\n\tquery.bindValue(\":tags\", QStringList() << tag);\n\tif (!query.exec())\n\t{\n\t\tlog(QString(\"SQL error when getting tags: %1\").arg(query.lastError().text()), Logger::Error);\n\t\treturn TagType(\"unknown\");\n\t}\n\n\tint idTtype = query.record().indexOf(\"ttype\");\n\tif (!query.first())\n\t\treturn TagType(\"unknown\");\n\n\treturn m_tagTypes[query.value(idTtype).toInt()];\n}\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nFilePropertyWidgetQt::FilePropertyWidgetQt(FileProperty* property)\n : PropertyWidgetQt(property), property_(property) {\n generateWidget();\n updateFromProperty();\n}\n\nvoid FilePropertyWidgetQt::generateWidget() {\n QHBoxLayout* hLayout = new QHBoxLayout();\n setSpacingAndMargins(hLayout);\n setLayout(hLayout);\n\n label_ = new EditableLabelQt(this, property_);\n hLayout->addWidget(label_);\n\n QHBoxLayout* hWidgetLayout = new QHBoxLayout();\n hWidgetLayout->setContentsMargins(0, 0, 0, 0);\n QWidget* widget = new QWidget();\n widget->setLayout(hWidgetLayout);\n\n lineEdit_ = new QLineEdit(this);\n lineEdit_->setReadOnly(true);\n\n QSizePolicy sp = lineEdit_->sizePolicy();\n sp.setHorizontalStretch(3);\n lineEdit_->setSizePolicy(sp);\n\n openButton_ = new QToolButton(this);\n openButton_->setIcon(QIcon(\":\/icons\/open.png\"));\n hWidgetLayout->addWidget(lineEdit_);\n hWidgetLayout->addWidget(openButton_);\n\n sp = widget->sizePolicy();\n sp.setHorizontalStretch(3);\n widget->setSizePolicy(sp);\n\n hLayout->addWidget(widget);\n connect(openButton_, SIGNAL(pressed()), this, SLOT(setPropertyValue()));\n}\n\nvoid FilePropertyWidgetQt::setPropertyValue() {\n std::string path{property_->get()};\n if (!path.empty()) {\n \/\/ only accept path if it exists\n if (filesystem::directoryExists(path)) {\n \/\/ TODO: replace with filesystem:: functionality!\n path = QDir(QString::fromStdString(path)).absolutePath().toStdString();\n }\n }\n\n \/\/ Setup Extensions\n std::vector filters = property_->getNameFilters();\n InviwoFileDialog importFileDialog(this, property_->getDisplayName(),\n property_->getContentType(), path);\n\n for (const auto& filter : filters) importFileDialog.addExtension(filter);\n\n switch (property_->getAcceptMode()) {\n case FileProperty::AcceptMode::Save:\n importFileDialog.setAcceptMode(QFileDialog::AcceptSave);\n break;\n\n case FileProperty::AcceptMode::Open:\n importFileDialog.setAcceptMode(QFileDialog::AcceptOpen);\n break;\n\n default:\n importFileDialog.setAcceptMode(QFileDialog::AcceptOpen);\n }\n\n switch (property_->getFileMode()) {\n case FileProperty::FileMode::AnyFile:\n importFileDialog.setFileMode(QFileDialog::AnyFile);\n break;\n\n case FileProperty::FileMode::ExistingFile:\n importFileDialog.setFileMode(QFileDialog::ExistingFile);\n break;\n\n case FileProperty::FileMode::Directory:\n importFileDialog.setFileMode(QFileDialog::Directory);\n break;\n\n case FileProperty::FileMode::ExistingFiles:\n importFileDialog.setFileMode(QFileDialog::ExistingFiles);\n break;\n\n case FileProperty::FileMode::DirectoryOnly:\n importFileDialog.setFileMode(QFileDialog::DirectoryOnly);\n break;\n\n default:\n importFileDialog.setFileMode(QFileDialog::AnyFile);\n break;\n }\n\n if (importFileDialog.exec()) {\n QString path = importFileDialog.selectedFiles().at(0);\n property_->set(path.toStdString());\n }\n\n updateFromProperty();\n}\n\nbool FilePropertyWidgetQt::requestFile() {\n setPropertyValue();\n return !property_->get().empty();\n}\n\nvoid FilePropertyWidgetQt::updateFromProperty() {\n lineEdit_->setText(QFileInfo(QString::fromStdString(property_->get())).fileName());\n}\n\n} \/\/ namespace\nFilePropertyWidgetQT: Check if path is a file or a directory. If it is a file we need the file directory of that path for QT to open the correct path in the file dialog (closes issue inviwo\/inviwo-dev#1104)\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nFilePropertyWidgetQt::FilePropertyWidgetQt(FileProperty* property)\n : PropertyWidgetQt(property), property_(property) {\n generateWidget();\n updateFromProperty();\n}\n\nvoid FilePropertyWidgetQt::generateWidget() {\n QHBoxLayout* hLayout = new QHBoxLayout();\n setSpacingAndMargins(hLayout);\n setLayout(hLayout);\n\n label_ = new EditableLabelQt(this, property_);\n hLayout->addWidget(label_);\n\n QHBoxLayout* hWidgetLayout = new QHBoxLayout();\n hWidgetLayout->setContentsMargins(0, 0, 0, 0);\n QWidget* widget = new QWidget();\n widget->setLayout(hWidgetLayout);\n\n lineEdit_ = new QLineEdit(this);\n lineEdit_->setReadOnly(true);\n\n QSizePolicy sp = lineEdit_->sizePolicy();\n sp.setHorizontalStretch(3);\n lineEdit_->setSizePolicy(sp);\n\n openButton_ = new QToolButton(this);\n openButton_->setIcon(QIcon(\":\/icons\/open.png\"));\n hWidgetLayout->addWidget(lineEdit_);\n hWidgetLayout->addWidget(openButton_);\n\n sp = widget->sizePolicy();\n sp.setHorizontalStretch(3);\n widget->setSizePolicy(sp);\n\n hLayout->addWidget(widget);\n connect(openButton_, SIGNAL(pressed()), this, SLOT(setPropertyValue()));\n}\n\nvoid FilePropertyWidgetQt::setPropertyValue() {\n std::string path{ property_->get() };\n\n if (!path.empty()) {\n if (filesystem::directoryExists(path)) { \/\/ if a folder is selected\n \/\/ TODO: replace with filesystem:: functionality!\n path = QDir(QString::fromStdString(path)).absolutePath().toStdString();\n } else if (filesystem::fileExists(path)) {\n \/\/ if a file is selected, set path the the folder, not the file\n path = QDir(QString::fromStdString(filesystem::getFileDirectory(path)))\n .absolutePath()\n .toStdString();\n }\n }\n\n \/\/ Setup Extensions\n std::vector filters = property_->getNameFilters();\n InviwoFileDialog importFileDialog(this, property_->getDisplayName(),\n property_->getContentType(), path);\n\n for (const auto& filter : filters) importFileDialog.addExtension(filter);\n\n switch (property_->getAcceptMode()) {\n case FileProperty::AcceptMode::Save:\n importFileDialog.setAcceptMode(QFileDialog::AcceptSave);\n break;\n\n case FileProperty::AcceptMode::Open:\n importFileDialog.setAcceptMode(QFileDialog::AcceptOpen);\n break;\n\n default:\n importFileDialog.setAcceptMode(QFileDialog::AcceptOpen);\n }\n\n switch (property_->getFileMode()) {\n case FileProperty::FileMode::AnyFile:\n importFileDialog.setFileMode(QFileDialog::AnyFile);\n break;\n\n case FileProperty::FileMode::ExistingFile:\n importFileDialog.setFileMode(QFileDialog::ExistingFile);\n break;\n\n case FileProperty::FileMode::Directory:\n importFileDialog.setFileMode(QFileDialog::Directory);\n break;\n\n case FileProperty::FileMode::ExistingFiles:\n importFileDialog.setFileMode(QFileDialog::ExistingFiles);\n break;\n\n case FileProperty::FileMode::DirectoryOnly:\n importFileDialog.setFileMode(QFileDialog::DirectoryOnly);\n break;\n\n default:\n importFileDialog.setFileMode(QFileDialog::AnyFile);\n break;\n }\n\n if (importFileDialog.exec()) {\n QString path = importFileDialog.selectedFiles().at(0);\n property_->set(path.toStdString());\n }\n\n updateFromProperty();\n}\n\nbool FilePropertyWidgetQt::requestFile() {\n setPropertyValue();\n return !property_->get().empty();\n}\n\nvoid FilePropertyWidgetQt::updateFromProperty() {\n lineEdit_->setText(QFileInfo(QString::fromStdString(property_->get())).fileName());\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"timer.hpp\"\n#include \"scheduler.hpp\"\n#include \"logging.hpp\"\n#include \"kernel.hpp\" \/\/suspend_boot\n\n#include \"drivers\/pit.hpp\"\n#include \"drivers\/hpet.hpp\"\n\n#include \"fs\/sysfs.hpp\"\n\nnamespace {\n\nuint64_t _timer_ticks = 0;\nuint64_t _timer_seconds = 0;\nuint64_t _timer_frequency = 0;\n\nvolatile uint64_t _timer_countdown = 0;\n\nstd::string sysfs_uptime(){\n return std::to_string(timer::seconds());\n}\n\nbool find_hw_timer(){\n if(hpet::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install HPET driver\\n\");\n }\n\n if(pit::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install PIT driver\\n\");\n }\n\n return false;\n}\n\n} \/\/End of anonymous namespace\n\nvoid timer::install(){\n if(!find_hw_timer()){\n logging::logf(logging::log_level::ERROR, \"Unable to install any timer driver\\n\");\n suspend_boot();\n }\n\n sysfs::set_dynamic_value(\"\/sys\/\", \"uptime\", &sysfs_uptime);\n}\n\nvoid timer::tick(){\n ++_timer_ticks;\n\n if(_timer_countdown != 0){\n --_timer_countdown;\n }\n\n scheduler::tick();\n\n if(_timer_ticks % frequency() == 0){\n ++_timer_seconds;\n }\n}\n\nuint64_t timer::ticks(){\n return _timer_ticks;\n}\n\nuint64_t timer::seconds(){\n return _timer_seconds;\n}\n\nuint64_t timer::frequency(){\n return _timer_frequency;\n}\n\nvoid timer::frequency(uint64_t freq){\n _timer_frequency = freq;\n\n logging::logf(logging::log_level::DEBUG, \"timer: Frequency set to %u Hz\\n\", freq);\n}\nRemove legacy countdown\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"timer.hpp\"\n#include \"scheduler.hpp\"\n#include \"logging.hpp\"\n#include \"kernel.hpp\" \/\/suspend_boot\n\n#include \"drivers\/pit.hpp\"\n#include \"drivers\/hpet.hpp\"\n\n#include \"fs\/sysfs.hpp\"\n\nnamespace {\n\nuint64_t _timer_ticks = 0;\nuint64_t _timer_seconds = 0;\nuint64_t _timer_frequency = 0;\n\nstd::string sysfs_uptime(){\n return std::to_string(timer::seconds());\n}\n\nbool find_hw_timer(){\n if(hpet::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install HPET driver\\n\");\n }\n\n if(pit::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install PIT driver\\n\");\n }\n\n return false;\n}\n\n} \/\/End of anonymous namespace\n\nvoid timer::install(){\n if(!find_hw_timer()){\n logging::logf(logging::log_level::ERROR, \"Unable to install any timer driver\\n\");\n suspend_boot();\n }\n\n sysfs::set_dynamic_value(\"\/sys\/\", \"uptime\", &sysfs_uptime);\n}\n\nvoid timer::tick(){\n ++_timer_ticks;\n\n scheduler::tick();\n\n if(_timer_ticks % frequency() == 0){\n ++_timer_seconds;\n }\n}\n\nuint64_t timer::ticks(){\n return _timer_ticks;\n}\n\nuint64_t timer::seconds(){\n return _timer_seconds;\n}\n\nuint64_t timer::frequency(){\n return _timer_frequency;\n}\n\nvoid timer::frequency(uint64_t freq){\n _timer_frequency = freq;\n\n logging::logf(logging::log_level::DEBUG, \"timer: Frequency set to %u Hz\\n\", freq);\n}\n<|endoftext|>"} {"text":"\/* \n * Copyright 2009-2011 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid and interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline=NULL;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"help\", \"produce this help message\")\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n try {\n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (size_t i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n try {\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n } \n } catch (const char* message) {\n if(strcmp(\"qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n } \n else if(strcmp(\"constrained_qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while fitting.\");\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n try {\n spline->Interpolate(in.x(), in.y());\n } catch (const char* message) {\n if(strcmp(\"qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else if(strcmp(\"constrained_qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while interpolating.\");\n }\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n unsigned int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n\t}\n catch(std::exception &error) {\n cerr << \"an error occurred:\\n\" << error.what() << endl;\n return -1;\n }\n return 0;\n}\n\ncsg_resample: fixed flags of derivative file\/* \n * Copyright 2009-2011 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid and interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline=NULL;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"help\", \"produce this help message\")\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n try {\n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (size_t i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n try {\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n } \n } catch (const char* message) {\n if(strcmp(\"qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n } \n else if(strcmp(\"constrained_qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while fitting.\");\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n try {\n spline->Interpolate(in.x(), in.y());\n } catch (const char* message) {\n if(strcmp(\"qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else if(strcmp(\"constrained_qrsolve_zero_column_in_matrix\",message)) {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while interpolating.\");\n }\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n unsigned int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n der.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n\t}\n catch(std::exception &error) {\n cerr << \"an error occurred:\\n\" << error.what() << endl;\n return -1;\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Date Started: 8\/09\/18\n * Original Author: Sajid Ibne Anower\n * Editors:\n * Purpose: Widget to display voltage of the batteries\n * This code is released under the MIT License. Copyright BLUEsat UNSW, 2017, 2018\n *\/\n#include \"ros_video_components\/ros_voltage_meter.hpp\"\n\n#define RECT_X 0\n#define RECT_Y 0\n#define RECT_WIDTH RECT_X*40\n#define RECT_HEIGHT 150\n#define MAXDATA 100\n#define MAXNUM 5\n#define NUMCOLOR 3\n#define GREEN 4\n#define YELLOW 2\n#define RED 1\n#define HASH MAXDATA\/MAXNUM\n#define TOO_WEAK MAXDATA\/20\n\nROS_Voltage_Meter::ROS_Voltage_Meter(QQuickItem * parent) :\n QQuickPaintedItem(parent),\n topic_value(\"\/rover\/volt\"),\n ros_ready(false),\n data(50) {}\n\nvoid ROS_Voltage_Meter::setup(ros::NodeHandle * nh) {\n volt_sub = nh->subscribe(\n \"\/rover\/volt\",\n 1,\n &ROS_Voltage_Meter::receive_volt_val,\n this);\n ros_ready = true;\n}\n\nvoid ROS_Voltage_Meter::paint(QPainter * painter) {\n int x = RECT_X;\n int y = RECT_Y;\n int widthV = width(); \/\/ RECT_WIDTH;\n int heightV = height(); \/\/ RECT_HEIGHT;\n\n QLinearGradient linearGradient(0, 0, 100, 100);\n int num = 0;\n float hash = HASH;\n if (data >= MAXDATA) {\n num = MAXNUM;\n } else if (data <= TOO_WEAK) {\n num = 0;\n linearGradient.setColorAt(0.0, Qt::white);\n painter->setBrush(linearGradient);\n } else {\n num = (data\/hash) + 1;\n }\n \/\/ draw the outer main rectangle\n painter->drawRect(x, y, widthV - 1, heightV - 1);\n\n int i = 0;\n\n int barWidth = widthV\/MAXNUM;\n int barHeight = heightV\/MAXNUM;\n y += ((MAXNUM-1) * heightV) \/MAXNUM;\n const int increment = heightV\/MAXNUM;\n if (num == 0) {\n ROS_INFO(\"NO SIGNAL\\n\");\n } else {\n for (i = 1; i <= num; i++) {\n if (num >= GREEN) {\n linearGradient.setColorAt(0.2, Qt::green);\n } else if (num >= YELLOW) {\n linearGradient.setColorAt(0.2, Qt::yellow);\n } else {\n linearGradient.setColorAt(0.2, Qt::red);\n }\n painter->setBrush(linearGradient);\n painter->drawRect(x, y, barWidth, barHeight);\n x += barWidth; \/\/ move x along\n barHeight += increment; \/\/ increase height\n y -= increment; \/\/ decrease height\n }\n }\n}\n\nvoid ROS_Voltage_Meter::set_topic(const QString & new_value) {\n \/\/ ROS_INFO(\"set_topic\");\n if (topic_value != new_value) {\n topic_value = new_value;\n if (ros_ready) {\n volt_sub.shutdown();\n volt_sub = nh->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Voltage_Meter::receive_volt_val,\n this);\n }\n emit topic_changed();\n }\n}\n\nQString ROS_Voltage_Meter::get_topic() const {\n return topic_value;\n}\n\nvoid ROS_Voltage_Meter :: receive_volt_val(const std_msgs::Float32::ConstPtr & msg) {\n data = msg->data;\n ROS_INFO(\"Received voltage update\");\n update();\n}\nAdd stub for paint\/*\n * Date Started: 8\/09\/18\n * Original Author: Sajid Ibne Anower\n * Editors:\n * Purpose: Widget to display voltage of the batteries\n * This code is released under the MIT License. Copyright BLUEsat UNSW, 2017, 2018\n *\/\n#include \"ros_video_components\/ros_voltage_meter.hpp\"\n\nROS_Voltage_Meter::ROS_Voltage_Meter(QQuickItem * parent) :\n QQuickPaintedItem(parent),\n topic_value(\"\/rover\/volt\"),\n ros_ready(false),\n data(50) {}\n\nvoid ROS_Voltage_Meter::setup(ros::NodeHandle * nh) {\n volt_sub = nh->subscribe(\n \"\/rover\/volt\",\n 1,\n &ROS_Voltage_Meter::receive_volt_val,\n this);\n ros_ready = true;\n}\n\nvoid ROS_Voltage_Meter::paint(QPainter * painter) {\n \/\/ TODO(sajidanower23)\n}\n\nvoid ROS_Voltage_Meter::set_topic(const QString & new_value) {\n \/\/ ROS_INFO(\"set_topic\");\n if (topic_value != new_value) {\n topic_value = new_value;\n if (ros_ready) {\n volt_sub.shutdown();\n volt_sub = nh->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Voltage_Meter::receive_volt_val,\n this);\n }\n emit topic_changed();\n }\n}\n\nQString ROS_Voltage_Meter::get_topic() const {\n return topic_value;\n}\n\nvoid ROS_Voltage_Meter :: receive_volt_val(const std_msgs::Float32::ConstPtr & msg) {\n data = msg->data;\n ROS_INFO(\"Received voltage update\");\n update();\n}\n<|endoftext|>"} {"text":"#include \".\/shader_program.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \".\/gl.h\"\n\nShaderProgram::ShaderProgram(Gl *gl, std::string vertexShaderPath,\n std::string fragmentShaderPath)\n : gl(gl)\n{\n if (!shaderProgram.addShaderFromSourceCode(\n QOpenGLShader::Vertex,\n readFileAndHandleIncludes(vertexShaderPath.c_str())))\n {\n qCritical() << \"error\";\n }\n if (!shaderProgram.addShaderFromSourceCode(\n QOpenGLShader::Fragment,\n readFileAndHandleIncludes(fragmentShaderPath.c_str())))\n {\n qCritical() << \"error\";\n }\n if (!shaderProgram.link())\n {\n qCritical() << \"error\";\n }\n glCheckError();\n}\n\nShaderProgram::~ShaderProgram()\n{\n}\n\nvoid ShaderProgram::bind()\n{\n shaderProgram.bind();\n}\n\nvoid ShaderProgram::release()\n{\n shaderProgram.release();\n}\n\nvoid ShaderProgram::enableAndSetAttributes(std::string usage,\n int perVertexElements)\n{\n shaderProgram.enableAttributeArray(usage.c_str());\n shaderProgram.setAttributeBuffer(usage.c_str(), GL_FLOAT, 0,\n perVertexElements);\n glCheckError();\n}\n\nint ShaderProgram::getId()\n{\n return shaderProgram.programId();\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Matrix4f matrix)\n{\n glAssert(gl->glProgramUniformMatrix4fv(getId(), getLocation(name), 1,\n GL_FALSE, matrix.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector4f vector)\n{\n glAssert(\n gl->glProgramUniform4fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector3f vector)\n{\n glAssert(\n gl->glProgramUniform3fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector2f vector)\n{\n glAssert(\n gl->glProgramUniform2fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, float value)\n{\n glAssert(gl->glProgramUniform1f(getId(), getLocation(name), value));\n}\n\nvoid ShaderProgram::setUniform(const char *name, int value)\n{\n glAssert(gl->glProgramUniform1i(getId(), getLocation(name), value));\n}\n\nQString readFile(QString path)\n{\n QFile file(path);\n\n if (!file.open(QFile::ReadOnly | QFile::Text))\n throw std::runtime_error(\"The file '\" + path.toStdString() +\n \"' doesn't exist!\");\n\n std::stringstream buffer;\n QTextStream in(&file);\n\n return in.readAll();\n}\n\nQString ShaderProgram::readFileAndHandleIncludes(QString path)\n{\n auto directory = QFileInfo(path).absoluteDir().path() + \"\/\";\n auto source = readFile(path);\n\n QRegularExpression regex(\"^[ ]*#include[ ]+[\\\"<](.*)[\\\">].*\");\n regex.setPatternOptions(QRegularExpression::MultilineOption);\n\n auto match = regex.match(source);\n while (match.hasMatch())\n {\n auto filename = match.captured(1);\n auto includePath = directory + filename;\n auto includeSource = readFile(includePath);\n includeSource = includeSource.replace(\n QRegularExpression(\"^[ ]*#version \\\\d*.*$\",\n QRegularExpression::MultilineOption),\n \"\");\n source = source.replace(match.capturedStart(0), match.capturedLength(0),\n includeSource);\n\n qDebug() << path << \"includes\" << includePath;\n\n match = regex.match(source, match.capturedEnd(0));\n }\n\n return source;\n}\n\nint ShaderProgram::getLocation(const char *name)\n{\n return shaderProgram.uniformLocation(name);\n}\n\nFix linting errors.#include \".\/shader_program.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \".\/gl.h\"\n\nShaderProgram::ShaderProgram(Gl *gl, std::string vertexShaderPath,\n std::string fragmentShaderPath)\n : gl(gl)\n{\n if (!shaderProgram.addShaderFromSourceCode(\n QOpenGLShader::Vertex,\n readFileAndHandleIncludes(vertexShaderPath.c_str())))\n {\n qCritical() << \"error\";\n }\n if (!shaderProgram.addShaderFromSourceCode(\n QOpenGLShader::Fragment,\n readFileAndHandleIncludes(fragmentShaderPath.c_str())))\n {\n qCritical() << \"error\";\n }\n if (!shaderProgram.link())\n {\n qCritical() << \"error\";\n }\n glCheckError();\n}\n\nShaderProgram::~ShaderProgram()\n{\n}\n\nvoid ShaderProgram::bind()\n{\n shaderProgram.bind();\n}\n\nvoid ShaderProgram::release()\n{\n shaderProgram.release();\n}\n\nvoid ShaderProgram::enableAndSetAttributes(std::string usage,\n int perVertexElements)\n{\n shaderProgram.enableAttributeArray(usage.c_str());\n shaderProgram.setAttributeBuffer(usage.c_str(), GL_FLOAT, 0,\n perVertexElements);\n glCheckError();\n}\n\nint ShaderProgram::getId()\n{\n return shaderProgram.programId();\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Matrix4f matrix)\n{\n glAssert(gl->glProgramUniformMatrix4fv(getId(), getLocation(name), 1,\n GL_FALSE, matrix.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector4f vector)\n{\n glAssert(\n gl->glProgramUniform4fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector3f vector)\n{\n glAssert(\n gl->glProgramUniform3fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, Eigen::Vector2f vector)\n{\n glAssert(\n gl->glProgramUniform2fv(getId(), getLocation(name), 1, vector.data()));\n}\n\nvoid ShaderProgram::setUniform(const char *name, float value)\n{\n glAssert(gl->glProgramUniform1f(getId(), getLocation(name), value));\n}\n\nvoid ShaderProgram::setUniform(const char *name, int value)\n{\n glAssert(gl->glProgramUniform1i(getId(), getLocation(name), value));\n}\n\nQString readFile(QString path)\n{\n QFile file(path);\n\n if (!file.open(QFile::ReadOnly | QFile::Text))\n throw std::runtime_error(\"The file '\" + path.toStdString() +\n \"' doesn't exist!\");\n\n std::stringstream buffer;\n QTextStream in(&file);\n\n return in.readAll();\n}\n\nQString ShaderProgram::readFileAndHandleIncludes(QString path)\n{\n auto directory = QFileInfo(path).absoluteDir().path() + \"\/\";\n auto source = readFile(path);\n\n QRegularExpression regex(\"^[ ]*#include[ ]+[\\\"<](.*)[\\\">].*\");\n regex.setPatternOptions(QRegularExpression::MultilineOption);\n\n auto match = regex.match(source);\n while (match.hasMatch())\n {\n auto filename = match.captured(1);\n auto includePath = directory + filename;\n auto includeSource = readFile(includePath);\n includeSource = includeSource.replace(\n QRegularExpression(\"^[ ]*#version \\\\d*.*$\",\n QRegularExpression::MultilineOption),\n \"\");\n source = source.replace(match.capturedStart(0), match.capturedLength(0),\n includeSource);\n\n qDebug() << path << \"includes\" << includePath;\n\n match = regex.match(source, match.capturedEnd(0));\n }\n\n return source;\n}\n\nint ShaderProgram::getLocation(const char *name)\n{\n return shaderProgram.uniformLocation(name);\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nnamespace cpu\n{\n unsigned getIdx(af::dim4 strides, af::dim4 offs, int i, int j = 0, int k = 0, int l = 0)\n {\n return ((l + offs[3]) * strides[3] +\n (k + offs[2]) * strides[2] +\n (j + offs[1]) * strides[1] +\n (i + offs[0]));\n }\n\n template\n Array* diff1(const Array &in, const int dim)\n {\n \/\/ Bool for dimension\n bool is_dim0 = dim == 0;\n bool is_dim1 = dim == 1;\n bool is_dim2 = dim == 2;\n bool is_dim3 = dim == 3;\n\n \/\/ Decrement dimension of select dimension\n af::dim4 dims = in.dims();\n dims[dim]--;\n\n \/\/ Create output placeholder\n Array *outArray = createValueArray(dims, (T)0);\n\n \/\/ Get pointers to raw data\n const T *inPtr = in.get(false);\n T *outPtr = outArray->get();\n\n \/\/ TODO: Improve this\n for(dim_type l = 0; l < dims[3]; l++) {\n for(dim_type k = 0; k < dims[2]; k++) {\n for(dim_type j = 0; j < dims[1]; j++) {\n for(dim_type i = 0; i < dims[0]; i++) {\n \/\/ Operation: out[index] = in[index + 1 * dim_size] - in[index]\n int idx = getIdx(in.strides(), in.offsets(), i, j, k, l);\n int jdx = getIdx(in.strides(), in.offsets(),\n i + is_dim0, j + is_dim1,\n k + is_dim2, l + is_dim3);\n int odx = getIdx(outArray->strides(), outArray->offsets(), i, j, k, l);\n outPtr[odx] = inPtr[jdx] - inPtr[idx];\n }\n }\n }\n }\n\n return outArray;\n }\n\n template\n Array* diff2(const Array &in, const int dim)\n {\n \/\/ Bool for dimension\n bool is_dim0 = dim == 0;\n bool is_dim1 = dim == 1;\n bool is_dim2 = dim == 2;\n bool is_dim3 = dim == 3;\n\n \/\/ Decrement dimension of select dimension\n af::dim4 dims = in.dims();\n dims[dim] -= 2;\n\n \/\/ Create output placeholder\n Array *outArray = createValueArray(dims, (T)0);\n\n \/\/ Get pointers to raw data\n const T *inPtr = in.get(false);\n T *outPtr = outArray->get();\n\n \/\/ TODO: Improve this\n for(dim_type l = 0; l < dims[3]; l++) {\n for(dim_type k = 0; k < dims[2]; k++) {\n for(dim_type j = 0; j < dims[1]; j++) {\n for(dim_type i = 0; i < dims[0]; i++) {\n \/\/ Operation: out[index] = in[index + 1 * dim_size] - in[index]\n int idx = getIdx(in.strides(), in.offsets(), i, j, k, l);\n int jdx = getIdx(in.strides(), in.offsets(),\n i + is_dim0, j + is_dim1,\n k + is_dim2, l + is_dim3);\n int kdx = getIdx(in.strides(), in.offsets(),\n i + 2 * is_dim0, j + 2 * is_dim1,\n k + 2 * is_dim2, l + 2 * is_dim3);\n int odx = getIdx(outArray->strides(), outArray->offsets(), i, j, k, l);\n outPtr[odx] = inPtr[kdx] + inPtr[idx] - inPtr[jdx] - inPtr[jdx];\n }\n }\n }\n }\n\n return outArray;\n }\n\n#define INSTANTIATE(T) \\\n template Array* diff1 (const Array &in, const int dim); \\\n template Array* diff2 (const Array &in, const int dim); \\\n\n\n INSTANTIATE(float)\n INSTANTIATE(double)\n INSTANTIATE(cfloat)\n INSTANTIATE(cdouble)\n INSTANTIATE(int)\n INSTANTIATE(uint)\n INSTANTIATE(uchar)\n INSTANTIATE(char)\n}\nUpdated diff CPU with offset changes#include \n#include \n#include \n#include \n#include \n\nnamespace cpu\n{\n unsigned getIdx(af::dim4 strides, af::dim4 offs, int i, int j = 0, int k = 0, int l = 0)\n {\n return (l * strides[3] +\n k * strides[2] +\n j * strides[1] +\n i);\n }\n\n template\n Array* diff1(const Array &in, const int dim)\n {\n \/\/ Bool for dimension\n bool is_dim0 = dim == 0;\n bool is_dim1 = dim == 1;\n bool is_dim2 = dim == 2;\n bool is_dim3 = dim == 3;\n\n \/\/ Decrement dimension of select dimension\n af::dim4 dims = in.dims();\n dims[dim]--;\n\n \/\/ Create output placeholder\n Array *outArray = createValueArray(dims, (T)0);\n\n \/\/ Get pointers to raw data\n const T *inPtr = in.get();\n T *outPtr = outArray->get();\n\n \/\/ TODO: Improve this\n for(dim_type l = 0; l < dims[3]; l++) {\n for(dim_type k = 0; k < dims[2]; k++) {\n for(dim_type j = 0; j < dims[1]; j++) {\n for(dim_type i = 0; i < dims[0]; i++) {\n \/\/ Operation: out[index] = in[index + 1 * dim_size] - in[index]\n int idx = getIdx(in.strides(), in.offsets(), i, j, k, l);\n int jdx = getIdx(in.strides(), in.offsets(),\n i + is_dim0, j + is_dim1,\n k + is_dim2, l + is_dim3);\n int odx = getIdx(outArray->strides(), outArray->offsets(), i, j, k, l);\n outPtr[odx] = inPtr[jdx] - inPtr[idx];\n }\n }\n }\n }\n\n return outArray;\n }\n\n template\n Array* diff2(const Array &in, const int dim)\n {\n \/\/ Bool for dimension\n bool is_dim0 = dim == 0;\n bool is_dim1 = dim == 1;\n bool is_dim2 = dim == 2;\n bool is_dim3 = dim == 3;\n\n \/\/ Decrement dimension of select dimension\n af::dim4 dims = in.dims();\n dims[dim] -= 2;\n\n \/\/ Create output placeholder\n Array *outArray = createValueArray(dims, (T)0);\n\n \/\/ Get pointers to raw data\n const T *inPtr = in.get();\n T *outPtr = outArray->get();\n\n \/\/ TODO: Improve this\n for(dim_type l = 0; l < dims[3]; l++) {\n for(dim_type k = 0; k < dims[2]; k++) {\n for(dim_type j = 0; j < dims[1]; j++) {\n for(dim_type i = 0; i < dims[0]; i++) {\n \/\/ Operation: out[index] = in[index + 1 * dim_size] - in[index]\n int idx = getIdx(in.strides(), in.offsets(), i, j, k, l);\n int jdx = getIdx(in.strides(), in.offsets(),\n i + is_dim0, j + is_dim1,\n k + is_dim2, l + is_dim3);\n int kdx = getIdx(in.strides(), in.offsets(),\n i + 2 * is_dim0, j + 2 * is_dim1,\n k + 2 * is_dim2, l + 2 * is_dim3);\n int odx = getIdx(outArray->strides(), outArray->offsets(), i, j, k, l);\n outPtr[odx] = inPtr[kdx] + inPtr[idx] - inPtr[jdx] - inPtr[jdx];\n }\n }\n }\n }\n\n return outArray;\n }\n\n#define INSTANTIATE(T) \\\n template Array* diff1 (const Array &in, const int dim); \\\n template Array* diff2 (const Array &in, const int dim); \\\n\n\n INSTANTIATE(float)\n INSTANTIATE(double)\n INSTANTIATE(cfloat)\n INSTANTIATE(cdouble)\n INSTANTIATE(int)\n INSTANTIATE(uint)\n INSTANTIATE(uchar)\n INSTANTIATE(char)\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ bb_toposort_sccs LLVM sample. Demonstrates:\n\/\/\n\/\/\n\/\/ Eli Bendersky (eliben@gmail.com)\n\/\/ This code is in the public domain\n\/\/------------------------------------------------------------------------------\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n\nusing namespace llvm;\n\n\n\/\/ Runs a topological sort on the basic blocks of the given function. Uses\n\/\/ the simple recursive DFS from \"Introduction to algorithms\", with 3-coloring\n\/\/ of vertices. The coloring enables detecting cycles in the graph with a simple\n\/\/ test.\nclass TopoSorter {\npublic:\n void runToposort(const Function &F) {\n outs() << \"Topological sort of function \" << F.getName() << \":\\n\";\n \/\/ Initialize the color map by marking all the vertices white.\n for (Function::const_iterator I = F.begin(), IE = F.end(); I != IE; ++I) {\n ColorMap[I] = TopoSorter::WHITE;\n }\n\n \/\/ The BB graph has a single entry vertex from which the other BBs should\n \/\/ be discoverable - the function entry block.\n bool success = recursiveDFSToposort(&F.getEntryBlock());\n if (success) {\n \/\/ Now we have all the BBs inside SortedBBs in reverse topological order.\n for (BBVector::const_reverse_iterator RI = SortedBBs.rbegin(),\n RE = SortedBBs.rend();\n RI != RE; ++RI) {\n outs() << \" \" << (*RI)->getName() << \"\\n\";\n }\n } else {\n outs() << \" Sorting failed\\n\";\n }\n }\nprivate:\n enum Color {WHITE, GREY, BLACK};\n \/\/ Color marks per vertex (BB).\n typedef DenseMap BBColorMap;\n \/\/ Collects vertices (BBs) in \"finish\" order. The first finished vertex is\n \/\/ first, and so on.\n typedef SmallVector BBVector;\n BBColorMap ColorMap;\n BBVector SortedBBs;\n\n \/\/ Helper function to recursively run topological sort from a given BB.\n \/\/ Returns true if the sort succeeded and false otherwise; topological sort\n \/\/ may fail if, for example, the graph is not a DAG (detected a cycle).\n bool recursiveDFSToposort(const BasicBlock *BB) {\n ColorMap[BB] = TopoSorter::GREY;\n \/\/ For demonstration, using the lowest-level APIs here. A BB's successors\n \/\/ are determined by looking at its terminator instruction.\n const TerminatorInst *TInst = BB->getTerminator();\n for (unsigned I = 0, NSucc = TInst->getNumSuccessors(); I < NSucc; ++I) {\n BasicBlock *Succ = TInst->getSuccessor(I);\n Color SuccColor = ColorMap[Succ];\n if (SuccColor == TopoSorter::WHITE) {\n if (!recursiveDFSToposort(Succ))\n return false;\n } else if (SuccColor == TopoSorter::GREY) {\n \/\/ This detects a cycle because grey vertices are all ancestors of the\n \/\/ currently explored vertex (in other words, they're \"on the stack\").\n outs() << \" Detected cycle: edge from \" << BB->getName() << \n \" to \" << Succ->getName() << \"\\n\";\n return false;\n }\n }\n \/\/ This BB is finished (fully explored), so we can add it to the vector.\n ColorMap[BB] = TopoSorter::BLACK;\n SortedBBs.push_back(BB);\n return true;\n }\n};\n\n\nclass AnalyzeBBGraph : public FunctionPass {\npublic:\n AnalyzeBBGraph() : FunctionPass(ID) {}\n\n virtual bool runOnFunction(Function &F) {\n TopoSorter TS;\n TS.runToposort(F);\n return false;\n }\n\n \/\/ The address of this member is used to uniquely identify the class. This is\n \/\/ used by LLVM's own RTTI mechanism.\n static char ID;\n};\n\nchar AnalyzeBBGraph::ID = 0;\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n errs() << \"Usage: \" << argv[0] << \" \\n\";\n return 1;\n }\n\n \/\/ Parse the input LLVM IR file into a module.\n SMDiagnostic Err;\n Module *Mod = ParseIRFile(argv[1], Err, getGlobalContext());\n if (!Mod) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n \/\/ Create a pass manager and fill it with the passes we want to run.\n PassManager PM;\n PM.add(new AnalyzeBBGraph());\n PM.run(*Mod);\n\n return 0;\n}\nUsing po_iterator to produce a post-order iteration.\/\/------------------------------------------------------------------------------\n\/\/ bb_toposort_sccs LLVM sample. Demonstrates:\n\/\/\n\/\/\n\/\/ Eli Bendersky (eliben@gmail.com)\n\/\/ This code is in the public domain\n\/\/------------------------------------------------------------------------------\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/PostOrderIterator.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \n\nusing namespace llvm;\n\n\n\/\/ Runs a topological sort on the basic blocks of the given function. Uses\n\/\/ the simple recursive DFS from \"Introduction to algorithms\", with 3-coloring\n\/\/ of vertices. The coloring enables detecting cycles in the graph with a simple\n\/\/ test.\nclass TopoSorter {\npublic:\n void runToposort(const Function &F) {\n outs() << \"Topological sort of function \" << F.getName() << \":\\n\";\n \/\/ Initialize the color map by marking all the vertices white.\n for (Function::const_iterator I = F.begin(), IE = F.end(); I != IE; ++I) {\n ColorMap[I] = TopoSorter::WHITE;\n }\n\n \/\/ The BB graph has a single entry vertex from which the other BBs should\n \/\/ be discoverable - the function entry block.\n bool success = recursiveDFSToposort(&F.getEntryBlock());\n if (success) {\n \/\/ Now we have all the BBs inside SortedBBs in reverse topological order.\n for (BBVector::const_reverse_iterator RI = SortedBBs.rbegin(),\n RE = SortedBBs.rend();\n RI != RE; ++RI) {\n outs() << \" \" << (*RI)->getName() << \"\\n\";\n }\n } else {\n outs() << \" Sorting failed\\n\";\n }\n }\nprivate:\n enum Color {WHITE, GREY, BLACK};\n \/\/ Color marks per vertex (BB).\n typedef DenseMap BBColorMap;\n \/\/ Collects vertices (BBs) in \"finish\" order. The first finished vertex is\n \/\/ first, and so on.\n typedef SmallVector BBVector;\n BBColorMap ColorMap;\n BBVector SortedBBs;\n\n \/\/ Helper function to recursively run topological sort from a given BB.\n \/\/ Returns true if the sort succeeded and false otherwise; topological sort\n \/\/ may fail if, for example, the graph is not a DAG (detected a cycle).\n bool recursiveDFSToposort(const BasicBlock *BB) {\n ColorMap[BB] = TopoSorter::GREY;\n \/\/ For demonstration, using the lowest-level APIs here. A BB's successors\n \/\/ are determined by looking at its terminator instruction.\n const TerminatorInst *TInst = BB->getTerminator();\n for (unsigned I = 0, NSucc = TInst->getNumSuccessors(); I < NSucc; ++I) {\n BasicBlock *Succ = TInst->getSuccessor(I);\n Color SuccColor = ColorMap[Succ];\n if (SuccColor == TopoSorter::WHITE) {\n if (!recursiveDFSToposort(Succ))\n return false;\n } else if (SuccColor == TopoSorter::GREY) {\n \/\/ This detects a cycle because grey vertices are all ancestors of the\n \/\/ currently explored vertex (in other words, they're \"on the stack\").\n outs() << \" Detected cycle: edge from \" << BB->getName() << \n \" to \" << Succ->getName() << \"\\n\";\n return false;\n }\n }\n \/\/ This BB is finished (fully explored), so we can add it to the vector.\n ColorMap[BB] = TopoSorter::BLACK;\n SortedBBs.push_back(BB);\n return true;\n }\n};\n\n\nclass AnalyzeBBGraph : public FunctionPass {\npublic:\n AnalyzeBBGraph(const std::string &AnalysisKind) \n : FunctionPass(ID), AnalysisKind(AnalysisKind)\n {}\n\n virtual bool runOnFunction(Function &F) {\n if (AnalysisKind == \"-topo\") {\n TopoSorter TS;\n TS.runToposort(F);\n } else if (AnalysisKind == \"-po\") {\n \/\/ Use LLVM's post-order iterator to produce a reverse topological sort.\n \/\/ Note that this doesn't detect cycles so if the graph is not a DAG, the\n \/\/ result is not a true topological sort.\n outs() << \"Basic blocks of \" << F.getName() << \" in post-order:\\n\";\n for (po_iterator I = po_begin(&F.getEntryBlock()),\n IE = po_end(&F.getEntryBlock());\n I != IE; ++I) {\n outs() << \" \" << (*I)->getName() << \"\\n\";\n } \n } else {\n outs() << \"Unknown analysis kind: \" << AnalysisKind << \"\\n\";\n }\n return false;\n }\n\n \/\/ The address of this member is used to uniquely identify the class. This is\n \/\/ used by LLVM's own RTTI mechanism.\n static char ID;\nprivate:\n std::string AnalysisKind;\n};\n\nchar AnalyzeBBGraph::ID = 0;\n\nint main(int argc, char **argv) {\n if (argc < 3) {\n \/\/ Using very basic command-line argument parsing here...\n errs() << \"Usage: \" << argv[0] << \" -[topo|po|scc] \\n\";\n return 1;\n }\n\n \/\/ Parse the input LLVM IR file into a module.\n SMDiagnostic Err;\n Module *Mod = ParseIRFile(argv[2], Err, getGlobalContext());\n if (!Mod) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n \/\/ Create a pass manager and fill it with the passes we want to run.\n PassManager PM;\n PM.add(new AnalyzeBBGraph(std::string(argv[1])));\n PM.run(*Mod);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* sim_connection.cpp\n *\n * libpsx\n *\n * Copyright (C) 2015, Christopher Collins\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n * USA\n*\/\n#include \"psx.h\"\n#include \n#include \n#ifdef _WIN32\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\nusing namespace std;\nusing namespace psx;\n\nSimConnection::SimConnection(const std::string &hostname, int port)\n : hostname(hostname), port(port)\n{\n msgMutex = SDL_CreateMutex();\n}\n\nSimConnection::~SimConnection()\n{\n stopListener();\n if (NULL != msgMutex) {\n SDL_DestroyMutex(msgMutex);\n msgMutex = NULL;\n }\n}\n\nbool\nSimConnection::connect()\n{\n char serviceName[16];\n snprintf(serviceName, 16, \"%d\", port);\n serviceName[15] = '\\0';\n\n struct addrinfo addrHints = {\n ai_flags: AI_NUMERICSERV | AI_ADDRCONFIG,\n ai_family: AF_INET,\n ai_socktype: SOCK_STREAM,\n };\n\n struct addrinfo *results = NULL;\n if (getaddrinfo(hostname.c_str(), serviceName, &addrHints, &results)) {\n return false;\n }\n\n socket_fd = socket(results->ai_family, results->ai_socktype, 0);\n if (-1 == socket_fd) {\n perror(\"connect: socket\");\n return false;\n }\n int nodelay = 1;\n setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));\n int retry_delay = base_retry_interval;\n while (running) {\n if (!::connect(socket_fd, results->ai_addr, results->ai_addrlen)) {\n return true;\n }\n SDL_Delay(retry_delay);\n if ((retry_delay * 2) <= max_retry_interval) {\n retry_delay *= 2;\n }\n }\n close(socket_fd);\n return false;\n}\n\nvoid\nSimConnection::stopListener()\n{\n running = false;\n \/\/ force shtudown the socket - this should trip a 0 byte iop in the listener which will let it die.\n if (socket_fd >= 0) {\n shutdown(socket_fd, SHUT_RDWR);\n }\n if (rcvThread != NULL) {\n SDL_WaitThread(rcvThread, NULL);\n rcvThread = NULL;\n }\n}\n\nextern \"C\" {\n static int\n bootstrapListener(void *data)\n {\n SimConnection *sc = static_cast(data);\n\n return sc->listener();\n }\n}\n\nvoid\nSimConnection::startListener()\n{\n if (NULL != rcvThread) {\n return;\n }\n running = true;\n rcvThread = SDL_CreateThread(bootstrapListener, \"PSXListener\", static_cast(this));\n}\n\nint\nSimConnection::listener()\n{\n while (running) {\n if (!connect()) {\n cerr << \"failed to connect\" << endl;\n continue;\n }\n\n std::string curMsg = \"\";\n while(running) {\n char cBuf;\n int len = recv(socket_fd, &cBuf, 1, 0);\n if (len > 0) {\n if (cBuf == '\\n') {\n interpret(curMsg);\n curMsg = \"\";\n } else {\n curMsg += cBuf;\n }\n } else {\n if (len < 0 && errno == EINTR) {\n continue;\n }\n \/\/ some kind of error. Reconnect.\n ::close(socket_fd);\n socket_fd = -1;\n break;\n }\n }\n }\n return 0;\n}\n\nvoid\nSimConnection::send(const std::string &msg)\n{\n ::send(socket_fd, msg.c_str(), msg.length(), 0);\n}\n\nvoid\nSimConnection::send(const WirePair &pair)\n{\n std::string wireString = pair.toWire();\n wireString += \"\\n\";\n\n send(wireString);\n}\nconform with ANSI syntax\/* sim_connection.cpp\n *\n * libpsx\n *\n * Copyright (C) 2015, Christopher Collins\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n * USA\n*\/\n#include \"psx.h\"\n#include \n#include \n#ifdef _WIN32\n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\nusing namespace std;\nusing namespace psx;\n\nSimConnection::SimConnection(const std::string &hostname, int port)\n : hostname(hostname), port(port)\n{\n msgMutex = SDL_CreateMutex();\n}\n\nSimConnection::~SimConnection()\n{\n stopListener();\n if (NULL != msgMutex) {\n SDL_DestroyMutex(msgMutex);\n msgMutex = NULL;\n }\n}\n\nbool\nSimConnection::connect()\n{\n char serviceName[16];\n snprintf(serviceName, 16, \"%d\", port);\n serviceName[15] = '\\0';\n\n struct addrinfo addrHints = {\n .ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG,\n .ai_family = AF_INET,\n .ai_socktype = SOCK_STREAM,\n };\n\n struct addrinfo *results = NULL;\n if (getaddrinfo(hostname.c_str(), serviceName, &addrHints, &results)) {\n return false;\n }\n\n socket_fd = socket(results->ai_family, results->ai_socktype, 0);\n if (-1 == socket_fd) {\n perror(\"connect: socket\");\n return false;\n }\n int nodelay = 1;\n setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));\n int retry_delay = base_retry_interval;\n while (running) {\n if (!::connect(socket_fd, results->ai_addr, results->ai_addrlen)) {\n return true;\n }\n SDL_Delay(retry_delay);\n if ((retry_delay * 2) <= max_retry_interval) {\n retry_delay *= 2;\n }\n }\n close(socket_fd);\n return false;\n}\n\nvoid\nSimConnection::stopListener()\n{\n running = false;\n \/\/ force shtudown the socket - this should trip a 0 byte iop in the listener which will let it die.\n if (socket_fd >= 0) {\n shutdown(socket_fd, SHUT_RDWR);\n }\n if (rcvThread != NULL) {\n SDL_WaitThread(rcvThread, NULL);\n rcvThread = NULL;\n }\n}\n\nextern \"C\" {\n static int\n bootstrapListener(void *data)\n {\n SimConnection *sc = static_cast(data);\n\n return sc->listener();\n }\n}\n\nvoid\nSimConnection::startListener()\n{\n if (NULL != rcvThread) {\n return;\n }\n running = true;\n rcvThread = SDL_CreateThread(bootstrapListener, \"PSXListener\", static_cast(this));\n}\n\nint\nSimConnection::listener()\n{\n while (running) {\n if (!connect()) {\n cerr << \"failed to connect\" << endl;\n continue;\n }\n\n std::string curMsg = \"\";\n while(running) {\n char cBuf;\n int len = recv(socket_fd, &cBuf, 1, 0);\n if (len > 0) {\n if (cBuf == '\\n') {\n interpret(curMsg);\n curMsg = \"\";\n } else {\n curMsg += cBuf;\n }\n } else {\n if (len < 0 && errno == EINTR) {\n continue;\n }\n \/\/ some kind of error. Reconnect.\n ::close(socket_fd);\n socket_fd = -1;\n break;\n }\n }\n }\n return 0;\n}\n\nvoid\nSimConnection::send(const std::string &msg)\n{\n ::send(socket_fd, msg.c_str(), msg.length(), 0);\n}\n\nvoid\nSimConnection::send(const WirePair &pair)\n{\n std::string wireString = pair.toWire();\n wireString += \"\\n\";\n\n send(wireString);\n}\n<|endoftext|>"} {"text":"#include \"..\/Block_Diagonal_Matrix.hxx\"\n\n\/\/ Minimum eigenvalue of A. A is assumed to be symmetric.\n\n\/\/ Annoyingly, El::HermitianEig modifies 'block'. It is OK, because\n\/\/ it is only called from step_length(), which passes in a temporary.\n\/\/ Still ugly.\nEl::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)\n{\n El::BigFloat local_min(El::limits::Max());\n\n for(auto &block : A.blocks)\n {\n El::DistMatrix eigenvalues(block.Grid());\n El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues);\n local_min = El::Min(local_min, El::Min(eigenvalues));\n }\n return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);\n}\nWork around a bug in Elemental eigenvalue computation#include \"..\/Block_Diagonal_Matrix.hxx\"\n\n\/\/ Minimum eigenvalue of A. A is assumed to be symmetric.\n\n\/\/ Annoyingly, El::HermitianEig modifies 'block'. It is OK, because\n\/\/ it is only called from step_length(), which passes in a temporary.\n\/\/ Still ugly.\nEl::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)\n{\n El::BigFloat local_min(El::limits::Max());\n\n for(auto &block : A.blocks)\n {\n El::DistMatrix eigenvalues(block.Grid());\n \/\/\/ There is a bug in El::HermitianEig when there is more than\n \/\/\/ one level of recursion when computing eigenvalues. One fix\n \/\/\/ is to increase the cutoff so that there is no more than one\n \/\/\/ level of recursion.\n\n \/\/\/ An alternate workaround is to compute both eigenvalues and\n \/\/\/ eigenvectors, but that seems to be significantly slower.\n El::HermitianEigCtrl hermitian_eig_ctrl;\n hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff=block.Height()\/2+1;\n\n El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues);\n local_min = El::Min(local_min, El::Min(eigenvalues));\n }\n return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);\n}\n<|endoftext|>"} {"text":"\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\/**\n * @file\n * @brief Droneshare API Query Object\n *\n * @author Bill Bonney \n *\/\n\n#include \"QsLog.h\"\n#include \"AutoUpdateCheck.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"QGC.h\"\n\n#define VERSION_REGEX \"(\\\\d*\\\\.\\\\d+\\\\.?\\\\d+)-?(rc\\\\d)?\"\n\n\nAutoUpdateCheck::AutoUpdateCheck(QObject *parent) :\n QObject(parent),\n m_networkReply(NULL),\n m_httpRequestAborted(false),\n m_suppressNoUpdateSignal(false)\n{\n loadSettings();\n}\n\nvoid AutoUpdateCheck::forcedAutoUpdateCheck()\n{\n loadSettings();\n setSkipVersion(\"0.0.0\");\n autoUpdateCheck();\n}\n\nvoid AutoUpdateCheck::autoUpdateCheck()\n{\n autoUpdateCheck(QUrl(AUTOUPDATE_VERSION_OBJECT_LOCATION\n + AUTOUPDATE_VERSION_OBJECT_NAME));\n}\n\nvoid AutoUpdateCheck::autoUpdateCheck(const QUrl &url)\n{\n QLOG_DEBUG() << \"retrieve versionobject from server: \" + url.toString();\n\n m_url = QUrl(url);\n\n if (m_networkReply != NULL){\n delete m_networkReply;\n m_networkReply = NULL;\n }\n m_networkReply = m_networkAccessManager.get(QNetworkRequest(m_url));\n connect(m_networkReply, SIGNAL(finished()), this, SLOT(httpFinished()));\n connect(m_networkReply, SIGNAL(downloadProgress(qint64,qint64)),\n this, SLOT(updateDataReadProgress(qint64,qint64)));\n}\n\nvoid AutoUpdateCheck::cancelDownload()\n{\n m_httpRequestAborted = true;\n m_networkReply->abort();\n}\n\nvoid AutoUpdateCheck::httpFinished()\n{\n QLOG_DEBUG() << \"AutoUpdateCheck::httpFinished()\";\n if (m_httpRequestAborted) {\n m_networkReply->deleteLater();\n m_networkReply = NULL;\n return;\n }\n\n \/\/ Finished donwloading the version information\n if (m_networkReply->error()) {\n \/\/ [TODO] cleanup download failed\n#ifdef QT_DEBUG\n QMessageBox::information(NULL, tr(\"HTTP\"),\n tr(\"Download failed: %1.\")\n .arg(m_networkReply->errorString()));\n#endif\n } else {\n \/\/ Process downloadeed object\n processDownloadedVersionObject(QString(m_networkReply->readAll()));\n }\n\n m_networkReply->deleteLater();\n m_networkReply = NULL;\n}\n\nvoid AutoUpdateCheck::processDownloadedVersionObject(const QString &versionObject)\n{\n QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(versionObject);\n QScriptEngine engine;\n QScriptValue result = engine.evaluate(\"(\"+versionObject+\")\");\n\n if (engine.hasUncaughtException()){\n QLOG_ERROR() << \"Error evaluating version object\";\n QLOG_ERROR() << \"Error @line#\" << engine.uncaughtExceptionLineNumber();\n QLOG_ERROR() << \"Backtrace:\" << engine.uncaughtExceptionBacktrace();\n QLOG_ERROR() << \"Syntax Check:\" << syntaxCheck.errorMessage();\n QLOG_ERROR() << \"Syntax Check line:\" << syntaxCheck.errorLineNumber()\n << \" col:\" << syntaxCheck.errorColumnNumber();\n return;\n }\n\n QScriptValue entries = result.property(\"releases\");\n QScriptValueIterator it(entries);\n while (it.hasNext()){\n it.next();\n QScriptValue entry = it.value();\n\n QString platform = entry.property(\"platform\").toString();\n QString type = entry.property(\"type\").toString();\n QString version = entry.property(\"version\").toString();\n QString name = entry.property(\"name\").toString();\n QString locationUrl = entry.property(\"url\").toString();\n\n if ((platform == define2string(APP_PLATFORM)) && (type == m_releaseType)){\n if (compareVersionStrings(version,QGC_APPLICATION_VERSION)){\n QLOG_DEBUG() << \"Found New Version: \" << platform << \" \"\n << type << \" \" << version << \" \" << locationUrl;\n if(m_skipVerison != version){\n emit updateAvailable(version, type, locationUrl, name);\n } else {\n QLOG_INFO() << \"Version Skipped at user request\";\n }\n break;\n } else {\n QLOG_INFO() << \"no new update available\";\n if (!m_suppressNoUpdateSignal){\n emit noUpdateAvailable();\n }\n m_suppressNoUpdateSignal = false;\n }\n }\n }\n}\n\nvoid AutoUpdateCheck::httpReadyRead()\n{\n\n}\n\nvoid AutoUpdateCheck::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)\n{\n if (m_httpRequestAborted)\n return;\n QLOG_DEBUG() << \"Downloading:\" << bytesRead << \"\/\" << totalBytes;\n}\n\nbool AutoUpdateCheck::compareVersionStrings(const QString& newVersion, const QString& currentVersion)\n{\n \/\/ [TODO] DRY this out by creating global function for use in APM Firmware as well\n int newMajor,newMinor,newBuild = 0;\n int currentMajor, currentMinor,currentBuild = 0;\n\n QString newBuildSubMoniker, oldBuildSubMoniker; \/\/ holds if the build is a rc or dev build\n\n\n QRegExp versionEx(VERSION_REGEX);\n QString versionstr = \"\";\n int pos = versionEx.indexIn(newVersion);\n if (pos > -1) {\n \/\/ Split first sub-element to get numercal major.minor.build version\n QLOG_DEBUG() << \"Detected newVersion:\" << versionEx.capturedTexts()<< \" count:\"\n << versionEx.captureCount();\n versionstr = versionEx.cap(1);\n QStringList versionList = versionstr.split(\".\");\n newMajor = versionList[0].toInt();\n newMinor = versionList[1].toInt();\n if (versionList.size() > 2){\n newBuild = versionList[2].toInt();\n }\n \/\/ second subelement is either rcX candidate or developement build\n if (versionEx.captureCount() == 2)\n newBuildSubMoniker = versionEx.cap(2);\n }\n\n QRegExp versionEx2(VERSION_REGEX);\n versionstr = \"\";\n pos = versionEx2.indexIn(currentVersion);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected currentVersion:\" << versionEx2.capturedTexts() << \" count:\"\n << versionEx2.captureCount();\n versionstr = versionEx2.cap(1);\n QStringList versionList = versionstr.split(\".\");\n currentMajor = versionList[0].toInt();\n currentMinor = versionList[1].toInt();\n if (versionList.size() > 2){\n currentBuild = versionList[2].toInt();\n }\n \/\/ second subelement is either rcX candidate or developement build\n if (versionEx2.captureCount() == 2)\n oldBuildSubMoniker = versionEx2.cap(2);\n }\n\n QLOG_DEBUG() << \"Verison Compare:\" <currentMajor){\n \/\/ A Major release\n return true;\n } else if (newMajor == currentMajor){\n if (newMinor > currentMinor){\n \/\/ A minor release\n return true;\n } else if (newMinor == currentMinor){\n if (newBuild > currentBuild)\n \/\/ new build (or tiny release)\n return true;\n else if (newBuild == currentBuild) {\n \/\/ Check if RC is newer\n \/\/ If the version isn't newer, it might be a new release candidate\n int newRc = 0, oldRc = 0;\n\n if (newBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)\n && oldBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)) {\n QRegExp releaseNumber(\"\\\\d+\");\n pos = releaseNumber.indexIn(newBuildSubMoniker);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected newRc:\" << versionEx.capturedTexts();\n newRc = releaseNumber.cap(0).toInt();\n }\n\n QRegExp releaseNumber2(\"\\\\d+\");\n pos = releaseNumber2.indexIn(oldBuildSubMoniker);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected oldRc:\" << versionEx2.capturedTexts();\n oldRc = releaseNumber.cap(0).toInt();\n }\n\n if (newRc > oldRc)\n return true;\n }\n\n if (newBuildSubMoniker.length() == 0\n && oldBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)) {\n QLOG_DEBUG() << \"Stable build newer that last unstable release candidate \";\n return true; \/\/ this means a new stable build of the unstable rc is available\n }\n }\n }\n }\n\n\n\n return false;\n}\n\nvoid AutoUpdateCheck::setSkipVersion(const QString& version)\n{\n m_skipVerison = version;\n writeSettings();\n}\n\nvoid AutoUpdateCheck::setAutoUpdateEnabled(bool enabled)\n{\n m_isAutoUpdateEnabled = enabled;\n writeSettings();\n}\n\nbool AutoUpdateCheck::isUpdateEnabled()\n{\n return m_isAutoUpdateEnabled;\n}\n\nvoid AutoUpdateCheck::loadSettings()\n{\n \/\/ Load defaults from settings\n QSettings settings;\n settings.beginGroup(\"AUTO_UPDATE\");\n m_isAutoUpdateEnabled = settings.value(\"ENABLED\", true).toBool();\n m_skipVerison = settings.value(\"SKIP_VERSION\", \"0.0.0\").toString();\n m_releaseType = settings.value(\"RELEASE_TYPE\", define2string(APP_TYPE)).toString();\n settings.endGroup();\n}\n\nvoid AutoUpdateCheck::writeSettings()\n{\n \/\/ Store settings\n QSettings settings;\n settings.beginGroup(\"AUTO_UPDATE\");\n settings.setValue(\"ENABLED\", m_isAutoUpdateEnabled);\n settings.setValue(\"SKIP_VERSION\", m_skipVerison);\n settings.setValue(\"RELEASE_TYPE\", m_releaseType);\n settings.endGroup();\n settings.sync();\n}\n\nvoid AutoUpdateCheck::suppressNoUpdateSignal()\n{\n m_suppressNoUpdateSignal = true;\n}\nAutoupdate: Fixes RC version compare\/*===================================================================\nAPM_PLANNER Open Source Ground Control Station\n\n(c) 2014 APM_PLANNER PROJECT \n\nThis file is part of the APM_PLANNER project\n\n APM_PLANNER is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n APM_PLANNER is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with APM_PLANNER. If not, see .\n\n======================================================================*\/\n\/**\n * @file\n * @brief Droneshare API Query Object\n *\n * @author Bill Bonney \n *\/\n\n#include \"QsLog.h\"\n#include \"AutoUpdateCheck.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"QGC.h\"\n\n#define VERSION_REGEX \"(\\\\d*\\\\.\\\\d+\\\\.?\\\\d+)-?(rc\\\\d)?\"\n\n\nAutoUpdateCheck::AutoUpdateCheck(QObject *parent) :\n QObject(parent),\n m_networkReply(NULL),\n m_httpRequestAborted(false),\n m_suppressNoUpdateSignal(false)\n{\n loadSettings();\n}\n\nvoid AutoUpdateCheck::forcedAutoUpdateCheck()\n{\n loadSettings();\n setSkipVersion(\"0.0.0\");\n autoUpdateCheck();\n}\n\nvoid AutoUpdateCheck::autoUpdateCheck()\n{\n autoUpdateCheck(QUrl(AUTOUPDATE_VERSION_OBJECT_LOCATION\n + AUTOUPDATE_VERSION_OBJECT_NAME));\n}\n\nvoid AutoUpdateCheck::autoUpdateCheck(const QUrl &url)\n{\n QLOG_DEBUG() << \"retrieve versionobject from server: \" + url.toString();\n\n m_url = QUrl(url);\n\n if (m_networkReply != NULL){\n delete m_networkReply;\n m_networkReply = NULL;\n }\n m_networkReply = m_networkAccessManager.get(QNetworkRequest(m_url));\n connect(m_networkReply, SIGNAL(finished()), this, SLOT(httpFinished()));\n connect(m_networkReply, SIGNAL(downloadProgress(qint64,qint64)),\n this, SLOT(updateDataReadProgress(qint64,qint64)));\n}\n\nvoid AutoUpdateCheck::cancelDownload()\n{\n m_httpRequestAborted = true;\n m_networkReply->abort();\n}\n\nvoid AutoUpdateCheck::httpFinished()\n{\n QLOG_DEBUG() << \"AutoUpdateCheck::httpFinished()\";\n if (m_httpRequestAborted) {\n m_networkReply->deleteLater();\n m_networkReply = NULL;\n return;\n }\n\n \/\/ Finished donwloading the version information\n if (m_networkReply->error()) {\n \/\/ [TODO] cleanup download failed\n#ifdef QT_DEBUG\n QMessageBox::information(NULL, tr(\"HTTP\"),\n tr(\"Download failed: %1.\")\n .arg(m_networkReply->errorString()));\n#endif\n } else {\n \/\/ Process downloadeed object\n processDownloadedVersionObject(QString(m_networkReply->readAll()));\n }\n\n m_networkReply->deleteLater();\n m_networkReply = NULL;\n}\n\nvoid AutoUpdateCheck::processDownloadedVersionObject(const QString &versionObject)\n{\n QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(versionObject);\n QScriptEngine engine;\n QScriptValue result = engine.evaluate(\"(\"+versionObject+\")\");\n\n if (engine.hasUncaughtException()){\n QLOG_ERROR() << \"Error evaluating version object\";\n QLOG_ERROR() << \"Error @line#\" << engine.uncaughtExceptionLineNumber();\n QLOG_ERROR() << \"Backtrace:\" << engine.uncaughtExceptionBacktrace();\n QLOG_ERROR() << \"Syntax Check:\" << syntaxCheck.errorMessage();\n QLOG_ERROR() << \"Syntax Check line:\" << syntaxCheck.errorLineNumber()\n << \" col:\" << syntaxCheck.errorColumnNumber();\n return;\n }\n\n QScriptValue entries = result.property(\"releases\");\n QScriptValueIterator it(entries);\n while (it.hasNext()){\n it.next();\n QScriptValue entry = it.value();\n\n QString platform = entry.property(\"platform\").toString();\n QString type = entry.property(\"type\").toString();\n QString version = entry.property(\"version\").toString();\n QString name = entry.property(\"name\").toString();\n QString locationUrl = entry.property(\"url\").toString();\n\n if ((platform == define2string(APP_PLATFORM)) && (type == m_releaseType)){\n if (compareVersionStrings(version,QGC_APPLICATION_VERSION)){\n QLOG_DEBUG() << \"Found New Version: \" << platform << \" \"\n << type << \" \" << version << \" \" << locationUrl;\n if(m_skipVerison != version){\n emit updateAvailable(version, type, locationUrl, name);\n } else {\n QLOG_INFO() << \"Version Skipped at user request\";\n }\n break;\n } else {\n QLOG_INFO() << \"no new update available\";\n if (!m_suppressNoUpdateSignal){\n emit noUpdateAvailable();\n }\n m_suppressNoUpdateSignal = false;\n }\n }\n }\n}\n\nvoid AutoUpdateCheck::httpReadyRead()\n{\n\n}\n\nvoid AutoUpdateCheck::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)\n{\n if (m_httpRequestAborted)\n return;\n QLOG_DEBUG() << \"Downloading:\" << bytesRead << \"\/\" << totalBytes;\n}\n\nbool AutoUpdateCheck::compareVersionStrings(const QString& newVersion, const QString& currentVersion)\n{\n \/\/ [TODO] DRY this out by creating global function for use in APM Firmware as well\n int newMajor,newMinor,newBuild = 0;\n int currentMajor, currentMinor,currentBuild = 0;\n\n QString newBuildSubMoniker, oldBuildSubMoniker; \/\/ holds if the build is a rc or dev build\n\n\n QRegExp versionEx(VERSION_REGEX);\n QString versionstr = \"\";\n int pos = versionEx.indexIn(newVersion);\n if (pos > -1) {\n \/\/ Split first sub-element to get numercal major.minor.build version\n QLOG_DEBUG() << \"Detected newVersion:\" << versionEx.capturedTexts()<< \" count:\"\n << versionEx.captureCount();\n versionstr = versionEx.cap(1);\n QStringList versionList = versionstr.split(\".\");\n newMajor = versionList[0].toInt();\n newMinor = versionList[1].toInt();\n if (versionList.size() > 2){\n newBuild = versionList[2].toInt();\n }\n \/\/ second subelement is either rcX candidate or developement build\n if (versionEx.captureCount() == 2)\n newBuildSubMoniker = versionEx.cap(2);\n }\n\n QRegExp versionEx2(VERSION_REGEX);\n versionstr = \"\";\n pos = versionEx2.indexIn(currentVersion);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected currentVersion:\" << versionEx2.capturedTexts() << \" count:\"\n << versionEx2.captureCount();\n versionstr = versionEx2.cap(1);\n QStringList versionList = versionstr.split(\".\");\n currentMajor = versionList[0].toInt();\n currentMinor = versionList[1].toInt();\n if (versionList.size() > 2){\n currentBuild = versionList[2].toInt();\n }\n \/\/ second subelement is either rcX candidate or developement build\n if (versionEx2.captureCount() == 2)\n oldBuildSubMoniker = versionEx2.cap(2);\n }\n\n QLOG_DEBUG() << \"Verison Compare:\" <currentMajor){\n \/\/ A Major release\n return true;\n } else if (newMajor == currentMajor){\n if (newMinor > currentMinor){\n \/\/ A minor release\n return true;\n } else if (newMinor == currentMinor){\n if (newBuild > currentBuild)\n \/\/ new build (or tiny release)\n return true;\n else if (newBuild == currentBuild) {\n \/\/ Check if RC is newer\n \/\/ If the version isn't newer, it might be a new release candidate\n int newRc = 0, oldRc = 0;\n\n if (newBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)\n && oldBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)) {\n QRegExp releaseNumber(\"\\\\d+\");\n pos = releaseNumber.indexIn(newBuildSubMoniker);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected newRc:\" << versionEx.capturedTexts();\n newRc = releaseNumber.cap(0).toInt();\n }\n\n QRegExp releaseNumber2(\"\\\\d+\");\n pos = releaseNumber2.indexIn(oldBuildSubMoniker);\n if (pos > -1) {\n QLOG_DEBUG() << \"Detected oldRc:\" << versionEx2.capturedTexts();\n oldRc = releaseNumber2.cap(0).toInt();\n }\n\n if (newRc > oldRc)\n return true;\n }\n\n if (newBuildSubMoniker.length() == 0\n && oldBuildSubMoniker.startsWith(\"RC\", Qt::CaseInsensitive)) {\n QLOG_DEBUG() << \"Stable build newer that last unstable release candidate \";\n return true; \/\/ this means a new stable build of the unstable rc is available\n }\n }\n }\n }\n\n\n\n return false;\n}\n\nvoid AutoUpdateCheck::setSkipVersion(const QString& version)\n{\n m_skipVerison = version;\n writeSettings();\n}\n\nvoid AutoUpdateCheck::setAutoUpdateEnabled(bool enabled)\n{\n m_isAutoUpdateEnabled = enabled;\n writeSettings();\n}\n\nbool AutoUpdateCheck::isUpdateEnabled()\n{\n return m_isAutoUpdateEnabled;\n}\n\nvoid AutoUpdateCheck::loadSettings()\n{\n \/\/ Load defaults from settings\n QSettings settings;\n settings.beginGroup(\"AUTO_UPDATE\");\n m_isAutoUpdateEnabled = settings.value(\"ENABLED\", true).toBool();\n m_skipVerison = settings.value(\"SKIP_VERSION\", \"0.0.0\").toString();\n m_releaseType = settings.value(\"RELEASE_TYPE\", define2string(APP_TYPE)).toString();\n settings.endGroup();\n}\n\nvoid AutoUpdateCheck::writeSettings()\n{\n \/\/ Store settings\n QSettings settings;\n settings.beginGroup(\"AUTO_UPDATE\");\n settings.setValue(\"ENABLED\", m_isAutoUpdateEnabled);\n settings.setValue(\"SKIP_VERSION\", m_skipVerison);\n settings.setValue(\"RELEASE_TYPE\", m_releaseType);\n settings.endGroup();\n settings.sync();\n}\n\nvoid AutoUpdateCheck::suppressNoUpdateSignal()\n{\n m_suppressNoUpdateSignal = true;\n}\n<|endoftext|>"} {"text":"#ifndef KISSFFT_CLASS_HH\n#define KISSFFT_CLASS_HH\n#include \n#include \n\n\ntemplate \n >\nclass kissfft\n{\n public:\n typedef T_Scalar scalar_type;\n typedef T_Complex cpx_type;\n\n kissfft( std::size_t nfft,\n bool inverse )\n :_nfft(nfft)\n ,_inverse(inverse)\n {\n \/\/ fill twiddle factors\n _twiddles.resize(_nfft);\n const scalar_type phinc = (_inverse?2:-2)* acos( (scalar_type) -1) \/ _nfft;\n for (std::size_t i=0;i<_nfft;++i)\n _twiddles[i] = exp( cpx_type(0,i*phinc) );\n\n \/\/factorize\n \/\/start factoring out 4's, then 2's, then 3,5,7,9,...\n std::size_t n= _nfft;\n std::size_t p=4;\n do {\n while (n % p) {\n switch (p) {\n case 4: p = 2; break;\n case 2: p = 3; break;\n default: p += 2; break;\n }\n if (p*p>n)\n p = n;\/\/ no more factors\n }\n n \/= p;\n _stageRadix.push_back(p);\n _stageRemainder.push_back(n);\n }while(n>1);\n }\n\n \/\/\/ Calculates the complex Discrete Fourier Transform.\n \/\/\/\n \/\/\/ The size of the passed arrays must be passed in the constructor.\n \/\/\/ The sum of the squares of the absolute values in the @c dst\n \/\/\/ array will be @c N times the sum of the squares of the absolute\n \/\/\/ values in the @c src array, where @c N is the size of the array.\n \/\/\/ In other words, the l_2 norm of the resulting array will be\n \/\/\/ @c sqrt(N) times as big as the l_2 norm of the input array.\n \/\/\/ This is also the case when the inverse flag is set in the\n \/\/\/ constructor. Hence when applying the same transform twice, but with\n \/\/\/ the inverse flag changed the second time, then the result will\n \/\/\/ be equal to the original input times @c N.\n void transform( const cpx_type * src,\n cpx_type * dst ) const\n {\n kf_work(0, dst, src, 1,1);\n }\n\n \/\/\/ Calculates the Discrete Fourier Transform (DFT) of a real input\n \/\/\/ of size @c 2*N.\n \/\/\/\n \/\/\/ The 0-th and N-th value of the DFT are real numbers. These are\n \/\/\/ stored in @c dst[0].real() and @c dst[1].imag() respectively.\n \/\/\/ The remaining DFT values up to the index N-1 are stored in\n \/\/\/ @c dst[1] to @c dst[N-1].\n \/\/\/ The other half of the DFT values can be calculated from the\n \/\/\/ symmetry relation\n \/\/\/ @code\n \/\/\/ DFT(src)[2*N-k] == conj( DFT(src)[k] );\n \/\/\/ @endcode\n \/\/\/ The same scaling factors as in @c transform() apply.\n \/\/\/\n \/\/\/ @note For this to work, the types @c scalar_type and @c cpx_type\n \/\/\/ must fulfill the following requirements:\n \/\/\/\n \/\/\/ For any object @c z of type @c cpx_type,\n \/\/\/ @c reinterpret_cast(z)[0] is the real part of @c z and\n \/\/\/ @c reinterpret_cast(z)[1] is the imaginary part of @c z.\n \/\/\/ For any pointer to an element of an array of @c cpx_type named @c p\n \/\/\/ and any valid array index @c i, @c reinterpret_cast(p)[2*i]\n \/\/\/ is the real part of the complex number @c p[i], and\n \/\/\/ @c reinterpret_cast(p)[2*i+1] is the imaginary part of the\n \/\/\/ complex number @c p[i].\n \/\/\/\n \/\/\/ Since C++11, these requirements are guaranteed to be satisfied for\n \/\/\/ @c scalar_types being @c float, @c double or @c long @c double\n \/\/\/ together with @c cpx_type being @c std::complex.\n void transform_real( const scalar_type * src,\n cpx_type * dst ) const\n {\n const std::size_t N = _nfft;\n if ( N == 0 )\n return;\n\n \/\/ perform complex FFT\n transform( reinterpret_cast(src), dst );\n\n \/\/ post processing for k = 0 and k = N\n dst[0] = cpx_type( dst[0].real() + dst[0].imag(),\n dst[0].real() - dst[0].imag() );\n\n \/\/ post processing for all the other k = 1, 2, ..., N-1\n const scalar_type pi = acos( (scalar_type) -1);\n const scalar_type half_phi_inc = ( _inverse ? pi : -pi ) \/ N;\n const cpx_type twiddle_mul = exp( cpx_type(0, half_phi_inc) );\n for ( std::size_t k = 1; 2*k < N; ++k )\n {\n const cpx_type w = 0.5 * cpx_type(\n dst[k].real() + dst[N-k].real(),\n dst[k].imag() - dst[N-k].imag() );\n const cpx_type z = 0.5 * cpx_type(\n dst[k].imag() + dst[N-k].imag(),\n -dst[k].real() + dst[N-k].real() );\n const cpx_type twiddle =\n k % 2 == 0 ?\n _twiddles[k\/2] :\n _twiddles[k\/2] * twiddle_mul;\n dst[ k] = w + twiddle * z;\n dst[N-k] = conj( w - twiddle * z );\n }\n if ( N % 2 == 0 )\n dst[N\/2] = conj( dst[N\/2] );\n }\n\n private:\n void kf_work( std::size_t stage,\n cpx_type * Fout,\n const cpx_type * f,\n std::size_t fstride,\n std::size_t in_stride) const\n {\n const std::size_t p = _stageRadix[stage];\n const std::size_t m = _stageRemainder[stage];\n cpx_type * const Fout_beg = Fout;\n cpx_type * const Fout_end = Fout + p*m;\n\n if (m==1) {\n do{\n *Fout = *f;\n f += fstride*in_stride;\n }while(++Fout != Fout_end );\n }else{\n do{\n \/\/ recursive call:\n \/\/ DFT of size m*p performed by doing\n \/\/ p instances of smaller DFTs of size m, \n \/\/ each one takes a decimated version of the input\n kf_work(stage+1, Fout , f, fstride*p,in_stride);\n f += fstride*in_stride;\n }while( (Fout += m) != Fout_end );\n }\n\n Fout=Fout_beg;\n\n \/\/ recombine the p smaller DFTs \n switch (p) {\n case 2: kf_bfly2(Fout,fstride,m); break;\n case 3: kf_bfly3(Fout,fstride,m); break;\n case 4: kf_bfly4(Fout,fstride,m); break;\n case 5: kf_bfly5(Fout,fstride,m); break;\n default: kf_bfly_generic(Fout,fstride,m,p); break;\n }\n }\n\n void kf_bfly2( cpx_type * Fout, const size_t fstride, std::size_t m) const\n {\n for (std::size_t k=0;k=_nfft)\n twidx-=_nfft;\n Fout[ k ] += scratchbuf[q] * twiddles[twidx];\n }\n k += m;\n }\n }\n }\n\n std::size_t _nfft;\n bool _inverse;\n std::vector _twiddles;\n std::vector _stageRadix;\n std::vector _stageRemainder;\n};\n#endif\nNormalized identation in new code.#ifndef KISSFFT_CLASS_HH\n#define KISSFFT_CLASS_HH\n#include \n#include \n\n\ntemplate \n >\nclass kissfft\n{\n public:\n typedef T_Scalar scalar_type;\n typedef T_Complex cpx_type;\n\n kissfft( std::size_t nfft,\n bool inverse )\n :_nfft(nfft)\n ,_inverse(inverse)\n {\n \/\/ fill twiddle factors\n _twiddles.resize(_nfft);\n const scalar_type phinc = (_inverse?2:-2)* acos( (scalar_type) -1) \/ _nfft;\n for (std::size_t i=0;i<_nfft;++i)\n _twiddles[i] = exp( cpx_type(0,i*phinc) );\n\n \/\/factorize\n \/\/start factoring out 4's, then 2's, then 3,5,7,9,...\n std::size_t n= _nfft;\n std::size_t p=4;\n do {\n while (n % p) {\n switch (p) {\n case 4: p = 2; break;\n case 2: p = 3; break;\n default: p += 2; break;\n }\n if (p*p>n)\n p = n;\/\/ no more factors\n }\n n \/= p;\n _stageRadix.push_back(p);\n _stageRemainder.push_back(n);\n }while(n>1);\n }\n\n \/\/\/ Calculates the complex Discrete Fourier Transform.\n \/\/\/\n \/\/\/ The size of the passed arrays must be passed in the constructor.\n \/\/\/ The sum of the squares of the absolute values in the @c dst\n \/\/\/ array will be @c N times the sum of the squares of the absolute\n \/\/\/ values in the @c src array, where @c N is the size of the array.\n \/\/\/ In other words, the l_2 norm of the resulting array will be\n \/\/\/ @c sqrt(N) times as big as the l_2 norm of the input array.\n \/\/\/ This is also the case when the inverse flag is set in the\n \/\/\/ constructor. Hence when applying the same transform twice, but with\n \/\/\/ the inverse flag changed the second time, then the result will\n \/\/\/ be equal to the original input times @c N.\n void transform( const cpx_type * src,\n cpx_type * dst ) const\n {\n kf_work(0, dst, src, 1,1);\n }\n\n \/\/\/ Calculates the Discrete Fourier Transform (DFT) of a real input\n \/\/\/ of size @c 2*N.\n \/\/\/\n \/\/\/ The 0-th and N-th value of the DFT are real numbers. These are\n \/\/\/ stored in @c dst[0].real() and @c dst[1].imag() respectively.\n \/\/\/ The remaining DFT values up to the index N-1 are stored in\n \/\/\/ @c dst[1] to @c dst[N-1].\n \/\/\/ The other half of the DFT values can be calculated from the\n \/\/\/ symmetry relation\n \/\/\/ @code\n \/\/\/ DFT(src)[2*N-k] == conj( DFT(src)[k] );\n \/\/\/ @endcode\n \/\/\/ The same scaling factors as in @c transform() apply.\n \/\/\/\n \/\/\/ @note For this to work, the types @c scalar_type and @c cpx_type\n \/\/\/ must fulfill the following requirements:\n \/\/\/\n \/\/\/ For any object @c z of type @c cpx_type,\n \/\/\/ @c reinterpret_cast(z)[0] is the real part of @c z and\n \/\/\/ @c reinterpret_cast(z)[1] is the imaginary part of @c z.\n \/\/\/ For any pointer to an element of an array of @c cpx_type named @c p\n \/\/\/ and any valid array index @c i, @c reinterpret_cast(p)[2*i]\n \/\/\/ is the real part of the complex number @c p[i], and\n \/\/\/ @c reinterpret_cast(p)[2*i+1] is the imaginary part of the\n \/\/\/ complex number @c p[i].\n \/\/\/\n \/\/\/ Since C++11, these requirements are guaranteed to be satisfied for\n \/\/\/ @c scalar_types being @c float, @c double or @c long @c double\n \/\/\/ together with @c cpx_type being @c std::complex.\n void transform_real( const scalar_type * src,\n cpx_type * dst ) const\n {\n const std::size_t N = _nfft;\n if ( N == 0 )\n return;\n\n \/\/ perform complex FFT\n transform( reinterpret_cast(src), dst );\n\n \/\/ post processing for k = 0 and k = N\n dst[0] = cpx_type( dst[0].real() + dst[0].imag(),\n dst[0].real() - dst[0].imag() );\n\n \/\/ post processing for all the other k = 1, 2, ..., N-1\n const scalar_type pi = acos( (scalar_type) -1);\n const scalar_type half_phi_inc = ( _inverse ? pi : -pi ) \/ N;\n const cpx_type twiddle_mul = exp( cpx_type(0, half_phi_inc) );\n for ( std::size_t k = 1; 2*k < N; ++k )\n {\n const cpx_type w = 0.5 * cpx_type(\n dst[k].real() + dst[N-k].real(),\n dst[k].imag() - dst[N-k].imag() );\n const cpx_type z = 0.5 * cpx_type(\n dst[k].imag() + dst[N-k].imag(),\n -dst[k].real() + dst[N-k].real() );\n const cpx_type twiddle =\n k % 2 == 0 ?\n _twiddles[k\/2] :\n _twiddles[k\/2] * twiddle_mul;\n dst[ k] = w + twiddle * z;\n dst[N-k] = conj( w - twiddle * z );\n }\n if ( N % 2 == 0 )\n dst[N\/2] = conj( dst[N\/2] );\n }\n\n private:\n void kf_work( std::size_t stage,\n cpx_type * Fout,\n const cpx_type * f,\n std::size_t fstride,\n std::size_t in_stride) const\n {\n const std::size_t p = _stageRadix[stage];\n const std::size_t m = _stageRemainder[stage];\n cpx_type * const Fout_beg = Fout;\n cpx_type * const Fout_end = Fout + p*m;\n\n if (m==1) {\n do{\n *Fout = *f;\n f += fstride*in_stride;\n }while(++Fout != Fout_end );\n }else{\n do{\n \/\/ recursive call:\n \/\/ DFT of size m*p performed by doing\n \/\/ p instances of smaller DFTs of size m, \n \/\/ each one takes a decimated version of the input\n kf_work(stage+1, Fout , f, fstride*p,in_stride);\n f += fstride*in_stride;\n }while( (Fout += m) != Fout_end );\n }\n\n Fout=Fout_beg;\n\n \/\/ recombine the p smaller DFTs \n switch (p) {\n case 2: kf_bfly2(Fout,fstride,m); break;\n case 3: kf_bfly3(Fout,fstride,m); break;\n case 4: kf_bfly4(Fout,fstride,m); break;\n case 5: kf_bfly5(Fout,fstride,m); break;\n default: kf_bfly_generic(Fout,fstride,m,p); break;\n }\n }\n\n void kf_bfly2( cpx_type * Fout, const size_t fstride, std::size_t m) const\n {\n for (std::size_t k=0;k=_nfft)\n twidx-=_nfft;\n Fout[ k ] += scratchbuf[q] * twiddles[twidx];\n }\n k += m;\n }\n }\n }\n\n std::size_t _nfft;\n bool _inverse;\n std::vector _twiddles;\n std::vector _stageRadix;\n std::vector _stageRemainder;\n};\n#endif\n<|endoftext|>"} {"text":"\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2007 Jos van den Oever \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"strigiconfig.h\"\n#include \"oleinputstream.h\"\n#include \"oleendanalyzer.h\"\n#include \"subinputstream.h\"\n#include \"analysisresult.h\"\n#include \"fieldtypes.h\"\n#include \"textutils.h\"\n#include \nusing namespace Strigi;\nusing namespace std;\n\nvoid\nOleEndAnalyzerFactory::registerFields(FieldRegister& reg) {\n static const char summaryKey[] = {0xE0,0x85,0x9F,0xF2,0xF9,0x4F,0x68,0x10,\n 0xAB,0x91,0x08,0x00,0x2B,0x27,0xB3,0xD9};\n static const char docSummaryKey[]= {0x02,0xD5,0xCD,0xD5,0x9C,0x2E,0x1B,0x10,\n 0x93,0x97,0x08,0x00,0x2B,0x2C,0xF9,0xAE};\n const RegisteredField* r;\n string key;\n map* m;\n\n \/\/ register the fields for the Summary Information Stream\n key.assign(summaryKey, 16);\n m = &fieldsMaps[key];\n r = reg.registerField(\"content.title\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[2] = r;\n r = reg.registerField(\"content.subject\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[3] = r;\n r = reg.registerField(\"content.author\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[4] = r;\n r = reg.registerField(\"content.keyword\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[5] = r;\n r = reg.registerField(\"content.comment\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[6] = r;\n\n \/\/ register the fields for the Document Summary Information Stream\n key.assign(docSummaryKey, 16);\n m = &fieldsMaps[key];\n r = reg.registerField(\"category\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[2] = r;\n r = reg.registerField(\"presentationtarget\",FieldRegister::stringType, 1, 0);\n if (r) (*m)[3] = r;\n r = reg.registerField(\"manager\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[14] = r;\n r = reg.registerField(\"company\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[15] = r;\n}\nconst map*\nOleEndAnalyzerFactory::getFieldMap(const string& key) const {\n map >::const_iterator i\n = fieldsMaps.find(key);\n return (i == fieldsMaps.end()) ?0 :&i->second;\n}\n\/\/ parse with info from http:\/\/www.wotsit.org\/getfile.asp?file=wword8&sc=230027800\nbool\ntryFIB(AnalysisResult& ar, InputStream* in) {\n const char* d;\n int32_t size = 34;\n int32_t nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size\n || (unsigned char)d[0] != 0xec || (unsigned char)d[1] != 0xa5) {\n return false;\n }\n bool complex = d[10] & 4;\n if (complex) return false;\n int32_t fcMin = readLittleEndianInt32(d+24);\n int32_t fcMac = readLittleEndianInt32(d+28);\n \/\/ for some reason we need to add 512 here. No clue why.\n fcMin += 512;\n fcMac += 512;\n uint16_t csw = readLittleEndianUInt16(d+32);\n size += 2*csw + 2;\n nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size) return false;\n csw = readLittleEndianUInt16(d+size-2);\n size += 4*csw + 2;\n nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size) return false;\n csw = readLittleEndianUInt16(d+size-2);\n size += 8*csw;\n \n nread = in->read(d, fcMac, fcMac);\n in->reset(0);\n if (nread != fcMac) {\n return false;\n }\n const char *end = d+fcMac;\n d += fcMin;\n const char *p = d;\n string text;\n while (p < end) {\n switch (*p) {\n case 7: \/\/ cell\/row end\n case 12: \/\/ Page break \/ Section mark\n case 13: \/\/ Paragraph end\n case 14: \/\/ Column end\n case 19: \/\/ Field start\n if (p > d) {\n text.append(d, p-d);\n\t ar.addText(text.c_str(), text.size());\n\t }\n text.assign(\"\");\n d = p+1;\n\t break;\n case 21: \/\/ Field end\n text.assign(\"\");\n d = p+1;\n\t break;\n case 30: \/\/ Non-breaken hyphen\n if (p > d) text.append(d, p-d);\n text.append(\"-\");\n d = p+1;\n case 31: \/\/ Non-required hyphen\n if (p > d) text.append(d, p-d);\n d = p+1;\n\t break;\n case 160: \/\/ Non-breaking space\n if (p > d) text.append(d, p-d);\n text.append(\" \");\n d = p+1;\n default:;\n }\n\t++p;\n }\n return true;\n}\nbool\nOleEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {\n return OleInputStream::checkHeader(header, headersize);\n}\nbool\ntryThumbsdbEntry(const string& name, AnalysisResult& ar, InputStream* in) {\n static const char magic[] = {0x0c, 0, 0, 0, 0x01, 0, 0, 0};\n const char* d;\n uint32_t nread = in->read(d, 12, 12);\n if (nread != 12 || memcmp(magic, d, 8)) {\n in->reset(0);\n return false;\n }\n SubInputStream thumb(in, in->size()-12);\n ar.indexChild(name, 0, &thumb);\n return true;\n}\n\/**\n * Exctract images from a 'Pictures' field from a ppt file.\n * http:\/\/jakarta.apache.org\/poi\/apidocs\/org\/apache\/poi\/hslf\/model\/Picture.html\n **\/\nvoid\ntryPictures(AnalysisResult& ar, InputStream* in) {\n const char* d;\n int32_t nread = in->read(d, 25, 25);\n ostringstream s;\n int pos = 1;\n while (nread == 25) {\n uint32_t size = readLittleEndianInt32(d+4)-17;\n SubInputStream sub(in, size);\n s << \"Pictures\/\" << pos++;\n ar.indexChild(s.str(), 0, &sub);\n s.str(\"\");\n nread = in->read(d, 25, 25);\n }\n}\n\/\/ format description: http:\/\/jakarta.apache.org\/poi\/hpsf\/internals.html\nbool\nOleEndAnalyzer::tryPropertyStream(AnalysisResult& idx,\n InputStream* in) {\n static const char magic[] = {0xfe, 0xff, 0, 0};\n const char* d;\n uint32_t nread = in->read(d, 28, 28);\n in->reset(0);\n if (nread != 28 || memcmp(magic, d, 4)) {\n return false;\n }\n \/\/ read all the data\n nread = in->read(d, in->size(), in->size());\n if (nread != in->size()) {\n return false;\n }\n int32_t n = readLittleEndianUInt32(d+24);\n if (in->size() < 28+n*20) {\n return false;\n }\n for (int32_t i=0; i= in->size()) {\n return false;\n }\n handlePropertyStream(key, d+offset, d+in->size());\n }\n return true;\n}\nvoid\nOleEndAnalyzer::handleProperty(const RegisteredField* field, const char* data) {\n int32_t datatype = readLittleEndianInt32(data);\n \/\/ currently we only support null-terminated strings\n if (datatype == 30) {\n int32_t len = readLittleEndianInt32(data+4);\n if (len > 0) {\n result->addValue(field, data+8, len-1);\n }\n }\n}\nvoid\nOleEndAnalyzer::handlePropertyStream(const char* key, const char* data,\n const char* end) {\n \/\/ get the fieldtable\n string k(key, 16);\n const map* table = factory->getFieldMap(k);\n if (table == 0) {\n return;\n }\n\n int32_t len = readLittleEndianInt32(data);\n const char* p = data + 8;\n const char* n = data + readLittleEndianInt32(data+4)*4 + 8;\n if (len < 0 || (len > end-data) || n > end) {\n return;\n }\n map::const_iterator field;\n while (p < n) {\n int32_t id = readLittleEndianInt32(p);\n field = table->find(id);\n if (field != table->end()) {\n int32_t offset = readLittleEndianInt32(p+4);\n handleProperty(field->second, data+offset);\n }\n p += 8;\n }\n}\nchar\nOleEndAnalyzer::analyze(AnalysisResult& ar, InputStream* in) {\n if(!in)\n return -1;\n\n result = &ar;\n OleInputStream ole(in);\n InputStream *s = ole.nextEntry();\n if (ole.status()) {\n fprintf(stderr, \"error: %s\\n\", ole.error());\n\treturn -1;\n }\n while (s) {\n const string& name = ole.entryInfo().filename;\n if (name.size()) {\n\t if (tryFIB(ar, s)) {\n } else if (tryThumbsdbEntry(name, ar, s)) {\n } else if (name[0] == 5) {\n \/\/ todo: handle property stream\n tryPropertyStream(ar, s);\n } else if (name == \"Pictures\") {\n tryPictures(ar, s);\n } else {\n ar.indexChild(name, ole.entryInfo().mtime,\n s);\n }\n }\n s = ole.nextEntry();\n }\n if (ole.status() == Error) {\n m_error = ole.error();\n return -1;\n } else {\n m_error.resize(0);\n }\n return 0;\n}\nsmall fixes to avoid extracting special characters\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2007 Jos van den Oever \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"strigiconfig.h\"\n#include \"oleinputstream.h\"\n#include \"oleendanalyzer.h\"\n#include \"subinputstream.h\"\n#include \"analysisresult.h\"\n#include \"fieldtypes.h\"\n#include \"textutils.h\"\n#include \nusing namespace Strigi;\nusing namespace std;\n\nvoid\nOleEndAnalyzerFactory::registerFields(FieldRegister& reg) {\n static const char summaryKey[] = {0xE0,0x85,0x9F,0xF2,0xF9,0x4F,0x68,0x10,\n 0xAB,0x91,0x08,0x00,0x2B,0x27,0xB3,0xD9};\n static const char docSummaryKey[]= {0x02,0xD5,0xCD,0xD5,0x9C,0x2E,0x1B,0x10,\n 0x93,0x97,0x08,0x00,0x2B,0x2C,0xF9,0xAE};\n const RegisteredField* r;\n string key;\n map* m;\n\n \/\/ register the fields for the Summary Information Stream\n key.assign(summaryKey, 16);\n m = &fieldsMaps[key];\n r = reg.registerField(\"content.title\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[2] = r;\n r = reg.registerField(\"content.subject\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[3] = r;\n r = reg.registerField(\"content.author\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[4] = r;\n r = reg.registerField(\"content.keyword\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[5] = r;\n r = reg.registerField(\"content.comment\", FieldRegister::stringType, -1, 0);\n if (r) (*m)[6] = r;\n\n \/\/ register the fields for the Document Summary Information Stream\n key.assign(docSummaryKey, 16);\n m = &fieldsMaps[key];\n r = reg.registerField(\"category\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[2] = r;\n r = reg.registerField(\"presentationtarget\",FieldRegister::stringType, 1, 0);\n if (r) (*m)[3] = r;\n r = reg.registerField(\"manager\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[14] = r;\n r = reg.registerField(\"company\", FieldRegister::stringType, 1, 0);\n if (r) (*m)[15] = r;\n}\nconst map*\nOleEndAnalyzerFactory::getFieldMap(const string& key) const {\n map >::const_iterator i\n = fieldsMaps.find(key);\n return (i == fieldsMaps.end()) ?0 :&i->second;\n}\n\/\/ parse with info from http:\/\/www.wotsit.org\/getfile.asp?file=wword8&sc=230027800\nbool\ntryFIB(AnalysisResult& ar, InputStream* in) {\n const char* d;\n int32_t size = 34;\n int32_t nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size\n || (unsigned char)d[0] != 0xec || (unsigned char)d[1] != 0xa5) {\n return false;\n }\n bool complex = d[10] & 4;\n if (complex) return false;\n int32_t fcMin = readLittleEndianInt32(d+24);\n int32_t fcMac = readLittleEndianInt32(d+28);\n \/\/ for some reason we need to add 512 here. No clue why.\n fcMin += 512;\n fcMac += 512;\n uint16_t csw = readLittleEndianUInt16(d+32);\n size += 2*csw + 2;\n nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size) return false;\n csw = readLittleEndianUInt16(d+size-2);\n size += 4*csw + 2;\n nread = in->read(d, size, size);\n in->reset(0);\n if (nread != size) return false;\n csw = readLittleEndianUInt16(d+size-2);\n size += 8*csw;\n \n nread = in->read(d, fcMac, fcMac);\n in->reset(0);\n if (nread != fcMac) {\n return false;\n }\n const char *end = d+fcMac;\n d += fcMin;\n const char *p = d;\n string text;\n while (p < end) {\n switch (*p) {\n case 7: \/\/ cell\/row end\n case 11: \/\/ ?\n case 12: \/\/ Page break \/ Section mark\n case 13: \/\/ Paragraph end\n case 14: \/\/ Column end\n case 19: \/\/ Field start\n case 20: \/\/ ?\n if (p > d) {\n text.append(d, p-d);\n\t ar.addText(text.c_str(), text.size());\n\t }\n text.assign(\"\");\n d = p+1;\n\t break;\n case 21: \/\/ Field end\n text.assign(\"\");\n d = p+1;\n\t break;\n case 30: \/\/ Non-breaken hyphen\n if (p > d) text.append(d, p-d);\n text.append(\"-\");\n d = p+1;\n case 31: \/\/ Non-required hyphen\n if (p > d) text.append(d, p-d);\n d = p+1;\n\t break;\n case 160: \/\/ Non-breaking space\n if (p > d) text.append(d, p-d);\n text.append(\" \");\n d = p+1;\n default:;\n }\n\t++p;\n }\n return true;\n}\nbool\nOleEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {\n return OleInputStream::checkHeader(header, headersize);\n}\nbool\ntryThumbsdbEntry(const string& name, AnalysisResult& ar, InputStream* in) {\n static const char magic[] = {0x0c, 0, 0, 0, 0x01, 0, 0, 0};\n const char* d;\n uint32_t nread = in->read(d, 12, 12);\n if (nread != 12 || memcmp(magic, d, 8)) {\n in->reset(0);\n return false;\n }\n SubInputStream thumb(in, in->size()-12);\n ar.indexChild(name, 0, &thumb);\n return true;\n}\n\/**\n * Exctract images from a 'Pictures' field from a ppt file.\n * http:\/\/jakarta.apache.org\/poi\/apidocs\/org\/apache\/poi\/hslf\/model\/Picture.html\n **\/\nvoid\ntryPictures(AnalysisResult& ar, InputStream* in) {\n const char* d;\n int32_t nread = in->read(d, 25, 25);\n ostringstream s;\n int pos = 1;\n while (nread == 25) {\n uint32_t size = readLittleEndianInt32(d+4)-17;\n SubInputStream sub(in, size);\n s << \"Pictures\/\" << pos++;\n ar.indexChild(s.str(), 0, &sub);\n s.str(\"\");\n nread = in->read(d, 25, 25);\n }\n}\n\/\/ format description: http:\/\/jakarta.apache.org\/poi\/hpsf\/internals.html\nbool\nOleEndAnalyzer::tryPropertyStream(AnalysisResult& idx,\n InputStream* in) {\n static const char magic[] = {0xfe, 0xff, 0, 0};\n const char* d;\n uint32_t nread = in->read(d, 28, 28);\n in->reset(0);\n if (nread != 28 || memcmp(magic, d, 4)) {\n return false;\n }\n \/\/ read all the data\n nread = in->read(d, in->size(), in->size());\n if (nread != in->size()) {\n return false;\n }\n int32_t n = readLittleEndianUInt32(d+24);\n if (in->size() < 28+n*20) {\n return false;\n }\n for (int32_t i=0; i= in->size()) {\n return false;\n }\n handlePropertyStream(key, d+offset, d+in->size());\n }\n return true;\n}\nvoid\nOleEndAnalyzer::handleProperty(const RegisteredField* field, const char* data) {\n int32_t datatype = readLittleEndianInt32(data);\n \/\/ currently we only support null-terminated strings\n if (datatype == 30) {\n int32_t len = readLittleEndianInt32(data+4);\n if (len > 0) {\n result->addValue(field, data+8, len-1);\n }\n }\n}\nvoid\nOleEndAnalyzer::handlePropertyStream(const char* key, const char* data,\n const char* end) {\n \/\/ get the fieldtable\n string k(key, 16);\n const map* table = factory->getFieldMap(k);\n if (table == 0) {\n return;\n }\n\n int32_t len = readLittleEndianInt32(data);\n const char* p = data + 8;\n const char* n = data + readLittleEndianInt32(data+4)*4 + 8;\n if (len < 0 || (len > end-data) || n > end) {\n return;\n }\n map::const_iterator field;\n while (p < n) {\n int32_t id = readLittleEndianInt32(p);\n field = table->find(id);\n if (field != table->end()) {\n int32_t offset = readLittleEndianInt32(p+4);\n handleProperty(field->second, data+offset);\n }\n p += 8;\n }\n}\nchar\nOleEndAnalyzer::analyze(AnalysisResult& ar, InputStream* in) {\n if(!in)\n return -1;\n\n result = &ar;\n OleInputStream ole(in);\n InputStream *s = ole.nextEntry();\n if (ole.status()) {\n fprintf(stderr, \"error: %s\\n\", ole.error());\n\treturn -1;\n }\n while (s) {\n const string& name = ole.entryInfo().filename;\n if (name.size()) {\n\t if (tryFIB(ar, s)) {\n } else if (tryThumbsdbEntry(name, ar, s)) {\n } else if (name[0] == 5) {\n \/\/ todo: handle property stream\n tryPropertyStream(ar, s);\n } else if (name == \"Pictures\") {\n tryPictures(ar, s);\n } else {\n ar.indexChild(name, ole.entryInfo().mtime,\n s);\n }\n }\n s = ole.nextEntry();\n }\n if (ole.status() == Error) {\n m_error = ole.error();\n return -1;\n } else {\n m_error.resize(0);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2001, 2002 Rolf Magnus \n * Copyright (C) 2006 Jos van den Oever \n * Copyright (C) 2007 Vincent Ricard \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \n\n#include \"pngendanalyzer.h\"\n#include \"analysisresult.h\"\n#include \"textendanalyzer.h\"\n#include \"subinputstream.h\"\n#include \"fieldtypes.h\"\n#include \"gzipinputstream.h\"\n#include \"textutils.h\"\nusing namespace std;\nusing namespace Strigi;\n\nconst string PngEndAnalyzerFactory::widthFieldName(\"width\");\nconst string PngEndAnalyzerFactory::heightFieldName(\"height\");\nconst string PngEndAnalyzerFactory::colorDepthFieldName(\"colorDepth\");\nconst string PngEndAnalyzerFactory::colorModeFieldName(\"colorMode\");\nconst string PngEndAnalyzerFactory::compressionFieldName(\"compression\");\nconst string PngEndAnalyzerFactory::interlaceModeFieldName(\"interlaceMode\");\nconst string PngEndAnalyzerFactory::lastModificationTimeFieldName(\"lastModificationTime\");\nconst string PngEndAnalyzerFactory::titleFieldName(\"title\");\nconst string PngEndAnalyzerFactory::authorFieldName(\"author\");\nconst string PngEndAnalyzerFactory::descriptionFieldName(\"description\");\nconst string PngEndAnalyzerFactory::copyrightFieldName(\"copyright\");\nconst string PngEndAnalyzerFactory::creationTimeFieldName(\"creationTime\");\nconst string PngEndAnalyzerFactory::softwareFieldName(\"software\");\nconst string PngEndAnalyzerFactory::disclaimerFieldName(\"disclaimer\");\nconst string PngEndAnalyzerFactory::warningFieldName(\"warning\");\nconst string PngEndAnalyzerFactory::sourceFieldName(\"source\");\nconst string PngEndAnalyzerFactory::commentFieldName(\"comment\");\n\n\/\/ and for the colors\nstatic const char* colors[] = {\n \"Grayscale\",\n \"Unknown\",\n \"RGB\",\n \"Palette\",\n \"Grayscale\/Alpha\",\n \"Unknown\",\n \"RGB\/Alpha\"\n};\n\nstatic const char* interlaceModes[] = {\n \"None\",\n \"Adam7\"\n};\n\nvoid\nPngEndAnalyzerFactory::registerFields(FieldRegister& reg) {\n widthField = reg.registerField(widthFieldName,\n FieldRegister::integerType, 1, 0);\n heightField = reg.registerField(heightFieldName,\n FieldRegister::integerType, 1, 0);\n colorDepthField = reg.registerField(colorDepthFieldName,\n FieldRegister::integerType, 1, 0);\n colorModeField = reg.registerField(colorModeFieldName,\n FieldRegister::integerType, 1, 0);\n compressionField = reg.registerField(compressionFieldName,\n FieldRegister::integerType, 1, 0);\n interlaceModeField = reg.registerField(interlaceModeFieldName,\n FieldRegister::integerType, 1, 0);\n lastModificationTimeField = reg.registerField(lastModificationTimeFieldName,\n FieldRegister::integerType, 1, 0);\n titleField = reg.registerField(titleFieldName,\n FieldRegister::stringType, 1, 0);\n authorField = reg.registerField(authorFieldName,\n FieldRegister::stringType, 1, 0);\n descriptionField = reg.registerField(descriptionFieldName,\n FieldRegister::stringType, 1, 0);\n copyrightField = reg.registerField(copyrightFieldName,\n FieldRegister::stringType, 1, 0);\n creationTimeField = reg.registerField(creationTimeFieldName,\n FieldRegister::integerType, 1, 0);\n softwareField = reg.registerField(softwareFieldName,\n FieldRegister::stringType, 1, 0);\n disclaimerField = reg.registerField(disclaimerFieldName,\n FieldRegister::stringType, 1, 0);\n warningField = reg.registerField(warningFieldName,\n FieldRegister::stringType, 1, 0);\n sourceField = reg.registerField(sourceFieldName,\n FieldRegister::stringType, 1, 0);\n commentField = reg.registerField(commentFieldName,\n FieldRegister::stringType, 1, 0);\n}\n\nPngEndAnalyzer::PngEndAnalyzer(const PngEndAnalyzerFactory* f) :factory(f) {\n \/\/ XXX hack to workaround mktime\n \/\/ which takes care of the local time zone\n struct tm timeZone;\n timeZone.tm_sec = 0;\n timeZone.tm_min = 0;\n timeZone.tm_hour = 0;\n timeZone.tm_mday = 1;\n timeZone.tm_mon = 0;\n timeZone.tm_year = 70;\n timeZone.tm_isdst = 0;\n timeZoneOffset = mktime(&timeZone);\n}\nbool\nPngEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {\n static const unsigned char pngmagic[]\n = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};\n return headersize >= 29 && memcmp(header, pngmagic, 8) == 0;\n}\nchar\nPngEndAnalyzer::analyze(AnalysisResult& as, InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 12, 12);\n if (nread != 12) {\n \/\/ file is too small to be a png\n return -1;\n }\n\n \/\/ read chunksize and include the size of the type and crc (4 + 4)\n uint32_t chunksize = readBigEndianUInt32(c+8) + 8;\n if (chunksize > 1048576) {\n fprintf(stderr,\"chunk too big: %u\\n\",chunksize);\n return -1;\n }\n nread = in->read(c, chunksize, chunksize);\n \/\/ the IHDR chunk should be the first\n if (nread != (int32_t)chunksize || strncmp(c, \"IHDR\", 4)) {\n return -1;\n }\n\n \/\/ read the png dimensions\n uint32_t width = readBigEndianUInt32(c+4);\n uint32_t height = readBigEndianUInt32(c+8);\n as.addValue(factory->widthField, width);\n as.addValue(factory->heightField, height);\n\n uint16_t type = c[13];\n uint16_t bpp = c[12];\n\n \/\/ the bpp are only per channel, so we need to multiply the with\n \/\/ the channel count\n switch (type) {\n case 0: break; \/\/ Grayscale\n case 2: bpp *= 3; break; \/\/ RGB\n case 3: break; \/\/ palette\n case 4: bpp *= 2; break; \/\/ grayscale w. alpha\n case 6: bpp *= 4; break; \/\/ RGBA\n\n default: \/\/ we don't get any sensible value here\n bpp = 0;\n }\n\n as.addValue(factory->colorDepthField, (uint32_t)bpp);\n as.addValue(factory->colorModeField,\n (type < sizeof(colors)\/sizeof(colors[0]))\n ? colors[type] : \"Unknown\");\n\n as.addValue(factory->compressionField,\n (c[14] == 0) ? \"Deflate\" : \"Unknown\");\n\n as.addValue(factory->interlaceModeField,\n ((uint)c[16] < sizeof(interlaceModes)\/sizeof(interlaceModes[0]))\n ? interlaceModes[(int)c[16]] : \"Unknown\");\n\n \/\/ read the rest of the chunks\n \/\/ TODO: check if we want a fast or complete analysis\n \/\/ read the type\n nread = in->read(c, 8, 8);\n while (nread == 8 && strncmp(\"IEND\", c+4, 4)) {\n \/\/ get the size of the data block\n chunksize = readBigEndianUInt32(c);\n\n \/\/ TODO read http:\/\/tools.ietf.org\/html\/rfc2083 to handle\n \/\/ predefined text values and map them to good semantic fields\n\n if (strncmp(\"tEXt\", c+4, 4) == 0) {\n \/\/ TODO convert latin1 to utf8 and analyze the format properly\n SubInputStream sub(in, chunksize);\n analyzeText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"zTXt\", c+4, 4) == 0) {\n SubInputStream sub(in, chunksize);\n analyzeZText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"iTXt\", c+4, 4) == 0) {\n SubInputStream sub(in, chunksize);\n analyzeText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"tIME\", c+4, 4) == 0) {\n \/\/ the chunck size has to be 7\n if (chunksize != 7) {\n return -1;\n }\n nread = in->read(c, chunksize, chunksize);\n if (nread != (int32_t)chunksize) {\n return -1;\n }\n int32_t time = extractTime(c);\n if (time == -1) {\n return -1;\n }\n as.addValue(factory->lastModificationTimeField, (uint32_t)time);\n } else {\n nread = (int32_t)in->skip(chunksize);\n if (nread != (int32_t)chunksize) {\n fprintf(stderr, \"could not skip chunk size %u\\n\", chunksize);\n return -1;\n }\n }\n in->skip(4); \/\/ skip crc\n nread = in->read(c, 8, 8);\n }\n if (nread != 8) {\n \/\/ invalid file or error\n fprintf(stderr, \"bad end in %s\\n\", as.path().c_str());\n return -1;\n }\n\n return 0;\n}\nchar\nPngEndAnalyzer::analyzeText(Strigi::AnalysisResult& as,\n InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 80, 80);\n if (nread < 1) {\n return -1;\n }\n \/\/ find the \\0\n int32_t nlen = 0;\n while (nlen < nread && c[nlen]) nlen++;\n if (nlen == nread) return -1;\n const string name(c, nlen); \/\/ do something with the name!\n in->reset(nlen+1);\n addMetaData(name, as, in);\n TextEndAnalyzer tea;\n return tea.analyze(as, in);\n}\nchar\nPngEndAnalyzer::analyzeZText(Strigi::AnalysisResult& as,\n InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 81, 81);\n if (nread < 1) {\n return -1;\n }\n \/\/ find the \\0\n int32_t nlen = 0;\n while (nlen < nread && c[nlen]) nlen++;\n if (nlen == nread) return -1;\n const string name(c, nlen); \/\/ do something with the name!\n in->reset(nlen+2);\n GZipInputStream z(in, GZipInputStream::ZLIBFORMAT);\n addMetaData(name, as, &z);\n TextEndAnalyzer tea;\n return tea.analyze(as, &z);\n}\nint32_t\nPngEndAnalyzer::extractTime(const char* chunck) {\n int16_t year = readBigEndianInt16(chunck);\n int8_t month = *(chunck+2);\n int8_t day = *(chunck+3);\n int8_t hour = *(chunck+4);\n int8_t minute = *(chunck+5);\n int8_t second = *(chunck+6);\n \/\/ check the data (the leap second is allowed)\n if (!(1 <= month && month <= 12\n && 1 <= day && day <= 31\n && 0 <= hour && hour <= 23\n && 0 <= minute && minute <= 59\n && 0 <= second && second <= 60)) {\n return -1;\n }\n \/\/ we want to store the date\/time as a number of\n \/\/ seconds since Epoch (1970-01-01T00:00:00)\n struct tm dateTime;\n dateTime.tm_sec = second;\n dateTime.tm_min = minute;\n dateTime.tm_hour = hour;\n dateTime.tm_mday = day;\n dateTime.tm_mon = month-1;\n dateTime.tm_year = year-1900;\n dateTime.tm_isdst = 0;\n\n time_t sinceEpoch = mktime(&dateTime);\n if (sinceEpoch == (time_t)-1) {\n fprintf(stderr, \"could not compute the date\/time\\n\");\n return -1;\n }\n\n \/\/ FIXME the chunck is UTC but mktime use the local timezone :-(\n \/\/ so i have to add the offset of the local time zone\n \/\/ If someone has a better solution...\n return sinceEpoch + timeZoneOffset;\n}\nvoid\nPngEndAnalyzer::addMetaData(const string& key,\n Strigi::AnalysisResult& as, InputStream* in) {\n const char* b;\n \/\/ try to store the whole buffer\n int32_t nread = in->read(b, 0, -1);\n if (0 < nread) {\n const string value(b, nread);\n if (\"Title\" == key) {\n as.addValue(factory->titleField, value);\n } else if (\"Author\" == key) {\n as.addValue(factory->authorField, value);\n } else if (\"Description\" == key) {\n as.addValue(factory->descriptionField, value);\n } else if (\"Copyright\" == key) {\n as.addValue(factory->copyrightField, value);\n } else if (\"Creation Time\" == key) {\n \/\/ TODO we need to parse the date time\n \/\/ \"[...]the date format defined in section 5.2.14 of RFC 1123[...]\"\n } else if (\"Software\" == key) {\n as.addValue(factory->softwareField, value);\n } else if (\"Disclaimer\" == key) {\n as.addValue(factory->disclaimerField, value);\n } else if (\"Warning\" == key) {\n as.addValue(factory->warningField, value);\n } else if (\"Source\" == key) {\n as.addValue(factory->sourceField, value);\n } else if (\"Comment\" == key) {\n as.addValue(factory->commentField, value);\n }\n }\n}\nreset the InputStream to not break the full text index\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2001, 2002 Rolf Magnus \n * Copyright (C) 2006 Jos van den Oever \n * Copyright (C) 2007 Vincent Ricard \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \n\n#include \"pngendanalyzer.h\"\n#include \"analysisresult.h\"\n#include \"textendanalyzer.h\"\n#include \"subinputstream.h\"\n#include \"fieldtypes.h\"\n#include \"gzipinputstream.h\"\n#include \"textutils.h\"\nusing namespace std;\nusing namespace Strigi;\n\nconst string PngEndAnalyzerFactory::widthFieldName(\"width\");\nconst string PngEndAnalyzerFactory::heightFieldName(\"height\");\nconst string PngEndAnalyzerFactory::colorDepthFieldName(\"colorDepth\");\nconst string PngEndAnalyzerFactory::colorModeFieldName(\"colorMode\");\nconst string PngEndAnalyzerFactory::compressionFieldName(\"compression\");\nconst string PngEndAnalyzerFactory::interlaceModeFieldName(\"interlaceMode\");\nconst string PngEndAnalyzerFactory::lastModificationTimeFieldName(\"lastModificationTime\");\nconst string PngEndAnalyzerFactory::titleFieldName(\"title\");\nconst string PngEndAnalyzerFactory::authorFieldName(\"author\");\nconst string PngEndAnalyzerFactory::descriptionFieldName(\"description\");\nconst string PngEndAnalyzerFactory::copyrightFieldName(\"copyright\");\nconst string PngEndAnalyzerFactory::creationTimeFieldName(\"creationTime\");\nconst string PngEndAnalyzerFactory::softwareFieldName(\"software\");\nconst string PngEndAnalyzerFactory::disclaimerFieldName(\"disclaimer\");\nconst string PngEndAnalyzerFactory::warningFieldName(\"warning\");\nconst string PngEndAnalyzerFactory::sourceFieldName(\"source\");\nconst string PngEndAnalyzerFactory::commentFieldName(\"comment\");\n\n\/\/ and for the colors\nstatic const char* colors[] = {\n \"Grayscale\",\n \"Unknown\",\n \"RGB\",\n \"Palette\",\n \"Grayscale\/Alpha\",\n \"Unknown\",\n \"RGB\/Alpha\"\n};\n\nstatic const char* interlaceModes[] = {\n \"None\",\n \"Adam7\"\n};\n\nvoid\nPngEndAnalyzerFactory::registerFields(FieldRegister& reg) {\n widthField = reg.registerField(widthFieldName,\n FieldRegister::integerType, 1, 0);\n heightField = reg.registerField(heightFieldName,\n FieldRegister::integerType, 1, 0);\n colorDepthField = reg.registerField(colorDepthFieldName,\n FieldRegister::integerType, 1, 0);\n colorModeField = reg.registerField(colorModeFieldName,\n FieldRegister::integerType, 1, 0);\n compressionField = reg.registerField(compressionFieldName,\n FieldRegister::integerType, 1, 0);\n interlaceModeField = reg.registerField(interlaceModeFieldName,\n FieldRegister::integerType, 1, 0);\n lastModificationTimeField = reg.registerField(lastModificationTimeFieldName,\n FieldRegister::integerType, 1, 0);\n titleField = reg.registerField(titleFieldName,\n FieldRegister::stringType, 1, 0);\n authorField = reg.registerField(authorFieldName,\n FieldRegister::stringType, 1, 0);\n descriptionField = reg.registerField(descriptionFieldName,\n FieldRegister::stringType, 1, 0);\n copyrightField = reg.registerField(copyrightFieldName,\n FieldRegister::stringType, 1, 0);\n creationTimeField = reg.registerField(creationTimeFieldName,\n FieldRegister::integerType, 1, 0);\n softwareField = reg.registerField(softwareFieldName,\n FieldRegister::stringType, 1, 0);\n disclaimerField = reg.registerField(disclaimerFieldName,\n FieldRegister::stringType, 1, 0);\n warningField = reg.registerField(warningFieldName,\n FieldRegister::stringType, 1, 0);\n sourceField = reg.registerField(sourceFieldName,\n FieldRegister::stringType, 1, 0);\n commentField = reg.registerField(commentFieldName,\n FieldRegister::stringType, 1, 0);\n}\n\nPngEndAnalyzer::PngEndAnalyzer(const PngEndAnalyzerFactory* f) :factory(f) {\n \/\/ XXX hack to workaround mktime\n \/\/ which takes care of the local time zone\n struct tm timeZone;\n timeZone.tm_sec = 0;\n timeZone.tm_min = 0;\n timeZone.tm_hour = 0;\n timeZone.tm_mday = 1;\n timeZone.tm_mon = 0;\n timeZone.tm_year = 70;\n timeZone.tm_isdst = 0;\n timeZoneOffset = mktime(&timeZone);\n}\nbool\nPngEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {\n static const unsigned char pngmagic[]\n = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};\n return headersize >= 29 && memcmp(header, pngmagic, 8) == 0;\n}\nchar\nPngEndAnalyzer::analyze(AnalysisResult& as, InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 12, 12);\n if (nread != 12) {\n \/\/ file is too small to be a png\n return -1;\n }\n\n \/\/ read chunksize and include the size of the type and crc (4 + 4)\n uint32_t chunksize = readBigEndianUInt32(c+8) + 8;\n if (chunksize > 1048576) {\n fprintf(stderr,\"chunk too big: %u\\n\",chunksize);\n return -1;\n }\n nread = in->read(c, chunksize, chunksize);\n \/\/ the IHDR chunk should be the first\n if (nread != (int32_t)chunksize || strncmp(c, \"IHDR\", 4)) {\n return -1;\n }\n\n \/\/ read the png dimensions\n uint32_t width = readBigEndianUInt32(c+4);\n uint32_t height = readBigEndianUInt32(c+8);\n as.addValue(factory->widthField, width);\n as.addValue(factory->heightField, height);\n\n uint16_t type = c[13];\n uint16_t bpp = c[12];\n\n \/\/ the bpp are only per channel, so we need to multiply the with\n \/\/ the channel count\n switch (type) {\n case 0: break; \/\/ Grayscale\n case 2: bpp *= 3; break; \/\/ RGB\n case 3: break; \/\/ palette\n case 4: bpp *= 2; break; \/\/ grayscale w. alpha\n case 6: bpp *= 4; break; \/\/ RGBA\n\n default: \/\/ we don't get any sensible value here\n bpp = 0;\n }\n\n as.addValue(factory->colorDepthField, (uint32_t)bpp);\n as.addValue(factory->colorModeField,\n (type < sizeof(colors)\/sizeof(colors[0]))\n ? colors[type] : \"Unknown\");\n\n as.addValue(factory->compressionField,\n (c[14] == 0) ? \"Deflate\" : \"Unknown\");\n\n as.addValue(factory->interlaceModeField,\n ((uint)c[16] < sizeof(interlaceModes)\/sizeof(interlaceModes[0]))\n ? interlaceModes[(int)c[16]] : \"Unknown\");\n\n \/\/ read the rest of the chunks\n \/\/ TODO: check if we want a fast or complete analysis\n \/\/ read the type\n nread = in->read(c, 8, 8);\n while (nread == 8 && strncmp(\"IEND\", c+4, 4)) {\n \/\/ get the size of the data block\n chunksize = readBigEndianUInt32(c);\n\n \/\/ TODO read http:\/\/tools.ietf.org\/html\/rfc2083 to handle\n \/\/ predefined text values and map them to good semantic fields\n\n if (strncmp(\"tEXt\", c+4, 4) == 0) {\n \/\/ TODO convert latin1 to utf8 and analyze the format properly\n SubInputStream sub(in, chunksize);\n analyzeText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"zTXt\", c+4, 4) == 0) {\n SubInputStream sub(in, chunksize);\n analyzeZText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"iTXt\", c+4, 4) == 0) {\n SubInputStream sub(in, chunksize);\n analyzeText(as, &sub);\n sub.skip(chunksize);\n } else if (strncmp(\"tIME\", c+4, 4) == 0) {\n \/\/ the chunck size has to be 7\n if (chunksize != 7) {\n return -1;\n }\n nread = in->read(c, chunksize, chunksize);\n if (nread != (int32_t)chunksize) {\n return -1;\n }\n int32_t time = extractTime(c);\n if (time == -1) {\n return -1;\n }\n as.addValue(factory->lastModificationTimeField, (uint32_t)time);\n } else {\n nread = (int32_t)in->skip(chunksize);\n if (nread != (int32_t)chunksize) {\n fprintf(stderr, \"could not skip chunk size %u\\n\", chunksize);\n return -1;\n }\n }\n in->skip(4); \/\/ skip crc\n nread = in->read(c, 8, 8);\n }\n if (nread != 8) {\n \/\/ invalid file or error\n fprintf(stderr, \"bad end in %s\\n\", as.path().c_str());\n return -1;\n }\n\n return 0;\n}\nchar\nPngEndAnalyzer::analyzeText(Strigi::AnalysisResult& as,\n InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 80, 80);\n if (nread < 1) {\n return -1;\n }\n \/\/ find the \\0\n int32_t nlen = 0;\n while (nlen < nread && c[nlen]) nlen++;\n if (nlen == nread) return -1;\n const string name(c, nlen); \/\/ do something with the name!\n in->reset(nlen+1);\n addMetaData(name, as, in);\n TextEndAnalyzer tea;\n return tea.analyze(as, in);\n}\nchar\nPngEndAnalyzer::analyzeZText(Strigi::AnalysisResult& as,\n InputStream* in) {\n const char* c;\n int32_t nread = in->read(c, 81, 81);\n if (nread < 1) {\n return -1;\n }\n \/\/ find the \\0\n int32_t nlen = 0;\n while (nlen < nread && c[nlen]) nlen++;\n if (nlen == nread) return -1;\n const string name(c, nlen); \/\/ do something with the name!\n in->reset(nlen+2);\n GZipInputStream z(in, GZipInputStream::ZLIBFORMAT);\n addMetaData(name, as, &z);\n TextEndAnalyzer tea;\n return tea.analyze(as, &z);\n}\nint32_t\nPngEndAnalyzer::extractTime(const char* chunck) {\n int16_t year = readBigEndianInt16(chunck);\n int8_t month = *(chunck+2);\n int8_t day = *(chunck+3);\n int8_t hour = *(chunck+4);\n int8_t minute = *(chunck+5);\n int8_t second = *(chunck+6);\n \/\/ check the data (the leap second is allowed)\n if (!(1 <= month && month <= 12\n && 1 <= day && day <= 31\n && 0 <= hour && hour <= 23\n && 0 <= minute && minute <= 59\n && 0 <= second && second <= 60)) {\n return -1;\n }\n \/\/ we want to store the date\/time as a number of\n \/\/ seconds since Epoch (1970-01-01T00:00:00)\n struct tm dateTime;\n dateTime.tm_sec = second;\n dateTime.tm_min = minute;\n dateTime.tm_hour = hour;\n dateTime.tm_mday = day;\n dateTime.tm_mon = month-1;\n dateTime.tm_year = year-1900;\n dateTime.tm_isdst = 0;\n\n time_t sinceEpoch = mktime(&dateTime);\n if (sinceEpoch == (time_t)-1) {\n fprintf(stderr, \"could not compute the date\/time\\n\");\n return -1;\n }\n\n \/\/ FIXME the chunck is UTC but mktime use the local timezone :-(\n \/\/ so i have to add the offset of the local time zone\n \/\/ If someone has a better solution...\n return sinceEpoch + timeZoneOffset;\n}\nvoid\nPngEndAnalyzer::addMetaData(const string& key,\n Strigi::AnalysisResult& as, InputStream* in) {\n const char* b;\n int64_t pos = in->position();\n \/\/ try to store the whole buffer\n int32_t nread = in->read(b, 0, -1);\n if (0 < nread) {\n const string value(b, nread);\n if (\"Title\" == key) {\n as.addValue(factory->titleField, value);\n } else if (\"Author\" == key) {\n as.addValue(factory->authorField, value);\n } else if (\"Description\" == key) {\n as.addValue(factory->descriptionField, value);\n } else if (\"Copyright\" == key) {\n as.addValue(factory->copyrightField, value);\n } else if (\"Creation Time\" == key) {\n \/\/ TODO we need to parse the date time\n \/\/ \"[...]the date format defined in section 5.2.14 of RFC 1123[...]\"\n } else if (\"Software\" == key) {\n as.addValue(factory->softwareField, value);\n } else if (\"Disclaimer\" == key) {\n as.addValue(factory->disclaimerField, value);\n } else if (\"Warning\" == key) {\n as.addValue(factory->warningField, value);\n } else if (\"Source\" == key) {\n as.addValue(factory->sourceField, value);\n } else if (\"Comment\" == key) {\n as.addValue(factory->commentField, value);\n }\n in->reset(pos);\n }\n}\n<|endoftext|>"} {"text":"\/*\n Persons Model Contact Item\n Represents person's contact item in the model\n Copyright (C) 2012 Martin Klapetek \n Copyright (C) 2012 Aleix Pol Gonzalez \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"contact-item.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nclass ContactItemPrivate {\npublic:\n QUrl uri;\n QHash data;\n\n \/\/\/@returns a list of the roles that we'll expect to be a QVariantList\n static QSet listRoles() {\n static QSet s_listRoles;\n if(s_listRoles.isEmpty()) {\n \/\/TODO: document this in persons-model.h\n s_listRoles.insert(PersonsModel::PhotoRole);\n s_listRoles.insert(PersonsModel::EmailRole);\n s_listRoles.insert(PersonsModel::PhoneRole);\n }\n return s_listRoles;\n }\n};\n\nContactItem::ContactItem(const QUrl &uri)\n : d_ptr(new ContactItemPrivate)\n{\n\/\/ setData(uri, PersonsModel::UriRole);\n d_ptr->uri = uri;\n}\n\nContactItem::~ContactItem()\n{\n delete d_ptr;\n}\n\nvoid ContactItem::setContactData(int role, const QVariant &v)\n{\n Q_D(ContactItem);\n QHash< int, QVariant >::iterator it = d->data.find(role);\n QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v;\n if (it == d->data.end()) {\n d->data.insert(role, value);\n emitDataChanged();\n } else if (*it != value) {\n Q_ASSERT(value.type() == it->type());\n *it = value;\n emitDataChanged();\n }\n}\n\nvoid ContactItem::addContactData(int role, const QVariant &value)\n{\n Q_D(ContactItem);\n QHash::iterator it = d->data.find(role);\n if (!d->listRoles().contains(role)) {\n setContactData(role, value);\n } else {\n if (it == d->data.end()) {\n d->data.insert(role, QVariantList() << value);\n emitDataChanged();\n } else if (*it != value) {\n Q_ASSERT(it->type() == QVariant::List);\n QVariantList current = it->toList();\n Q_ASSERT(current.isEmpty() || current.first().type()==value.type());\n current.append(value);\n *it = current;\n emitDataChanged();\n }\n }\n}\n\nvoid ContactItem::removeData(int role)\n{\n Q_D(ContactItem);\n if (d->data.remove(role)) {\n emitDataChanged();\n }\n}\n\n\nQUrl ContactItem::uri() const\n{\n Q_D(const ContactItem);\n return d->uri;\n}\n\nQVariant ContactItem::data(int role) const\n{\n Q_D(const ContactItem);\n\n QHash::const_iterator it = d->data.constFind(role);\n if (it!=d->data.constEnd()) {\n return *it;\n }\n\n switch(role) {\n case Qt::DisplayRole:\n if (!data(PersonsModel::NickRole).toString().isEmpty()) {\n return data(PersonsModel::NickRole);\n }\n if (!data(PersonsModel::LabelRole).toString().isEmpty()) {\n return data(PersonsModel::LabelRole);\n }\n if (!data(PersonsModel::IMRole).toString().isEmpty()) {\n return data(PersonsModel::IMRole);\n }\n if (!data(PersonsModel::EmailRole).toString().isEmpty()) {\n return data(PersonsModel::EmailRole);\n }\n if (!data(PersonsModel::PhoneRole).toString().isEmpty()) {\n return data(PersonsModel::PhoneRole);\n }\n\n return QString(\"Unknown person\"); \/\/FIXME: temporary\n case PersonsModel::UriRole: return d->uri; break;\n case PersonsModel::StatusRole: return QLatin1String(\"unknown\"); \/\/return unknown presence, for real presence use PersonsPresenceModel\n case PersonsModel::ContactsCountRole: return 1;\n case PersonsModel::ResourceTypeRole:\n return PersonsModel::Contact;\n case Qt::DecorationRole: {\n QVariantList photos = d->data.value(PersonsModel::PhotoRole).toList();\n return photos.isEmpty() ? KIcon(\"im-user\") : KIcon(photos.first().toUrl().toLocalFile());\n }\n }\n return QStandardItem::data(role);\n}\n\nvoid ContactItem::loadData()\n{\n Q_D(ContactItem);\n\n QHash bindingRoleMap;\n bindingRoleMap.insert(\"nco_imNickname\", PersonsModel::NickRole);\n bindingRoleMap.insert(\"nao_prefLabel\", PersonsModel::LabelRole);\n bindingRoleMap.insert(\"nco_imID\", PersonsModel::IMRole);\n bindingRoleMap.insert(\"nco_imImAcountType\", PersonsModel::IMAccountTypeRole);\n bindingRoleMap.insert(\"nco_hasIMAccount\", PersonsModel::IMAccountUriRole);\n bindingRoleMap.insert(\"nco_contactGroupName\", PersonsModel::ContactGroupsRole);\n bindingRoleMap.insert(\"nie_url\", PersonsModel::PhotoRole);\n bindingRoleMap.insert(\"nco_emailAddress\", PersonsModel::EmailRole);\n\n QString query = QString::fromUtf8(\n \"select DISTINCT ?nco_hasIMAccount \"\n \"?nco_imNickname ?nco_imID ?nco_imAccountType ?nco_hasEmailAddress \"\n \"?nie_url ?nao_prefLabel ?nco_contactGroupName \"\n\n \"WHERE { \"\n \"OPTIONAL { %1 nao:prefLabel ?nao_prefLabel. }\"\n\n\/\/ \"OPTIONAL { \"\n \"%1 nco:hasIMAccount ?nco_hasIMAccount. \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imNickname ?nco_imNickname. } \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imID ?nco_imID. } \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imAccountType ?nco_imAccountType. } \"\n\/\/ \" } \"\n \"OPTIONAL { \"\n \"%1 nco:belongsToGroup ?nco_belongsToGroup . \"\n \"?nco_belongsToGroup nco:contactGroupName ?nco_contactGroupName . \"\n \" }\"\n \"OPTIONAL {\"\n \"%1 nco:photo ?phRes. \"\n \"?phRes nie:url ?nie_url. \"\n \" } \"\n \"OPTIONAL { \"\n \"%1 nco:hasEmailAddress ?nco_hasEmailAddress. \"\n \"?nco_hasEmailAddress nco:emailAddress ?nco_emailAddress. \"\n \" } \"\n \"}\")\n .arg(Soprano::Node::resourceToN3(d->uri));\n\n Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel();\n Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );\n \/\/ FIXME: The result might come multiple times\n d->data.clear();\n if( it.next() ) {\n\n \/\/iterate over the results and add the wanted properties into the contact\n foreach (const QString& bName, it.bindingNames()) {\n if (!bindingRoleMap.contains(bName))\n continue;\n\n PersonsModel::Role role = bindingRoleMap.value(bName);\n QString value = it.binding(bName).toString();\n if (!value.isEmpty()) {\n addContactData(role, value);\n }\n }\n emitDataChanged();\n }\n}\nAdd missing NameRole querying into Qt::DisplayRole data\/*\n Persons Model Contact Item\n Represents person's contact item in the model\n Copyright (C) 2012 Martin Klapetek \n Copyright (C) 2012 Aleix Pol Gonzalez \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"contact-item.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nclass ContactItemPrivate {\npublic:\n QUrl uri;\n QHash data;\n\n \/\/\/@returns a list of the roles that we'll expect to be a QVariantList\n static QSet listRoles() {\n static QSet s_listRoles;\n if(s_listRoles.isEmpty()) {\n \/\/TODO: document this in persons-model.h\n s_listRoles.insert(PersonsModel::PhotoRole);\n s_listRoles.insert(PersonsModel::EmailRole);\n s_listRoles.insert(PersonsModel::PhoneRole);\n }\n return s_listRoles;\n }\n};\n\nContactItem::ContactItem(const QUrl &uri)\n : d_ptr(new ContactItemPrivate)\n{\n\/\/ setData(uri, PersonsModel::UriRole);\n d_ptr->uri = uri;\n}\n\nContactItem::~ContactItem()\n{\n delete d_ptr;\n}\n\nvoid ContactItem::setContactData(int role, const QVariant &v)\n{\n Q_D(ContactItem);\n QHash< int, QVariant >::iterator it = d->data.find(role);\n QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v;\n if (it == d->data.end()) {\n d->data.insert(role, value);\n emitDataChanged();\n } else if (*it != value) {\n Q_ASSERT(value.type() == it->type());\n *it = value;\n emitDataChanged();\n }\n}\n\nvoid ContactItem::addContactData(int role, const QVariant &value)\n{\n Q_D(ContactItem);\n QHash::iterator it = d->data.find(role);\n if (!d->listRoles().contains(role)) {\n setContactData(role, value);\n } else {\n if (it == d->data.end()) {\n d->data.insert(role, QVariantList() << value);\n emitDataChanged();\n } else if (*it != value) {\n Q_ASSERT(it->type() == QVariant::List);\n QVariantList current = it->toList();\n Q_ASSERT(current.isEmpty() || current.first().type()==value.type());\n current.append(value);\n *it = current;\n emitDataChanged();\n }\n }\n}\n\nvoid ContactItem::removeData(int role)\n{\n Q_D(ContactItem);\n if (d->data.remove(role)) {\n emitDataChanged();\n }\n}\n\n\nQUrl ContactItem::uri() const\n{\n Q_D(const ContactItem);\n return d->uri;\n}\n\nQVariant ContactItem::data(int role) const\n{\n Q_D(const ContactItem);\n\n QHash::const_iterator it = d->data.constFind(role);\n if (it!=d->data.constEnd()) {\n return *it;\n }\n\n switch(role) {\n case Qt::DisplayRole:\n if (!data(PersonsModel::NickRole).toString().isEmpty()) {\n return data(PersonsModel::NickRole);\n }\n if (!data(PersonsModel::LabelRole).toString().isEmpty()) {\n return data(PersonsModel::LabelRole);\n }\n if (!data(PersonsModel::NameRole).toString().isEmpty()) {\n return data(PersonsModel::NameRole);\n }\n if (!data(PersonsModel::IMRole).toString().isEmpty()) {\n return data(PersonsModel::IMRole);\n }\n if (!data(PersonsModel::EmailRole).toString().isEmpty()) {\n return data(PersonsModel::EmailRole);\n }\n if (!data(PersonsModel::PhoneRole).toString().isEmpty()) {\n return data(PersonsModel::PhoneRole);\n }\n\n return QString(\"Unknown person\"); \/\/FIXME: temporary\n case PersonsModel::UriRole: return d->uri; break;\n case PersonsModel::StatusRole: return QLatin1String(\"unknown\"); \/\/return unknown presence, for real presence use PersonsPresenceModel\n case PersonsModel::ContactsCountRole: return 1;\n case PersonsModel::ResourceTypeRole:\n return PersonsModel::Contact;\n case Qt::DecorationRole: {\n QVariantList photos = d->data.value(PersonsModel::PhotoRole).toList();\n return photos.isEmpty() ? KIcon(\"im-user\") : KIcon(photos.first().toUrl().toLocalFile());\n }\n }\n return QStandardItem::data(role);\n}\n\nvoid ContactItem::loadData()\n{\n Q_D(ContactItem);\n\n QHash bindingRoleMap;\n bindingRoleMap.insert(\"nco_imNickname\", PersonsModel::NickRole);\n bindingRoleMap.insert(\"nao_prefLabel\", PersonsModel::LabelRole);\n bindingRoleMap.insert(\"nco_imID\", PersonsModel::IMRole);\n bindingRoleMap.insert(\"nco_imImAcountType\", PersonsModel::IMAccountTypeRole);\n bindingRoleMap.insert(\"nco_hasIMAccount\", PersonsModel::IMAccountUriRole);\n bindingRoleMap.insert(\"nco_contactGroupName\", PersonsModel::ContactGroupsRole);\n bindingRoleMap.insert(\"nie_url\", PersonsModel::PhotoRole);\n bindingRoleMap.insert(\"nco_emailAddress\", PersonsModel::EmailRole);\n\n QString query = QString::fromUtf8(\n \"select DISTINCT ?nco_hasIMAccount \"\n \"?nco_imNickname ?nco_imID ?nco_imAccountType ?nco_hasEmailAddress \"\n \"?nie_url ?nao_prefLabel ?nco_contactGroupName \"\n\n \"WHERE { \"\n \"OPTIONAL { %1 nao:prefLabel ?nao_prefLabel. }\"\n\n\/\/ \"OPTIONAL { \"\n \"%1 nco:hasIMAccount ?nco_hasIMAccount. \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imNickname ?nco_imNickname. } \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imID ?nco_imID. } \"\n \"OPTIONAL { ?nco_hasIMAccount nco:imAccountType ?nco_imAccountType. } \"\n\/\/ \" } \"\n \"OPTIONAL { \"\n \"%1 nco:belongsToGroup ?nco_belongsToGroup . \"\n \"?nco_belongsToGroup nco:contactGroupName ?nco_contactGroupName . \"\n \" }\"\n \"OPTIONAL {\"\n \"%1 nco:photo ?phRes. \"\n \"?phRes nie:url ?nie_url. \"\n \" } \"\n \"OPTIONAL { \"\n \"%1 nco:hasEmailAddress ?nco_hasEmailAddress. \"\n \"?nco_hasEmailAddress nco:emailAddress ?nco_emailAddress. \"\n \" } \"\n \"}\")\n .arg(Soprano::Node::resourceToN3(d->uri));\n\n Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel();\n Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );\n \/\/ FIXME: The result might come multiple times\n d->data.clear();\n if( it.next() ) {\n\n \/\/iterate over the results and add the wanted properties into the contact\n foreach (const QString& bName, it.bindingNames()) {\n if (!bindingRoleMap.contains(bName))\n continue;\n\n PersonsModel::Role role = bindingRoleMap.value(bName);\n QString value = it.binding(bName).toString();\n if (!value.isEmpty()) {\n addContactData(role, value);\n }\n }\n emitDataChanged();\n }\n}\n<|endoftext|>"} {"text":"\/*################################################################################\n ##\n ## Copyright (C) 2016-2022 Keith O'Hara\n ##\n ## This file is part of the OptimLib C++ library.\n ##\n ## Licensed under the Apache License, Version 2.0 (the \"License\");\n ## you may not use this file except in compliance with the License.\n ## You may obtain a copy of the License at\n ##\n ## http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n ##\n ## Unless required by applicable law or agreed to in writing, software\n ## distributed under the License is distributed on an \"AS IS\" BASIS,\n ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ## See the License for the specific language governing permissions and\n ## limitations under the License.\n ##\n ################################################################################*\/\n\n\/*\n * Particle Swarm Optimization (PSO)\n *\/\n\n#include \"optim.hpp\"\n\n\/\/ [OPTIM_BEGIN]\noptimlib_inline\nbool\noptim::internal::pso_impl(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data, \n algo_settings_t* settings_inp\n)\n{\n bool success = false;\n\n const size_t n_vals = BMO_MATOPS_SIZE(init_out_vals);\n\n \/\/\n \/\/ PSO settings\n\n algo_settings_t settings;\n\n if (settings_inp) {\n settings = *settings_inp;\n }\n\n const int print_level = settings.print_level;\n\n const uint_t conv_failure_switch = settings.conv_failure_switch;\n const fp_t rel_objfn_change_tol = settings.rel_objfn_change_tol;\n\n const bool center_particle = settings.pso_settings.center_particle;\n\n const size_t n_pop = (center_particle) ? settings.pso_settings.n_pop + 1 : settings.pso_settings.n_pop;\n const size_t n_gen = settings.pso_settings.n_gen;\n const size_t check_freq = settings.pso_settings.check_freq;\n\n const uint_t inertia_method = settings.pso_settings.inertia_method;\n\n fp_t par_w = settings.pso_settings.par_initial_w;\n const fp_t par_w_max = settings.pso_settings.par_w_max;\n const fp_t par_w_min = settings.pso_settings.par_w_min;\n const fp_t par_damp = settings.pso_settings.par_w_damp;\n\n const uint_t velocity_method = settings.pso_settings.velocity_method;\n\n fp_t par_c_cog = settings.pso_settings.par_c_cog;\n fp_t par_c_soc = settings.pso_settings.par_c_soc;\n\n const fp_t par_initial_c_cog = settings.pso_settings.par_initial_c_cog;\n const fp_t par_final_c_cog = settings.pso_settings.par_final_c_cog;\n const fp_t par_initial_c_soc = settings.pso_settings.par_initial_c_soc;\n const fp_t par_final_c_soc = settings.pso_settings.par_final_c_soc;\n\n const bool return_position_mat = settings.pso_settings.return_position_mat;\n\n const bool vals_bound = settings.vals_bound;\n \n const ColVec_t lower_bounds = settings.lower_bounds;\n const ColVec_t upper_bounds = settings.upper_bounds;\n\n const ColVecInt_t bounds_type = determine_bounds_type(vals_bound, n_vals, lower_bounds, upper_bounds);\n\n ColVec_t par_initial_lb = ( BMO_MATOPS_SIZE(settings.pso_settings.initial_lb) == n_vals ) ? settings.pso_settings.initial_lb : BMO_MATOPS_ARRAY_ADD_SCALAR(init_out_vals, -0.5);\n ColVec_t par_initial_ub = ( BMO_MATOPS_SIZE(settings.pso_settings.initial_ub) == n_vals ) ? settings.pso_settings.initial_ub : BMO_MATOPS_ARRAY_ADD_SCALAR(init_out_vals, 0.5);\n\n sampling_bounds_check(vals_bound, n_vals, bounds_type, lower_bounds, upper_bounds, par_initial_lb, par_initial_ub);\n\n \/\/ parallelization setup\n\n int omp_n_threads = 1;\n\n#ifdef OPTIM_USE_OPENMP\n if (settings.pso_settings.omp_n_threads > 0) {\n omp_n_threads = settings.pso_settings.omp_n_threads;\n } else {\n omp_n_threads = std::max(1, static_cast(omp_get_max_threads()) \/ 2); \/\/ OpenMP often detects the number of virtual\/logical cores, not physical cores\n }\n#endif\n\n \/\/ random sampling setup\n\n rand_engine_t rand_engine(settings.rng_seed_value);\n std::vector rand_engines_vec;\n\n for (int i = 0; i < omp_n_threads; ++i) {\n size_t seed_val = generate_seed_value(i, omp_n_threads, rand_engine);\n rand_engines_vec.push_back(rand_engine_t(seed_val));\n }\n\n \/\/ lambda function for box constraints\n\n std::function box_objfn \\\n = [opt_objfn, vals_bound, bounds_type, lower_bounds, upper_bounds] (const ColVec_t& vals_inp, ColVec_t* grad_out, void* opt_data) \\\n -> fp_t \n {\n if (vals_bound) {\n ColVec_t vals_inv_trans = inv_transform(vals_inp, bounds_type, lower_bounds, upper_bounds);\n \n return opt_objfn(vals_inv_trans,nullptr,opt_data);\n } else {\n return opt_objfn(vals_inp,nullptr,opt_data);\n }\n };\n\n \/\/\n \/\/ initialize\n\n ColVec_t rand_vec(n_vals);\n ColVec_t objfn_vals(n_pop);\n Mat_t P(n_pop,n_vals);\n\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads) firstprivate(rand_vec)\n#endif\n for (size_t i = 0; i < n_pop; ++i) {\n size_t thread_num = 0;\n\n#ifdef OPTIM_USE_OPENMP\n thread_num = omp_get_thread_num();\n#endif\n\n if (center_particle && i == n_pop - 1) {\n P.row(i) = BMO_MATOPS_COLWISE_SUM( BMO_MATOPS_MIDDLE_ROWS(P, 0, n_pop-2) ) \/ static_cast(n_pop-1); \/\/ center vector\n } else {\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec);\n\n P.row(i) = BMO_MATOPS_TRANSPOSE( par_initial_lb + BMO_MATOPS_HADAMARD_PROD( (par_initial_ub - par_initial_lb), rand_vec ) );\n }\n\n fp_t prop_objfn_val = opt_objfn(BMO_MATOPS_TRANSPOSE(P.row(i)), nullptr, opt_data);\n\n if (!std::isfinite(prop_objfn_val)) {\n prop_objfn_val = inf;\n }\n \n objfn_vals(i) = prop_objfn_val;\n\n if (vals_bound) {\n P.row(i) = transform(P.row(i), bounds_type, lower_bounds, upper_bounds);\n }\n }\n\n ColVec_t best_vals = objfn_vals;\n Mat_t best_vecs = P;\n\n fp_t min_objfn_val_running = BMO_MATOPS_MIN_VAL(objfn_vals);\n fp_t min_objfn_val_check = min_objfn_val_running;\n \n RowVec_t best_sol_running = P.row( bmo::index_min(objfn_vals) );\n\n \/\/\n \/\/ begin loop\n\n size_t iter = 0;\n fp_t rel_objfn_change = 2.0*rel_objfn_change_tol;\n\n RowVec_t rand_vec_1(n_vals);\n RowVec_t rand_vec_2(n_vals);\n Mat_t V = BMO_MATOPS_ZERO_MAT(n_pop,n_vals);\n\n while (rel_objfn_change > rel_objfn_change_tol && iter < n_gen) {\n ++iter;\n \n \/\/\n \/\/ parameter updating\n\n if (inertia_method == 1) {\n par_w = par_w_min + (par_w_max - par_w_min) * (iter + 1) \/ n_gen;\n } else {\n par_w *= par_damp;\n }\n\n if (velocity_method == 2) {\n par_c_cog = par_initial_c_cog - (par_initial_c_cog - par_final_c_cog) * (iter + 1) \/ n_gen;\n par_c_soc = par_initial_c_soc - (par_initial_c_soc - par_final_c_soc) * (iter + 1) \/ n_gen;\n }\n\n \/\/\n \/\/ population loop\n\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads) firstprivate(rand_vec_1,rand_vec_2)\n#endif\n for (size_t i=0; i < n_pop; ++i) {\n size_t thread_num = 0;\n\n#ifdef OPTIM_USE_OPENMP\n thread_num = omp_get_thread_num();\n#endif\n\n if ( !(center_particle && i == n_pop - 1) ) {\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec_1);\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec_2);\n\n \/\/ RowVec_t rand_vec_1 = bmo::stats::runif_vec(n_vals, rand_engines_vec[thread_num]);\n \/\/ RowVec_t rand_vec_2 = bmo::stats::runif_vec(n_vals, rand_engines_vec[thread_num]);\n\n V.row(i) = par_w * V.row(i) + par_c_cog * BMO_MATOPS_HADAMARD_PROD( rand_vec_1, (best_vecs.row(i) - P.row(i)) ) \\\n + par_c_soc * BMO_MATOPS_HADAMARD_PROD( rand_vec_2, (best_sol_running - P.row(i)) );\n\n P.row(i) += V.row(i);\n } else {\n P.row(i) = BMO_MATOPS_COLWISE_SUM( BMO_MATOPS_MIDDLE_ROWS(P, 0, n_pop - 2) ) \/ static_cast(n_pop - 1); \/\/ center vector\n }\n \n \/\/\n\n fp_t prop_objfn_val = box_objfn( BMO_MATOPS_TRANSPOSE(P.row(i)), nullptr, opt_data);\n\n if (!std::isfinite(prop_objfn_val)) {\n prop_objfn_val = inf;\n }\n \n objfn_vals(i) = prop_objfn_val;\n \n if (objfn_vals(i) < best_vals(i)) {\n best_vals(i) = objfn_vals(i);\n best_vecs.row(i) = P.row(i);\n }\n }\n\n size_t min_objfn_val_index = bmo::index_min(best_vals);\n fp_t min_objfn_val = best_vals(min_objfn_val_index);\n\n \/\/\n\n if (min_objfn_val < min_objfn_val_running) {\n min_objfn_val_running = min_objfn_val;\n best_sol_running = best_vecs.row( min_objfn_val_index );\n }\n\n if (iter % check_freq == 0) {\n rel_objfn_change = std::abs(min_objfn_val_running - min_objfn_val_check) \/ (OPTIM_FPN_SMALL_NUMBER + std::abs(min_objfn_val_running));\n \n if (min_objfn_val_running < min_objfn_val_check) {\n min_objfn_val_check = min_objfn_val_running;\n }\n }\n\n \/\/\n\n OPTIM_PSO_TRACE(iter, rel_objfn_change, min_objfn_val_running, min_objfn_val_check, best_sol_running, P);\n }\n\n \/\/\n\n if (return_position_mat) {\n if (vals_bound) {\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads)\n#endif\n for (size_t i = 0; i < n_pop; ++i) {\n P.row(i) = inv_transform(P.row(i), bounds_type, lower_bounds, upper_bounds);\n }\n }\n\n settings_inp->pso_settings.position_mat = P;\n }\n\n \/\/\n\n if (vals_bound) {\n best_sol_running = inv_transform( best_sol_running, bounds_type, lower_bounds, upper_bounds);\n }\n\n error_reporting(init_out_vals, BMO_MATOPS_TRANSPOSE(best_sol_running), opt_objfn, opt_data, \n success, rel_objfn_change, rel_objfn_change_tol, iter, n_gen, \n conv_failure_switch, settings_inp);\n\n \/\/\n\n return success;\n}\n\noptimlib_inline\nbool\noptim::pso(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data\n)\n{\n return internal::pso_impl(init_out_vals,opt_objfn,opt_data,nullptr);\n}\n\noptimlib_inline\nbool\noptim::pso(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data, \n algo_settings_t& settings\n)\n{\n return internal::pso_impl(init_out_vals,opt_objfn,opt_data,&settings);\n}\nfix PSO center particle bug\/*################################################################################\n ##\n ## Copyright (C) 2016-2022 Keith O'Hara\n ##\n ## This file is part of the OptimLib C++ library.\n ##\n ## Licensed under the Apache License, Version 2.0 (the \"License\");\n ## you may not use this file except in compliance with the License.\n ## You may obtain a copy of the License at\n ##\n ## http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n ##\n ## Unless required by applicable law or agreed to in writing, software\n ## distributed under the License is distributed on an \"AS IS\" BASIS,\n ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ## See the License for the specific language governing permissions and\n ## limitations under the License.\n ##\n ################################################################################*\/\n\n\/*\n * Particle Swarm Optimization (PSO)\n *\/\n\n#include \"optim.hpp\"\n\n\/\/ [OPTIM_BEGIN]\noptimlib_inline\nbool\noptim::internal::pso_impl(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data, \n algo_settings_t* settings_inp\n)\n{\n bool success = false;\n\n const size_t n_vals = BMO_MATOPS_SIZE(init_out_vals);\n\n \/\/\n \/\/ PSO settings\n\n algo_settings_t settings;\n\n if (settings_inp) {\n settings = *settings_inp;\n }\n\n const int print_level = settings.print_level;\n\n const uint_t conv_failure_switch = settings.conv_failure_switch;\n const fp_t rel_objfn_change_tol = settings.rel_objfn_change_tol;\n\n const bool center_particle = settings.pso_settings.center_particle;\n\n const size_t n_center = (center_particle) ? 1 : 0;\n const size_t n_pop = settings.pso_settings.n_pop;\n const size_t n_gen = settings.pso_settings.n_gen;\n const size_t check_freq = settings.pso_settings.check_freq;\n\n const uint_t inertia_method = settings.pso_settings.inertia_method;\n\n fp_t par_w = settings.pso_settings.par_initial_w;\n const fp_t par_w_max = settings.pso_settings.par_w_max;\n const fp_t par_w_min = settings.pso_settings.par_w_min;\n const fp_t par_damp = settings.pso_settings.par_w_damp;\n\n const uint_t velocity_method = settings.pso_settings.velocity_method;\n\n fp_t par_c_cog = settings.pso_settings.par_c_cog;\n fp_t par_c_soc = settings.pso_settings.par_c_soc;\n\n const fp_t par_initial_c_cog = settings.pso_settings.par_initial_c_cog;\n const fp_t par_final_c_cog = settings.pso_settings.par_final_c_cog;\n const fp_t par_initial_c_soc = settings.pso_settings.par_initial_c_soc;\n const fp_t par_final_c_soc = settings.pso_settings.par_final_c_soc;\n\n const bool return_position_mat = settings.pso_settings.return_position_mat;\n\n const bool vals_bound = settings.vals_bound;\n \n const ColVec_t lower_bounds = settings.lower_bounds;\n const ColVec_t upper_bounds = settings.upper_bounds;\n\n const ColVecInt_t bounds_type = determine_bounds_type(vals_bound, n_vals, lower_bounds, upper_bounds);\n\n ColVec_t par_initial_lb = ( BMO_MATOPS_SIZE(settings.pso_settings.initial_lb) == n_vals ) ? settings.pso_settings.initial_lb : BMO_MATOPS_ARRAY_ADD_SCALAR(init_out_vals, -0.5);\n ColVec_t par_initial_ub = ( BMO_MATOPS_SIZE(settings.pso_settings.initial_ub) == n_vals ) ? settings.pso_settings.initial_ub : BMO_MATOPS_ARRAY_ADD_SCALAR(init_out_vals, 0.5);\n\n sampling_bounds_check(vals_bound, n_vals, bounds_type, lower_bounds, upper_bounds, par_initial_lb, par_initial_ub);\n\n \/\/ parallelization setup\n\n int omp_n_threads = 1;\n\n#ifdef OPTIM_USE_OPENMP\n if (settings.pso_settings.omp_n_threads > 0) {\n omp_n_threads = settings.pso_settings.omp_n_threads;\n } else {\n omp_n_threads = std::max(1, static_cast(omp_get_max_threads()) \/ 2); \/\/ OpenMP often detects the number of virtual\/logical cores, not physical cores\n }\n#endif\n\n \/\/ random sampling setup\n\n rand_engine_t rand_engine(settings.rng_seed_value);\n std::vector rand_engines_vec;\n\n for (int i = 0; i < omp_n_threads; ++i) {\n size_t seed_val = generate_seed_value(i, omp_n_threads, rand_engine);\n rand_engines_vec.push_back(rand_engine_t(seed_val));\n }\n\n \/\/ lambda function for box constraints\n\n std::function box_objfn \\\n = [opt_objfn, vals_bound, bounds_type, lower_bounds, upper_bounds] (const ColVec_t& vals_inp, ColVec_t* grad_out, void* opt_data) \\\n -> fp_t \n {\n if (vals_bound) {\n ColVec_t vals_inv_trans = inv_transform(vals_inp, bounds_type, lower_bounds, upper_bounds);\n \n return opt_objfn(vals_inv_trans,nullptr,opt_data);\n } else {\n return opt_objfn(vals_inp,nullptr,opt_data);\n }\n };\n\n \/\/\n \/\/ initialize\n\n ColVec_t rand_vec(n_vals);\n ColVec_t objfn_vals(n_pop);\n Mat_t P(n_pop + n_center, n_vals);\n\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads) firstprivate(rand_vec)\n#endif\n for (size_t i = 0; i < n_pop; ++i) {\n size_t thread_num = 0;\n\n#ifdef OPTIM_USE_OPENMP\n thread_num = omp_get_thread_num();\n#endif\n\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec);\n \n P.row(i) = BMO_MATOPS_TRANSPOSE( par_initial_lb + BMO_MATOPS_HADAMARD_PROD( (par_initial_ub - par_initial_lb), rand_vec ) );\n\n fp_t prop_objfn_val = opt_objfn(BMO_MATOPS_TRANSPOSE(P.row(i)), nullptr, opt_data);\n\n if (!std::isfinite(prop_objfn_val)) {\n prop_objfn_val = inf;\n }\n \n objfn_vals(i) = prop_objfn_val;\n\n if (vals_bound) {\n P.row(i) = transform(P.row(i), bounds_type, lower_bounds, upper_bounds);\n }\n }\n\n if (center_particle) {\n \/\/ taken outside the loop due to parallelization\n P.row(n_pop) = BMO_MATOPS_COLWISE_SUM( BMO_MATOPS_MIDDLE_ROWS(P, 0, n_pop - 1) ) \/ static_cast(n_pop); \/\/ center vector\n }\n\n ColVec_t best_vals = objfn_vals;\n Mat_t best_vecs = P;\n\n fp_t min_objfn_val_running = BMO_MATOPS_MIN_VAL(objfn_vals);\n fp_t min_objfn_val_check = min_objfn_val_running;\n \n RowVec_t best_sol_running = P.row( bmo::index_min(objfn_vals) );\n\n OPTIM_PSO_TRACE(0, 0, min_objfn_val_running, min_objfn_val_check, best_sol_running, P);\n\n \/\/\n \/\/ begin loop\n\n size_t iter = 0;\n fp_t rel_objfn_change = 2.0*rel_objfn_change_tol;\n\n RowVec_t rand_vec_1(n_vals);\n RowVec_t rand_vec_2(n_vals);\n Mat_t V = BMO_MATOPS_ZERO_MAT(n_pop, n_vals);\n\n while (rel_objfn_change > rel_objfn_change_tol && iter < n_gen) {\n ++iter;\n \n \/\/\n \/\/ parameter updating\n\n if (inertia_method == 1) {\n par_w = par_w_min + (par_w_max - par_w_min) * (iter + 1) \/ n_gen;\n } else {\n par_w *= par_damp;\n }\n\n if (velocity_method == 2) {\n par_c_cog = par_initial_c_cog - (par_initial_c_cog - par_final_c_cog) * (iter + 1) \/ n_gen;\n par_c_soc = par_initial_c_soc - (par_initial_c_soc - par_final_c_soc) * (iter + 1) \/ n_gen;\n }\n\n \/\/\n \/\/ population loop\n\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads) firstprivate(rand_vec_1,rand_vec_2)\n#endif\n for (size_t i=0; i < n_pop; ++i) {\n size_t thread_num = 0;\n\n#ifdef OPTIM_USE_OPENMP\n thread_num = omp_get_thread_num();\n#endif\n\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec_1);\n bmo::stats::internal::runif_vec_inplace(n_vals, rand_engines_vec[thread_num], rand_vec_2);\n\n V.row(i) = par_w * V.row(i) + par_c_cog * BMO_MATOPS_HADAMARD_PROD( rand_vec_1, (best_vecs.row(i) - P.row(i)) ) \\\n + par_c_soc * BMO_MATOPS_HADAMARD_PROD( rand_vec_2, (best_sol_running - P.row(i)) );\n\n P.row(i) += V.row(i);\n \n \/\/\n\n fp_t prop_objfn_val = box_objfn( BMO_MATOPS_TRANSPOSE(P.row(i)), nullptr, opt_data);\n\n if (!std::isfinite(prop_objfn_val)) {\n prop_objfn_val = inf;\n }\n \n objfn_vals(i) = prop_objfn_val;\n \n if (objfn_vals(i) < best_vals(i)) {\n best_vals(i) = objfn_vals(i);\n best_vecs.row(i) = P.row(i);\n }\n }\n\n if (center_particle) {\n \/\/ taken outside the loop due to parallelization\n P.row(n_pop) = BMO_MATOPS_COLWISE_SUM( BMO_MATOPS_MIDDLE_ROWS(P, 0, n_pop - 1) ) \/ static_cast(n_pop); \/\/ center vector\n\n fp_t prop_objfn_val = box_objfn( BMO_MATOPS_TRANSPOSE(P.row(n_pop)), nullptr, opt_data);\n\n if (!std::isfinite(prop_objfn_val)) {\n prop_objfn_val = inf;\n }\n \n objfn_vals(n_pop) = prop_objfn_val;\n \n if (objfn_vals(n_pop) < best_vals(n_pop)) {\n best_vals(n_pop) = objfn_vals(n_pop);\n best_vecs.row(n_pop) = P.row(n_pop);\n }\n }\n\n size_t min_objfn_val_index = bmo::index_min(best_vals);\n fp_t min_objfn_val = best_vals(min_objfn_val_index);\n\n \/\/\n\n if (min_objfn_val < min_objfn_val_running) {\n min_objfn_val_running = min_objfn_val;\n best_sol_running = best_vecs.row( min_objfn_val_index );\n }\n\n if (iter % check_freq == 0) {\n rel_objfn_change = std::abs(min_objfn_val_running - min_objfn_val_check) \/ (OPTIM_FPN_SMALL_NUMBER + std::abs(min_objfn_val_running));\n \n if (min_objfn_val_running < min_objfn_val_check) {\n min_objfn_val_check = min_objfn_val_running;\n }\n }\n\n \/\/\n\n OPTIM_PSO_TRACE(iter, rel_objfn_change, min_objfn_val_running, min_objfn_val_check, best_sol_running, P);\n }\n\n \/\/\n\n if (return_position_mat) {\n if (vals_bound) {\n#ifdef OPTIM_USE_OPENMP\n #pragma omp parallel for num_threads(omp_n_threads)\n#endif\n for (size_t i = 0; i < n_pop + n_center; ++i) {\n P.row(i) = inv_transform(P.row(i), bounds_type, lower_bounds, upper_bounds);\n }\n }\n\n settings_inp->pso_settings.position_mat = P;\n }\n\n \/\/\n\n if (vals_bound) {\n best_sol_running = inv_transform( best_sol_running, bounds_type, lower_bounds, upper_bounds);\n }\n\n error_reporting(init_out_vals, BMO_MATOPS_TRANSPOSE(best_sol_running), opt_objfn, opt_data, \n success, rel_objfn_change, rel_objfn_change_tol, iter, n_gen, \n conv_failure_switch, settings_inp);\n\n \/\/\n\n return success;\n}\n\noptimlib_inline\nbool\noptim::pso(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data\n)\n{\n return internal::pso_impl(init_out_vals,opt_objfn,opt_data,nullptr);\n}\n\noptimlib_inline\nbool\noptim::pso(\n ColVec_t& init_out_vals, \n std::function opt_objfn, \n void* opt_data, \n algo_settings_t& settings\n)\n{\n return internal::pso_impl(init_out_vals,opt_objfn,opt_data,&settings);\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n#include \"grins_config.h\"\n\n#include \n\n\/\/ GRINS\n#include \"grins\/simulation_builder.h\"\n#include \"grins\/simulation.h\"\n\n\/\/ GRVY\n#ifdef GRINS_HAVE_GRVY\n#include \"grvy.h\"\n#endif\n\n\/\/ libMesh\n#include \"libmesh\/parallel.h\"\n\nint main(int argc, char* argv[])\n{\n#ifdef GRINS_USE_GRVY_TIMERS\n GRVY::GRVY_Timer_Class grvy_timer;\n grvy_timer.Init(\"GRINS Timer\");\n#endif\n\n \/\/ Check command line count.\n if( argc < 2 )\n {\n \/\/ TODO: Need more consistent error handling.\n std::cerr << \"Error: Must specify libMesh input file.\" << std::endl;\n exit(1); \/\/ TODO: something more sophisticated for parallel runs?\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = argv[1];\n \n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n \/\/ GetPot doesn't throw an error for a nonexistent file?\n {\n std::ifstream i(libMesh_input_filename.c_str());\n if (!i)\n {\n std::cerr << \"Error: Could not read from libMesh input file \"\n << libMesh_input_filename << std::endl;\n exit(1);\n }\n }\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.BeginTimer(\"Initialize Solver\");\n#endif\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n \n libMesh::out << \"Starting GRINS with command:\\n\";\n for (unsigned int i=0; i != argc; ++i)\n libMesh::out << argv[i] << ' ';\n libMesh::out << std::endl;\n\n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( libMesh_inputfile,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.EndTimer(\"Initialize Solver\");\n\n \/\/ Attach GRVY timer to solver\n grins.attach_grvy_timer( &grvy_timer );\n#endif\n\ngrins.run();\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.Finalize();\n \n if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();\n#endif\n\n return 0;\n}\nShut up comparison warning\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n#include \"grins_config.h\"\n\n#include \n\n\/\/ GRINS\n#include \"grins\/simulation_builder.h\"\n#include \"grins\/simulation.h\"\n\n\/\/ GRVY\n#ifdef GRINS_HAVE_GRVY\n#include \"grvy.h\"\n#endif\n\n\/\/ libMesh\n#include \"libmesh\/parallel.h\"\n\nint main(int argc, char* argv[])\n{\n#ifdef GRINS_USE_GRVY_TIMERS\n GRVY::GRVY_Timer_Class grvy_timer;\n grvy_timer.Init(\"GRINS Timer\");\n#endif\n\n \/\/ Check command line count.\n if( argc < 2 )\n {\n \/\/ TODO: Need more consistent error handling.\n std::cerr << \"Error: Must specify libMesh input file.\" << std::endl;\n exit(1); \/\/ TODO: something more sophisticated for parallel runs?\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = argv[1];\n \n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n \/\/ GetPot doesn't throw an error for a nonexistent file?\n {\n std::ifstream i(libMesh_input_filename.c_str());\n if (!i)\n {\n std::cerr << \"Error: Could not read from libMesh input file \"\n << libMesh_input_filename << std::endl;\n exit(1);\n }\n }\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.BeginTimer(\"Initialize Solver\");\n#endif\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n \n libMesh::out << \"Starting GRINS with command:\\n\";\n for (int i=0; i != argc; ++i)\n libMesh::out << argv[i] << ' ';\n libMesh::out << std::endl;\n\n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( libMesh_inputfile,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.EndTimer(\"Initialize Solver\");\n\n \/\/ Attach GRVY timer to solver\n grins.attach_grvy_timer( &grvy_timer );\n#endif\n\ngrins.run();\n\n#ifdef GRINS_USE_GRVY_TIMERS\n grvy_timer.Finalize();\n \n if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"common.h\"\n#include \n#include \n#include \n\n#include \"Memory.h\"\n\n#define NUM_BUFFER_BITS 16\n#define MAX_NUM_BUFFERS ((size_t)1 << NUM_BUFFER_BITS)\n#define NUM_ADDRESS_BITS ((sizeof(size_t)<<3) - NUM_BUFFER_BITS)\n#define MAX_BUFFER_SIZE ((size_t)1 << NUM_ADDRESS_BITS)\n\n#define EXTRACT_BUFFER(address) \\\n (address >> NUM_ADDRESS_BITS)\n#define EXTRACT_OFFSET(address) \\\n (address ^ (EXTRACT_BUFFER(address) << NUM_ADDRESS_BITS))\n\nusing namespace spirsim;\nusing namespace std;\n\nMemory::Memory()\n{\n clear();\n}\n\nMemory::~Memory()\n{\n clear();\n}\n\nsize_t Memory::allocateBuffer(size_t size)\n{\n \/\/ Check requested size doesn't exceed maximum\n if (size > MAX_BUFFER_SIZE)\n {\n return NULL;\n }\n\n \/\/ Find first unallocated buffer slot\n int b = getNextBuffer();\n if (b < 0 || b >= MAX_NUM_BUFFERS)\n {\n return NULL;\n }\n\n \/\/ Create buffer\n Buffer buffer = {\n false,\n size,\n new unsigned char[size]\n };\n\n \/\/ Initialize contents to 0\n \/\/ TODO: Solution to catch use of uninitialised data\n memset(buffer.data, 0, size);\n\n m_memory[b] = buffer;\n m_totalAllocated += size;\n\n return ((size_t)b) << NUM_ADDRESS_BITS;\n}\n\nvoid Memory::clear()\n{\n map::iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n if (!itr->second.hostPtr)\n {\n delete[] itr->second.data;\n }\n }\n m_memory.clear();\n m_freeBuffers = queue();\n m_totalAllocated = 0;\n\n \/\/ Reserve first buffer as a makeshift 'NULL'\n m_memory[0].data = new unsigned char[0];\n\n}\n\nMemory* Memory::clone() const\n{\n Memory *mem = new Memory();\n\n \/\/ Clone buffers\n map::const_iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n Buffer src = itr->second;\n Buffer dest = {\n src.hostPtr,\n src.size,\n src.hostPtr ? src.data : new unsigned char[src.size]\n };\n memcpy(dest.data, src.data, src.size);\n mem->m_memory[itr->first] = dest;\n }\n\n \/\/ Clone state\n mem->m_freeBuffers = m_freeBuffers;\n mem->m_totalAllocated = m_totalAllocated;\n\n return mem;\n}\n\nsize_t Memory::createHostBuffer(size_t size, void *ptr)\n{\n \/\/ Check requested size doesn't exceed maximum\n if (size > MAX_BUFFER_SIZE)\n {\n return NULL;\n }\n\n \/\/ Find first unallocated buffer slot\n int b = getNextBuffer();\n if (b < 0 || b >= MAX_NUM_BUFFERS)\n {\n return NULL;\n }\n\n \/\/ Create buffer\n Buffer buffer = {\n true,\n size,\n (unsigned char*)ptr\n };\n\n m_memory[b] = buffer;\n m_totalAllocated += size;\n\n return ((size_t)b) << NUM_ADDRESS_BITS;\n}\n\nbool Memory::copy(size_t dest, size_t src, size_t size)\n{\n size_t src_buffer = EXTRACT_BUFFER(src);\n size_t src_offset = EXTRACT_OFFSET(src);\n size_t dest_buffer = EXTRACT_BUFFER(dest);\n size_t dest_offset = EXTRACT_OFFSET(dest);\n\n \/\/ Bounds check\n if (src_buffer >= MAX_NUM_BUFFERS ||\n dest_buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(src_buffer) == m_memory.end() ||\n m_memory.find(dest_buffer) == m_memory.end() ||\n src_offset+size > m_memory.at(src_buffer).size ||\n dest_offset+size > m_memory.at(dest_buffer).size)\n {\n return false;\n }\n\n \/\/ Copy data\n memcpy(m_memory.at(dest_buffer).data + dest_offset,\n m_memory.at(src_buffer).data + src_offset,\n size);\n\n return true;\n}\n\nvoid Memory::deallocateBuffer(size_t address)\n{\n int buffer = EXTRACT_BUFFER(address);\n assert(buffer < MAX_NUM_BUFFERS && m_memory.find(buffer) != m_memory.end());\n\n if (!m_memory[buffer].hostPtr)\n {\n delete[] m_memory[buffer].data;\n }\n\n m_totalAllocated -= m_memory[buffer].size;\n m_memory.erase(buffer);\n m_freeBuffers.push(buffer);\n}\n\nvoid Memory::dump() const\n{\n map::const_iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n for (int i = 0; i < itr->second.size; i++)\n {\n if (i%4 == 0)\n {\n cout << endl << hex << uppercase\n << setw(16) << setfill(' ') << right\n << ((((size_t)itr->first)<second.data[i];\n }\n }\n cout << endl;\n}\n\nsize_t Memory::getMaxAllocSize()\n{\n return MAX_BUFFER_SIZE;\n}\n\nint Memory::getNextBuffer()\n{\n if (m_freeBuffers.empty())\n {\n return m_memory.size();\n }\n else\n {\n int b = m_freeBuffers.front();\n m_freeBuffers.pop();\n return b;\n }\n}\n\nsize_t Memory::getTotalAllocated() const\n{\n return m_totalAllocated;\n}\n\nbool Memory::load(unsigned char *dest, size_t address, size_t size) const\n{\n size_t buffer = EXTRACT_BUFFER(address);\n size_t offset = EXTRACT_OFFSET(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory.at(buffer).size)\n {\n return false;\n }\n\n \/\/ Load data\n memcpy(dest, m_memory.at(buffer).data + offset, size);\n\n return true;\n}\n\nunsigned char* Memory::mapBuffer(size_t address, size_t offset, size_t size)\n{\n size_t buffer = EXTRACT_BUFFER(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory[buffer].size)\n {\n return false;\n }\n\n return m_memory[buffer].data + offset;\n}\n\nbool Memory::store(const unsigned char *source, size_t address, size_t size)\n{\n size_t buffer = EXTRACT_BUFFER(address);\n size_t offset = EXTRACT_OFFSET(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory[buffer].size)\n {\n return false;\n }\n\n \/\/ Store data\n memcpy(m_memory[buffer].data + offset, source, size);\n\n return true;\n}\nFixed leak in Memory class for its NULL buffer.#include \"common.h\"\n#include \n#include \n#include \n\n#include \"Memory.h\"\n\n#define NUM_BUFFER_BITS 16\n#define MAX_NUM_BUFFERS ((size_t)1 << NUM_BUFFER_BITS)\n#define NUM_ADDRESS_BITS ((sizeof(size_t)<<3) - NUM_BUFFER_BITS)\n#define MAX_BUFFER_SIZE ((size_t)1 << NUM_ADDRESS_BITS)\n\n#define EXTRACT_BUFFER(address) \\\n (address >> NUM_ADDRESS_BITS)\n#define EXTRACT_OFFSET(address) \\\n (address ^ (EXTRACT_BUFFER(address) << NUM_ADDRESS_BITS))\n\nusing namespace spirsim;\nusing namespace std;\n\nMemory::Memory()\n{\n clear();\n}\n\nMemory::~Memory()\n{\n clear();\n\n delete[] m_memory[0].data;\n}\n\nsize_t Memory::allocateBuffer(size_t size)\n{\n \/\/ Check requested size doesn't exceed maximum\n if (size > MAX_BUFFER_SIZE)\n {\n return NULL;\n }\n\n \/\/ Find first unallocated buffer slot\n int b = getNextBuffer();\n if (b < 0 || b >= MAX_NUM_BUFFERS)\n {\n return NULL;\n }\n\n \/\/ Create buffer\n Buffer buffer = {\n false,\n size,\n new unsigned char[size]\n };\n\n \/\/ Initialize contents to 0\n \/\/ TODO: Solution to catch use of uninitialised data\n memset(buffer.data, 0, size);\n\n m_memory[b] = buffer;\n m_totalAllocated += size;\n\n return ((size_t)b) << NUM_ADDRESS_BITS;\n}\n\nvoid Memory::clear()\n{\n map::iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n if (!itr->second.hostPtr)\n {\n delete[] itr->second.data;\n }\n }\n m_memory.clear();\n m_freeBuffers = queue();\n m_totalAllocated = 0;\n\n \/\/ Reserve first buffer as a makeshift 'NULL'\n m_memory[0].data = new unsigned char[0];\n}\n\nMemory* Memory::clone() const\n{\n Memory *mem = new Memory();\n\n \/\/ Clone buffers\n map::const_iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n Buffer src = itr->second;\n Buffer dest = {\n src.hostPtr,\n src.size,\n src.hostPtr ? src.data : new unsigned char[src.size]\n };\n memcpy(dest.data, src.data, src.size);\n mem->m_memory[itr->first] = dest;\n }\n\n \/\/ Clone state\n mem->m_freeBuffers = m_freeBuffers;\n mem->m_totalAllocated = m_totalAllocated;\n\n return mem;\n}\n\nsize_t Memory::createHostBuffer(size_t size, void *ptr)\n{\n \/\/ Check requested size doesn't exceed maximum\n if (size > MAX_BUFFER_SIZE)\n {\n return NULL;\n }\n\n \/\/ Find first unallocated buffer slot\n int b = getNextBuffer();\n if (b < 0 || b >= MAX_NUM_BUFFERS)\n {\n return NULL;\n }\n\n \/\/ Create buffer\n Buffer buffer = {\n true,\n size,\n (unsigned char*)ptr\n };\n\n m_memory[b] = buffer;\n m_totalAllocated += size;\n\n return ((size_t)b) << NUM_ADDRESS_BITS;\n}\n\nbool Memory::copy(size_t dest, size_t src, size_t size)\n{\n size_t src_buffer = EXTRACT_BUFFER(src);\n size_t src_offset = EXTRACT_OFFSET(src);\n size_t dest_buffer = EXTRACT_BUFFER(dest);\n size_t dest_offset = EXTRACT_OFFSET(dest);\n\n \/\/ Bounds check\n if (src_buffer >= MAX_NUM_BUFFERS ||\n dest_buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(src_buffer) == m_memory.end() ||\n m_memory.find(dest_buffer) == m_memory.end() ||\n src_offset+size > m_memory.at(src_buffer).size ||\n dest_offset+size > m_memory.at(dest_buffer).size)\n {\n return false;\n }\n\n \/\/ Copy data\n memcpy(m_memory.at(dest_buffer).data + dest_offset,\n m_memory.at(src_buffer).data + src_offset,\n size);\n\n return true;\n}\n\nvoid Memory::deallocateBuffer(size_t address)\n{\n int buffer = EXTRACT_BUFFER(address);\n assert(buffer < MAX_NUM_BUFFERS && m_memory.find(buffer) != m_memory.end());\n\n if (!m_memory[buffer].hostPtr)\n {\n delete[] m_memory[buffer].data;\n }\n\n m_totalAllocated -= m_memory[buffer].size;\n m_memory.erase(buffer);\n m_freeBuffers.push(buffer);\n}\n\nvoid Memory::dump() const\n{\n map::const_iterator itr;\n for (itr = m_memory.begin(); itr != m_memory.end(); itr++)\n {\n for (int i = 0; i < itr->second.size; i++)\n {\n if (i%4 == 0)\n {\n cout << endl << hex << uppercase\n << setw(16) << setfill(' ') << right\n << ((((size_t)itr->first)<second.data[i];\n }\n }\n cout << endl;\n}\n\nsize_t Memory::getMaxAllocSize()\n{\n return MAX_BUFFER_SIZE;\n}\n\nint Memory::getNextBuffer()\n{\n if (m_freeBuffers.empty())\n {\n return m_memory.size();\n }\n else\n {\n int b = m_freeBuffers.front();\n m_freeBuffers.pop();\n return b;\n }\n}\n\nsize_t Memory::getTotalAllocated() const\n{\n return m_totalAllocated;\n}\n\nbool Memory::load(unsigned char *dest, size_t address, size_t size) const\n{\n size_t buffer = EXTRACT_BUFFER(address);\n size_t offset = EXTRACT_OFFSET(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory.at(buffer).size)\n {\n return false;\n }\n\n \/\/ Load data\n memcpy(dest, m_memory.at(buffer).data + offset, size);\n\n return true;\n}\n\nunsigned char* Memory::mapBuffer(size_t address, size_t offset, size_t size)\n{\n size_t buffer = EXTRACT_BUFFER(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory[buffer].size)\n {\n return false;\n }\n\n return m_memory[buffer].data + offset;\n}\n\nbool Memory::store(const unsigned char *source, size_t address, size_t size)\n{\n size_t buffer = EXTRACT_BUFFER(address);\n size_t offset = EXTRACT_OFFSET(address);\n\n \/\/ Bounds check\n if (buffer >= MAX_NUM_BUFFERS ||\n m_memory.find(buffer) == m_memory.end() ||\n offset+size > m_memory[buffer].size)\n {\n return false;\n }\n\n \/\/ Store data\n memcpy(m_memory[buffer].data + offset, source, size);\n\n return true;\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashctl.h\"\n\nusing namespace std;\n\nvoid ShowUsage();\nvoid ShowVersion();\n\n\/\/Mutex to control access to all global node lists\nmutex g_toolchainListMutex;\n\n\/\/List of nodes (eliminate multiple splashbuild instances)\nunordered_set g_activeClients;\n\n\/\/List of compilers available on each node\n\/\/This is the authoritative pointer to nodes\nmap g_toolchainsByNode;\n\n\/\/List of nodes with any compiler for a given language and target architecture\nmap g_nodesByLanguage;\n\n\/\/List of nodes with a specific compiler (by hash)\nmap g_nodesByCompiler;\n\n\/**\n\t@brief Program entry point\n *\/\nint main(int argc, char* argv[])\n{\n\tint port = 49000;\n\n\tSeverity console_verbosity = Severity::NOTICE;\n\t\n\t\/\/Parse command-line arguments\n\tfor(int i=1; i= Severity::NOTICE)\n\t{\n\t\tShowVersion();\n\t\tprintf(\"\\n\");\n\t}\n\n\t\/\/Socket server\n\tSocket server(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif(!server.Bind(port))\n\t\treturn -1;\n\tif(!server.Listen())\n\t\treturn -1;\n\twhile(true)\n\t{\n\t\tthread t(ClientThread, server.Accept().Detach());\n\t\tt.detach();\n\t}\n\n\treturn 0;\n}\n\nvoid ShowVersion()\n{\n\tprintf(\n\t\t\"SPLASH control server daemon by Andrew D. Zonenberg.\\n\"\n\t\t\"\\n\"\n\t\t\"License: 3-clause BSD\\n\"\n\t\t\"This is free software: you are free to change and redistribute it.\\n\"\n\t\t\"There is NO WARRANTY, to the extent permitted by law.\\n\");\n}\n\nvoid ShowUsage()\n{\n\tprintf(\"Usage: splashctl [control_port]\\n\");\n\texit(0);\n}\nsplashctl: Added a bunch of comments describing future work\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashctl.h\"\n\nusing namespace std;\n\nvoid ShowUsage();\nvoid ShowVersion();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global state: toolchains\n\n\/\/Mutex to control access to all global node lists\nmutex g_toolchainListMutex;\n\n\/\/List of nodes (eliminate multiple splashbuild instances)\nunordered_set g_activeClients;\n\n\/\/List of compilers available on each node\n\/\/This is the authoritative pointer to nodes\nmap g_toolchainsByNode;\n\n\/\/List of nodes with any compiler for a given language and target architecture\nmap g_nodesByLanguage;\n\n\/\/List of nodes with a specific compiler (by hash)\nmap g_nodesByCompiler;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global state: files on clients\n\n\/*\n\tSet of hashes for source\/object files we have in the cache (need to read at app startup)\n\n\tDirectory structure:\n\t$CACHE\/\n\t\txx\/\t\t\t\tfirst octet of hash, as hex\n\t\t\thash\/\t\thash of file object (may not actually be the hash of the file, includes flags etc)\n\t\t\t\txx\t\tthe file itself (original filename)\n\t\t\t\t.hash\tsha256 of the file itself (for load-time integrity checking)\n\t\t\t\t.atime\tlast-accessed time of the file\n\t\t\t\t\t\tWe don't use filesystem atime as that's way too easy to set by accident\n\n\tGlobal cache:\n\tunordered_set \tlisting which hashes we have in the cache\n\tmap\t\tmapping hashes to last-used times\n\n\tClient state:\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ App code\n\n\/**\n\t@brief Program entry point\n *\/\nint main(int argc, char* argv[])\n{\n\tint port = 49000;\n\n\tSeverity console_verbosity = Severity::NOTICE;\n\t\n\t\/\/Parse command-line arguments\n\tfor(int i=1; i= Severity::NOTICE)\n\t{\n\t\tShowVersion();\n\t\tprintf(\"\\n\");\n\t}\n\n\t\/\/Socket server\n\tSocket server(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif(!server.Bind(port))\n\t\treturn -1;\n\tif(!server.Listen())\n\t\treturn -1;\n\twhile(true)\n\t{\n\t\tthread t(ClientThread, server.Accept().Detach());\n\t\tt.detach();\n\t}\n\n\treturn 0;\n}\n\nvoid ShowVersion()\n{\n\tprintf(\n\t\t\"SPLASH control server daemon by Andrew D. Zonenberg.\\n\"\n\t\t\"\\n\"\n\t\t\"License: 3-clause BSD\\n\"\n\t\t\"This is free software: you are free to change and redistribute it.\\n\"\n\t\t\"There is NO WARRANTY, to the extent permitted by law.\\n\");\n}\n\nvoid ShowUsage()\n{\n\tprintf(\"Usage: splashctl [control_port]\\n\");\n\texit(0);\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \"SDL.h\"\n#undef main\n\nnamespace MgCore\n{\n\n enum class KeyCode\n {\n _KEY_NONE = 0,\n KEY_A,\n KEY_B,\n KEY_C,\n KEY_D,\n KEY_E,\n KEY_F,\n KEY_G,\n KEY_H,\n KEY_I,\n KEY_J,\n KEY_K,\n KEY_L,\n KEY_M,\n KEY_N,\n KEY_O,\n KEY_P,\n KEY_Q,\n KEY_R,\n KEY_S,\n KEY_T,\n KEY_U,\n KEY_V,\n KEY_W,\n KEY_X,\n KEY_Y,\n KEY_Z,\n KEY_1,\n KEY_2,\n KEY_3,\n KEY_4,\n KEY_5,\n KEY_6,\n KEY_7,\n KEY_8,\n KEY_9,\n KEY_RETURN,\n KEY_ESCAPE,\n KEY_BACKSPACE,\n KEY_TAB,\n KEY_SPACE,\n KEY_MINUS,\n KEY_EQUALS,\n KEY_LEFT_BRACKET,\n KEY_RIGHT_BRACKET,\n KEY_BACKSLASH,\n KEY_SEMICOLON,\n KEY_APOSTROPHE,\n KEY_GRAVE,\n KEY_COMMA,\n KEY_PERIOD,\n KEY_SLASH,\n KEY_CAPS_LOCK,\n KEY_F1,\n KEY_F2,\n KEY_F3,\n KEY_F4,\n KEY_F5,\n KEY_F6,\n KEY_F7,\n KEY_F8,\n KEY_F9,\n KEY_F10,\n KEY_F11,\n KEY_F12,\n KEY_PRINT_SCREEN,\n KEY_SCROLL_LOCK,\n KEY_PAUSE,\n KEY_INSERT,\n KEY_HOME,\n KEY_PAGE_UP,\n KEY_DELETE,\n KEY_END,\n KEY_PAGE_DOWN,\n KEY_RIGHT,\n KEY_LEFT,\n KEY_DOWN,\n KEY_UP,\n KEY_NUMLOCK_CLEAR,\n KEY_KP_DIVIDE,\n KEY_KP_MULTIPLY,\n KEY_KP_MINUS,\n KEY_KP_PLUS,\n KEY_KP_ENTER,\n KEY_KP_1,\n KEY_KP_2,\n KEY_KP_3,\n KEY_KP_4,\n KEY_KP_5,\n KEY_KP_6,\n KEY_KP_7,\n KEY_KP_8,\n KEY_KP_9,\n KEY_KP_0,\n KEY_KP_PERIOD,\n KEY_NON_US_BACKSLASH,\n KEY_LEFT_CTRL,\n KEY_LEFT_SHIFT,\n KEY_LEFT_ALT,\n KEY_LEFT_SUPER,\n KEY_RIGHT_CTRL,\n KEY_RIGHT_SHIFT,\n KEY_RIGHT_ALT,\n KEY_RIGHT_SUPER\n };\n\n enum class ModFlag\n {\n MOD_NONE = 0,\n MOD_LEFT_SHIFT = 1 << 0,\n MOD_RIGHT_SHIFT = 1 << 1,\n MOD_LEFT_CTRL = 1 << 2,\n MOD_RIGHT_CTRL = 1 << 3,\n MOD_LEFT_ALT = 1 << 4,\n MOD_RIGHT_ALT = 1 << 5,\n MOD_LEFT_SUPER = 1 << 6,\n MOD_RIGHT_SUPER = 1 << 7,\n MOD_NUM = 1 << 8,\n MOD_CAPS = 1 << 9,\n };\n\n using underlying = std::underlying_type::type;\n\n static ModFlag operator|(const ModFlag& left, const ModFlag& right)\n {\n return static_cast(static_cast(left) | static_cast(right));\n }\n\n static ModFlag operator&(const ModFlag& left, const ModFlag& right)\n {\n return static_cast(static_cast(left) & static_cast(right));\n }\n\n\n static std::map modMap {\n {KMOD_NONE, ModFlag::MOD_NONE},\n {KMOD_LSHIFT, ModFlag::MOD_LEFT_SHIFT},\n {KMOD_RSHIFT, ModFlag::MOD_RIGHT_SHIFT},\n {KMOD_LCTRL, ModFlag::MOD_LEFT_CTRL},\n {KMOD_RCTRL, ModFlag::MOD_RIGHT_CTRL},\n {KMOD_LALT, ModFlag::MOD_LEFT_ALT},\n {KMOD_RALT, ModFlag::MOD_RIGHT_ALT},\n {KMOD_LGUI, ModFlag::MOD_LEFT_SUPER},\n {KMOD_RGUI, ModFlag::MOD_RIGHT_SUPER},\n {KMOD_NUM, ModFlag::MOD_NUM},\n {KMOD_CAPS, ModFlag::MOD_CAPS}};\n\n\n static std::map keyMap {\n {SDL_SCANCODE_A, KeyCode::KEY_A},\n {SDL_SCANCODE_B, KeyCode::KEY_B},\n {SDL_SCANCODE_C, KeyCode::KEY_C},\n {SDL_SCANCODE_D, KeyCode::KEY_D},\n {SDL_SCANCODE_E, KeyCode::KEY_E},\n {SDL_SCANCODE_F, KeyCode::KEY_F},\n {SDL_SCANCODE_G, KeyCode::KEY_G},\n {SDL_SCANCODE_H, KeyCode::KEY_H},\n {SDL_SCANCODE_I, KeyCode::KEY_I},\n {SDL_SCANCODE_J, KeyCode::KEY_J},\n {SDL_SCANCODE_K, KeyCode::KEY_K},\n {SDL_SCANCODE_L, KeyCode::KEY_L},\n {SDL_SCANCODE_M, KeyCode::KEY_M},\n {SDL_SCANCODE_N, KeyCode::KEY_N},\n {SDL_SCANCODE_O, KeyCode::KEY_O},\n {SDL_SCANCODE_P, KeyCode::KEY_P},\n {SDL_SCANCODE_Q, KeyCode::KEY_Q},\n {SDL_SCANCODE_R, KeyCode::KEY_R},\n {SDL_SCANCODE_S, KeyCode::KEY_S},\n {SDL_SCANCODE_T, KeyCode::KEY_T},\n {SDL_SCANCODE_U, KeyCode::KEY_U},\n {SDL_SCANCODE_V, KeyCode::KEY_V},\n {SDL_SCANCODE_W, KeyCode::KEY_W},\n {SDL_SCANCODE_X, KeyCode::KEY_X},\n {SDL_SCANCODE_Y, KeyCode::KEY_Y},\n {SDL_SCANCODE_Z, KeyCode::KEY_Z},\n {SDL_SCANCODE_1, KeyCode::KEY_1},\n {SDL_SCANCODE_2, KeyCode::KEY_2},\n {SDL_SCANCODE_3, KeyCode::KEY_3},\n {SDL_SCANCODE_4, KeyCode::KEY_4},\n {SDL_SCANCODE_5, KeyCode::KEY_5},\n {SDL_SCANCODE_6, KeyCode::KEY_6},\n {SDL_SCANCODE_7, KeyCode::KEY_7},\n {SDL_SCANCODE_8, KeyCode::KEY_7},\n {SDL_SCANCODE_9, KeyCode::KEY_8},\n {SDL_SCANCODE_0, KeyCode::KEY_9},\n {SDL_SCANCODE_RETURN, KeyCode::KEY_RETURN},\n {SDL_SCANCODE_ESCAPE, KeyCode::KEY_ESCAPE},\n {SDL_SCANCODE_BACKSPACE, KeyCode::KEY_BACKSPACE},\n {SDL_SCANCODE_TAB, KeyCode::KEY_TAB},\n {SDL_SCANCODE_SPACE, KeyCode::KEY_SPACE},\n {SDL_SCANCODE_MINUS, KeyCode::KEY_MINUS},\n {SDL_SCANCODE_EQUALS, KeyCode::KEY_EQUALS},\n {SDL_SCANCODE_LEFTBRACKET, KeyCode::KEY_LEFT_BRACKET},\n {SDL_SCANCODE_RIGHTBRACKET, KeyCode::KEY_RIGHT_BRACKET},\n {SDL_SCANCODE_BACKSLASH, KeyCode::KEY_BACKSLASH},\n {SDL_SCANCODE_SEMICOLON, KeyCode::KEY_SEMICOLON},\n {SDL_SCANCODE_APOSTROPHE, KeyCode::KEY_APOSTROPHE},\n {SDL_SCANCODE_GRAVE, KeyCode::KEY_GRAVE},\n {SDL_SCANCODE_COMMA, KeyCode::KEY_COMMA},\n {SDL_SCANCODE_PERIOD, KeyCode::KEY_PERIOD},\n {SDL_SCANCODE_SLASH, KeyCode::KEY_SLASH},\n {SDL_SCANCODE_CAPSLOCK, KeyCode::KEY_CAPS_LOCK},\n {SDL_SCANCODE_F1, KeyCode::KEY_F1},\n {SDL_SCANCODE_F2, KeyCode::KEY_F2},\n {SDL_SCANCODE_F3, KeyCode::KEY_F3},\n {SDL_SCANCODE_F4, KeyCode::KEY_F4},\n {SDL_SCANCODE_F5, KeyCode::KEY_F5},\n {SDL_SCANCODE_F6, KeyCode::KEY_F6},\n {SDL_SCANCODE_F7, KeyCode::KEY_F7},\n {SDL_SCANCODE_F8, KeyCode::KEY_F8},\n {SDL_SCANCODE_F9, KeyCode::KEY_F9},\n {SDL_SCANCODE_F10, KeyCode::KEY_F10},\n {SDL_SCANCODE_F11, KeyCode::KEY_F11},\n {SDL_SCANCODE_F12, KeyCode::KEY_F12},\n {SDL_SCANCODE_PRINTSCREEN, KeyCode::KEY_PRINT_SCREEN},\n {SDL_SCANCODE_SCROLLLOCK, KeyCode::KEY_SCROLL_LOCK},\n {SDL_SCANCODE_PAUSE, KeyCode::KEY_PAUSE},\n {SDL_SCANCODE_INSERT, KeyCode::KEY_INSERT},\n {SDL_SCANCODE_HOME, KeyCode::KEY_HOME},\n {SDL_SCANCODE_PAGEUP, KeyCode::KEY_PAGE_UP},\n {SDL_SCANCODE_DELETE, KeyCode::KEY_DELETE},\n {SDL_SCANCODE_END, KeyCode::KEY_END},\n {SDL_SCANCODE_PAGEDOWN, KeyCode::KEY_PAGE_DOWN},\n {SDL_SCANCODE_RIGHT, KeyCode::KEY_RIGHT},\n {SDL_SCANCODE_LEFT, KeyCode::KEY_LEFT},\n {SDL_SCANCODE_DOWN, KeyCode::KEY_DOWN},\n {SDL_SCANCODE_UP, KeyCode::KEY_UP},\n {SDL_SCANCODE_NUMLOCKCLEAR, KeyCode::KEY_NUMLOCK_CLEAR},\n {SDL_SCANCODE_KP_DIVIDE, KeyCode::KEY_KP_DIVIDE},\n {SDL_SCANCODE_KP_MULTIPLY, KeyCode::KEY_KP_MULTIPLY},\n {SDL_SCANCODE_KP_MINUS, KeyCode::KEY_KP_MINUS},\n {SDL_SCANCODE_KP_PLUS, KeyCode::KEY_KP_PLUS},\n {SDL_SCANCODE_KP_ENTER, KeyCode::KEY_KP_ENTER},\n {SDL_SCANCODE_KP_1, KeyCode::KEY_KP_1},\n {SDL_SCANCODE_KP_2, KeyCode::KEY_KP_2},\n {SDL_SCANCODE_KP_3, KeyCode::KEY_KP_3},\n {SDL_SCANCODE_KP_4, KeyCode::KEY_KP_4},\n {SDL_SCANCODE_KP_5, KeyCode::KEY_KP_5},\n {SDL_SCANCODE_KP_6, KeyCode::KEY_KP_6},\n {SDL_SCANCODE_KP_7, KeyCode::KEY_KP_7},\n {SDL_SCANCODE_KP_8, KeyCode::KEY_KP_8},\n {SDL_SCANCODE_KP_9, KeyCode::KEY_KP_9},\n {SDL_SCANCODE_KP_0, KeyCode::KEY_KP_0},\n {SDL_SCANCODE_KP_PERIOD, KeyCode::KEY_KP_PERIOD},\n {SDL_SCANCODE_NONUSBACKSLASH, KeyCode::KEY_NON_US_BACKSLASH},\n {SDL_SCANCODE_LCTRL, KeyCode::KEY_LEFT_CTRL},\n {SDL_SCANCODE_LSHIFT, KeyCode::KEY_LEFT_SHIFT},\n {SDL_SCANCODE_LALT, KeyCode::KEY_LEFT_ALT},\n {SDL_SCANCODE_LGUI, KeyCode::KEY_LEFT_SUPER},\n {SDL_SCANCODE_RCTRL, KeyCode::KEY_RIGHT_CTRL},\n {SDL_SCANCODE_RSHIFT, KeyCode::KEY_RIGHT_SHIFT},\n {SDL_SCANCODE_RALT, KeyCode::KEY_RIGHT_ALT},\n {SDL_SCANCODE_RGUI, KeyCode::KEY_RIGHT_SUPER}\n };\n\n\n static std::map keyStrMap {\n {KeyCode::KEY_CAPS_LOCK, \"CAPS LOCK\"},\n {KeyCode::KEY_F1, \"F1\"},\n {KeyCode::KEY_F2, \"F2\"},\n {KeyCode::KEY_F3, \"F3\"},\n {KeyCode::KEY_F4, \"F4\"},\n {KeyCode::KEY_F5, \"F5\"},\n {KeyCode::KEY_F6, \"F6\"},\n {KeyCode::KEY_F7, \"F7\"},\n {KeyCode::KEY_F8, \"F8\"},\n {KeyCode::KEY_F9, \"F9\"},\n {KeyCode::KEY_F10, \"F10\"},\n {KeyCode::KEY_F11, \"F11\"},\n {KeyCode::KEY_F12, \"F12\"},\n {KeyCode::KEY_PRINT_SCREEN, \"PRINT SCREEN\"},\n {KeyCode::KEY_SCROLL_LOCK, \"SCROLL LOCK\"},\n {KeyCode::KEY_PAUSE, \"PAUSE\"},\n {KeyCode::KEY_INSERT, \"INSERT\"},\n {KeyCode::KEY_HOME, \"HOME\"},\n {KeyCode::KEY_PAGE_UP, \"PAGE UP\"},\n {KeyCode::KEY_END, \"END\"},\n {KeyCode::KEY_PAGE_DOWN, \"PAGE DOWN\"},\n {KeyCode::KEY_RIGHT, \"RIGHT\"},\n {KeyCode::KEY_LEFT, \"LEFT\"},\n {KeyCode::KEY_DOWN, \"DOWN\"},\n {KeyCode::KEY_UP, \"UP\"},\n {KeyCode::KEY_NUMLOCK_CLEAR, \"NUMLOCK CLEAR\"},\n {KeyCode::KEY_LEFT_CTRL, \"LEFT CTRL\"},\n {KeyCode::KEY_LEFT_SHIFT, \"LEFT SHIFT\"},\n {KeyCode::KEY_LEFT_ALT, \"LEFT ALT\"},\n {KeyCode::KEY_LEFT_SUPER, \"LEFT SUPER\"},\n {KeyCode::KEY_RIGHT_CTRL, \"RIGHT CTRL\"},\n {KeyCode::KEY_RIGHT_SHIFT, \"RIGHT SHIFT\"},\n {KeyCode::KEY_RIGHT_ALT, \"RIGHT ALT\"},\n {KeyCode::KEY_RIGHT_SUPER, \"RIGHT SUPER\"}\n };\n\n\n\n\/\/ def process_modkeys(value):\n\/\/ keys = []\n\/\/ for key in modmap:\n\/\/ if value & key:\n\/\/ keys.append(modmap[key])\n\/\/ return keys\n\n\/\/ def process_key_char(value):\n\/\/ char = None\n\/\/ try:\n\/\/ char = str(chr(value))\n\/\/ except ValueError:\n\/\/ temp = value ^ (1<<30)\n\/\/ if temp in keymap:\n\/\/ char = keystrMap[keymap[temp]]\n\/\/ return char\n\n}\nimplement keymodifier checking function.#pragma once\n\n#include \n#include \n#include \n#include \n#include \"SDL.h\"\n#undef main\n\nnamespace MgCore\n{\n\n enum class KeyCode\n {\n _KEY_NONE = 0,\n KEY_A,\n KEY_B,\n KEY_C,\n KEY_D,\n KEY_E,\n KEY_F,\n KEY_G,\n KEY_H,\n KEY_I,\n KEY_J,\n KEY_K,\n KEY_L,\n KEY_M,\n KEY_N,\n KEY_O,\n KEY_P,\n KEY_Q,\n KEY_R,\n KEY_S,\n KEY_T,\n KEY_U,\n KEY_V,\n KEY_W,\n KEY_X,\n KEY_Y,\n KEY_Z,\n KEY_1,\n KEY_2,\n KEY_3,\n KEY_4,\n KEY_5,\n KEY_6,\n KEY_7,\n KEY_8,\n KEY_9,\n KEY_RETURN,\n KEY_ESCAPE,\n KEY_BACKSPACE,\n KEY_TAB,\n KEY_SPACE,\n KEY_MINUS,\n KEY_EQUALS,\n KEY_LEFT_BRACKET,\n KEY_RIGHT_BRACKET,\n KEY_BACKSLASH,\n KEY_SEMICOLON,\n KEY_APOSTROPHE,\n KEY_GRAVE,\n KEY_COMMA,\n KEY_PERIOD,\n KEY_SLASH,\n KEY_CAPS_LOCK,\n KEY_F1,\n KEY_F2,\n KEY_F3,\n KEY_F4,\n KEY_F5,\n KEY_F6,\n KEY_F7,\n KEY_F8,\n KEY_F9,\n KEY_F10,\n KEY_F11,\n KEY_F12,\n KEY_PRINT_SCREEN,\n KEY_SCROLL_LOCK,\n KEY_PAUSE,\n KEY_INSERT,\n KEY_HOME,\n KEY_PAGE_UP,\n KEY_DELETE,\n KEY_END,\n KEY_PAGE_DOWN,\n KEY_RIGHT,\n KEY_LEFT,\n KEY_DOWN,\n KEY_UP,\n KEY_NUMLOCK_CLEAR,\n KEY_KP_DIVIDE,\n KEY_KP_MULTIPLY,\n KEY_KP_MINUS,\n KEY_KP_PLUS,\n KEY_KP_ENTER,\n KEY_KP_1,\n KEY_KP_2,\n KEY_KP_3,\n KEY_KP_4,\n KEY_KP_5,\n KEY_KP_6,\n KEY_KP_7,\n KEY_KP_8,\n KEY_KP_9,\n KEY_KP_0,\n KEY_KP_PERIOD,\n KEY_NON_US_BACKSLASH,\n KEY_LEFT_CTRL,\n KEY_LEFT_SHIFT,\n KEY_LEFT_ALT,\n KEY_LEFT_SUPER,\n KEY_RIGHT_CTRL,\n KEY_RIGHT_SHIFT,\n KEY_RIGHT_ALT,\n KEY_RIGHT_SUPER\n };\n\n enum class ModFlag\n {\n MOD_NONE = 0,\n MOD_LEFT_SHIFT = 1 << 0,\n MOD_RIGHT_SHIFT = 1 << 1,\n MOD_LEFT_CTRL = 1 << 2,\n MOD_RIGHT_CTRL = 1 << 3,\n MOD_LEFT_ALT = 1 << 4,\n MOD_RIGHT_ALT = 1 << 5,\n MOD_LEFT_SUPER = 1 << 6,\n MOD_RIGHT_SUPER = 1 << 7,\n MOD_NUM = 1 << 8,\n MOD_CAPS = 1 << 9,\n };\n\n using underlying = std::underlying_type::type;\n\n static ModFlag operator|(const ModFlag& left, const ModFlag& right)\n {\n return static_cast(static_cast(left) | static_cast(right));\n }\n\n static ModFlag operator&(const ModFlag& left, const ModFlag& right)\n {\n return static_cast(static_cast(left) & static_cast(right));\n }\n\n\n static std::map modMap {\n {KMOD_NONE, ModFlag::MOD_NONE},\n {KMOD_LSHIFT, ModFlag::MOD_LEFT_SHIFT},\n {KMOD_RSHIFT, ModFlag::MOD_RIGHT_SHIFT},\n {KMOD_LCTRL, ModFlag::MOD_LEFT_CTRL},\n {KMOD_RCTRL, ModFlag::MOD_RIGHT_CTRL},\n {KMOD_LALT, ModFlag::MOD_LEFT_ALT},\n {KMOD_RALT, ModFlag::MOD_RIGHT_ALT},\n {KMOD_LGUI, ModFlag::MOD_LEFT_SUPER},\n {KMOD_RGUI, ModFlag::MOD_RIGHT_SUPER},\n {KMOD_NUM, ModFlag::MOD_NUM},\n {KMOD_CAPS, ModFlag::MOD_CAPS}};\n\n\n static std::map keyMap {\n {SDL_SCANCODE_A, KeyCode::KEY_A},\n {SDL_SCANCODE_B, KeyCode::KEY_B},\n {SDL_SCANCODE_C, KeyCode::KEY_C},\n {SDL_SCANCODE_D, KeyCode::KEY_D},\n {SDL_SCANCODE_E, KeyCode::KEY_E},\n {SDL_SCANCODE_F, KeyCode::KEY_F},\n {SDL_SCANCODE_G, KeyCode::KEY_G},\n {SDL_SCANCODE_H, KeyCode::KEY_H},\n {SDL_SCANCODE_I, KeyCode::KEY_I},\n {SDL_SCANCODE_J, KeyCode::KEY_J},\n {SDL_SCANCODE_K, KeyCode::KEY_K},\n {SDL_SCANCODE_L, KeyCode::KEY_L},\n {SDL_SCANCODE_M, KeyCode::KEY_M},\n {SDL_SCANCODE_N, KeyCode::KEY_N},\n {SDL_SCANCODE_O, KeyCode::KEY_O},\n {SDL_SCANCODE_P, KeyCode::KEY_P},\n {SDL_SCANCODE_Q, KeyCode::KEY_Q},\n {SDL_SCANCODE_R, KeyCode::KEY_R},\n {SDL_SCANCODE_S, KeyCode::KEY_S},\n {SDL_SCANCODE_T, KeyCode::KEY_T},\n {SDL_SCANCODE_U, KeyCode::KEY_U},\n {SDL_SCANCODE_V, KeyCode::KEY_V},\n {SDL_SCANCODE_W, KeyCode::KEY_W},\n {SDL_SCANCODE_X, KeyCode::KEY_X},\n {SDL_SCANCODE_Y, KeyCode::KEY_Y},\n {SDL_SCANCODE_Z, KeyCode::KEY_Z},\n {SDL_SCANCODE_1, KeyCode::KEY_1},\n {SDL_SCANCODE_2, KeyCode::KEY_2},\n {SDL_SCANCODE_3, KeyCode::KEY_3},\n {SDL_SCANCODE_4, KeyCode::KEY_4},\n {SDL_SCANCODE_5, KeyCode::KEY_5},\n {SDL_SCANCODE_6, KeyCode::KEY_6},\n {SDL_SCANCODE_7, KeyCode::KEY_7},\n {SDL_SCANCODE_8, KeyCode::KEY_7},\n {SDL_SCANCODE_9, KeyCode::KEY_8},\n {SDL_SCANCODE_0, KeyCode::KEY_9},\n {SDL_SCANCODE_RETURN, KeyCode::KEY_RETURN},\n {SDL_SCANCODE_ESCAPE, KeyCode::KEY_ESCAPE},\n {SDL_SCANCODE_BACKSPACE, KeyCode::KEY_BACKSPACE},\n {SDL_SCANCODE_TAB, KeyCode::KEY_TAB},\n {SDL_SCANCODE_SPACE, KeyCode::KEY_SPACE},\n {SDL_SCANCODE_MINUS, KeyCode::KEY_MINUS},\n {SDL_SCANCODE_EQUALS, KeyCode::KEY_EQUALS},\n {SDL_SCANCODE_LEFTBRACKET, KeyCode::KEY_LEFT_BRACKET},\n {SDL_SCANCODE_RIGHTBRACKET, KeyCode::KEY_RIGHT_BRACKET},\n {SDL_SCANCODE_BACKSLASH, KeyCode::KEY_BACKSLASH},\n {SDL_SCANCODE_SEMICOLON, KeyCode::KEY_SEMICOLON},\n {SDL_SCANCODE_APOSTROPHE, KeyCode::KEY_APOSTROPHE},\n {SDL_SCANCODE_GRAVE, KeyCode::KEY_GRAVE},\n {SDL_SCANCODE_COMMA, KeyCode::KEY_COMMA},\n {SDL_SCANCODE_PERIOD, KeyCode::KEY_PERIOD},\n {SDL_SCANCODE_SLASH, KeyCode::KEY_SLASH},\n {SDL_SCANCODE_CAPSLOCK, KeyCode::KEY_CAPS_LOCK},\n {SDL_SCANCODE_F1, KeyCode::KEY_F1},\n {SDL_SCANCODE_F2, KeyCode::KEY_F2},\n {SDL_SCANCODE_F3, KeyCode::KEY_F3},\n {SDL_SCANCODE_F4, KeyCode::KEY_F4},\n {SDL_SCANCODE_F5, KeyCode::KEY_F5},\n {SDL_SCANCODE_F6, KeyCode::KEY_F6},\n {SDL_SCANCODE_F7, KeyCode::KEY_F7},\n {SDL_SCANCODE_F8, KeyCode::KEY_F8},\n {SDL_SCANCODE_F9, KeyCode::KEY_F9},\n {SDL_SCANCODE_F10, KeyCode::KEY_F10},\n {SDL_SCANCODE_F11, KeyCode::KEY_F11},\n {SDL_SCANCODE_F12, KeyCode::KEY_F12},\n {SDL_SCANCODE_PRINTSCREEN, KeyCode::KEY_PRINT_SCREEN},\n {SDL_SCANCODE_SCROLLLOCK, KeyCode::KEY_SCROLL_LOCK},\n {SDL_SCANCODE_PAUSE, KeyCode::KEY_PAUSE},\n {SDL_SCANCODE_INSERT, KeyCode::KEY_INSERT},\n {SDL_SCANCODE_HOME, KeyCode::KEY_HOME},\n {SDL_SCANCODE_PAGEUP, KeyCode::KEY_PAGE_UP},\n {SDL_SCANCODE_DELETE, KeyCode::KEY_DELETE},\n {SDL_SCANCODE_END, KeyCode::KEY_END},\n {SDL_SCANCODE_PAGEDOWN, KeyCode::KEY_PAGE_DOWN},\n {SDL_SCANCODE_RIGHT, KeyCode::KEY_RIGHT},\n {SDL_SCANCODE_LEFT, KeyCode::KEY_LEFT},\n {SDL_SCANCODE_DOWN, KeyCode::KEY_DOWN},\n {SDL_SCANCODE_UP, KeyCode::KEY_UP},\n {SDL_SCANCODE_NUMLOCKCLEAR, KeyCode::KEY_NUMLOCK_CLEAR},\n {SDL_SCANCODE_KP_DIVIDE, KeyCode::KEY_KP_DIVIDE},\n {SDL_SCANCODE_KP_MULTIPLY, KeyCode::KEY_KP_MULTIPLY},\n {SDL_SCANCODE_KP_MINUS, KeyCode::KEY_KP_MINUS},\n {SDL_SCANCODE_KP_PLUS, KeyCode::KEY_KP_PLUS},\n {SDL_SCANCODE_KP_ENTER, KeyCode::KEY_KP_ENTER},\n {SDL_SCANCODE_KP_1, KeyCode::KEY_KP_1},\n {SDL_SCANCODE_KP_2, KeyCode::KEY_KP_2},\n {SDL_SCANCODE_KP_3, KeyCode::KEY_KP_3},\n {SDL_SCANCODE_KP_4, KeyCode::KEY_KP_4},\n {SDL_SCANCODE_KP_5, KeyCode::KEY_KP_5},\n {SDL_SCANCODE_KP_6, KeyCode::KEY_KP_6},\n {SDL_SCANCODE_KP_7, KeyCode::KEY_KP_7},\n {SDL_SCANCODE_KP_8, KeyCode::KEY_KP_8},\n {SDL_SCANCODE_KP_9, KeyCode::KEY_KP_9},\n {SDL_SCANCODE_KP_0, KeyCode::KEY_KP_0},\n {SDL_SCANCODE_KP_PERIOD, KeyCode::KEY_KP_PERIOD},\n {SDL_SCANCODE_NONUSBACKSLASH, KeyCode::KEY_NON_US_BACKSLASH},\n {SDL_SCANCODE_LCTRL, KeyCode::KEY_LEFT_CTRL},\n {SDL_SCANCODE_LSHIFT, KeyCode::KEY_LEFT_SHIFT},\n {SDL_SCANCODE_LALT, KeyCode::KEY_LEFT_ALT},\n {SDL_SCANCODE_LGUI, KeyCode::KEY_LEFT_SUPER},\n {SDL_SCANCODE_RCTRL, KeyCode::KEY_RIGHT_CTRL},\n {SDL_SCANCODE_RSHIFT, KeyCode::KEY_RIGHT_SHIFT},\n {SDL_SCANCODE_RALT, KeyCode::KEY_RIGHT_ALT},\n {SDL_SCANCODE_RGUI, KeyCode::KEY_RIGHT_SUPER}\n };\n\n\n std::vector processModifiers(int value)\n {\n std::vector keys;\n for (auto const& key : modMap) {\n if (value & key.first) {\n keys.push_back(key.second);\n }\n }\n return keys;\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2011 Arduino. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n See the GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \n#include \n#include \"UARTClass.h\"\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nUARTClass::UARTClass( Uart *pUart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer *pRx_buffer, RingBuffer *pTx_buffer )\n{\n _rx_buffer = pRx_buffer ;\n _tx_buffer = pTx_buffer;\n\n _pUart=pUart ;\n _dwIrq=dwIrq ;\n _dwId=dwId ;\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nvoid UARTClass::begin( const uint32_t dwBaudRate )\n{\n\tbegin( dwBaudRate, UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL );\n}\n\nvoid UARTClass::begin( const uint32_t dwBaudRate, const uint32_t config )\n{\n \/\/ Configure PMC\n pmc_enable_periph_clk( _dwId ) ;\n\n \/\/ Disable PDC channel\n _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;\n\n \/\/ Reset and disable receiver and transmitter\n _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;\n\n \/\/ Configure mode\n _pUart->UART_MR = config ;\n\n \/\/ Configure baudrate (asynchronous, no oversampling)\n _pUart->UART_BRGR = (SystemCoreClock \/ dwBaudRate) >> 4 ;\n\n \/\/ Configure interrupts\n _pUart->UART_IDR = 0xFFFFFFFF;\n _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;\n\n \/\/ Enable UART interrupt in NVIC\n NVIC_EnableIRQ(_dwIrq);\n\n \/\/make sure both ring buffers are initialized back to empty.\n _rx_buffer->_iHead = _rx_buffer->_iTail = 0;\n _tx_buffer->_iHead = _tx_buffer->_iTail = 0;\n\n \/\/ Enable receiver and transmitter\n _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;\n}\n\nvoid UARTClass::end( void )\n{\n \/\/ clear any received data\n _rx_buffer->_iHead = _rx_buffer->_iTail ;\n\n while (_tx_buffer->_iHead != _tx_buffer->_iTail); \/\/wait for transmit data to be sent\n\n \/\/ Disable UART interrupt in NVIC\n NVIC_DisableIRQ( _dwIrq ) ;\n\n \/\/ Wait for any outstanding data to be sent\n flush();\n\n pmc_disable_periph_clk( _dwId ) ;\n}\n\nvoid UARTClass::setInterruptPriority(uint32_t priority)\n{\n\tNVIC_SetPriority(_dwIrq, priority & 0x0F);\n}\n\nuint32_t UARTClass::getInterruptPriority()\n{\n\treturn NVIC_GetPriority(_dwIrq);\n}\n\nint UARTClass::available( void )\n{\n return (uint32_t)(SERIAL_BUFFER_SIZE + _rx_buffer->_iHead - _rx_buffer->_iTail) % SERIAL_BUFFER_SIZE ;\n}\n\nint UARTClass::availableForWrite(void)\n{\n int head = _tx_buffer->_iHead;\n int tail = _tx_buffer->_iTail;\n if (head >= tail) return SERIAL_BUFFER_SIZE - 1 - head + tail;\n return tail - head - 1;\n}\n\nint UARTClass::peek( void )\n{\n if ( _rx_buffer->_iHead == _rx_buffer->_iTail )\n return -1 ;\n\n return _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ;\n}\n\nint UARTClass::read( void )\n{\n \/\/ if the head isn't ahead of the tail, we don't have any characters\n if ( _rx_buffer->_iHead == _rx_buffer->_iTail )\n return -1 ;\n\n uint8_t uc = _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ;\n _rx_buffer->_iTail = (unsigned int)(_rx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE ;\n return uc ;\n}\n\nvoid UARTClass::flush( void )\n{\n \/\/ Wait for transmission to complete\n while ((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY)\n ;\n}\n\nsize_t UARTClass::write( const uint8_t uc_data )\n{\n if (((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) | (_tx_buffer->_iTail != _tx_buffer->_iHead)) \/\/is the hardware currently busy?\n {\n\t \/\/if busy we buffer\n\t unsigned int l = (_tx_buffer->_iHead + 1) % SERIAL_BUFFER_SIZE;\n\t while (_tx_buffer->_iTail == l); \/\/spin locks if we're about to overwrite the buffer. This continues once the data is sent\n\n\t _tx_buffer->_aucBuffer[_tx_buffer->_iHead] = uc_data;\n\t _tx_buffer->_iHead = l;\n\t _pUart->UART_IER = UART_IER_TXRDY; \/\/make sure TX interrupt is enabled\n }\n else \n {\n \/\/ Send character\n _pUart->UART_THR = uc_data ;\n }\n return 1;\n}\n\nvoid UARTClass::IrqHandler( void )\n{\n uint32_t status = _pUart->UART_SR;\n\n \/\/ Did we receive data ?\n if ((status & UART_SR_RXRDY) == UART_SR_RXRDY)\n _rx_buffer->store_char(_pUart->UART_RHR);\n\n \/\/Do we need to keep sending data?\n if ((status & UART_SR_TXRDY) == UART_SR_TXRDY) \n {\n\t if (_tx_buffer->_iTail != _tx_buffer->_iHead) { \/\/just in case\n\t\t_pUart->UART_THR = _tx_buffer->_aucBuffer[_tx_buffer->_iTail];\n\t\t_tx_buffer->_iTail = (unsigned int)(_tx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE;\n\t }\n\t else\n\t {\n\t\t_pUart->UART_IDR = UART_IDR_TXRDY; \/\/mask off transmit interrupt so we don't get it anymore\n\t }\n }\n\n \/\/ Acknowledge errors\n if ((status & UART_SR_OVRE) == UART_SR_OVRE ||\n\t\t (status & UART_SR_FRAME) == UART_SR_FRAME)\n {\n\t\/\/ TODO: error reporting outside ISR\n _pUart->UART_CR |= UART_CR_RSTSTA;\n }\n}\n\nFixed flush so that it actually is sure to flush all outstanding data.\/*\n Copyright (c) 2011 Arduino. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n See the GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \n#include \n#include \"UARTClass.h\"\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nUARTClass::UARTClass( Uart *pUart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer *pRx_buffer, RingBuffer *pTx_buffer )\n{\n _rx_buffer = pRx_buffer ;\n _tx_buffer = pTx_buffer;\n\n _pUart=pUart ;\n _dwIrq=dwIrq ;\n _dwId=dwId ;\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nvoid UARTClass::begin( const uint32_t dwBaudRate )\n{\n\tbegin( dwBaudRate, UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL );\n}\n\nvoid UARTClass::begin( const uint32_t dwBaudRate, const uint32_t config )\n{\n \/\/ Configure PMC\n pmc_enable_periph_clk( _dwId ) ;\n\n \/\/ Disable PDC channel\n _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;\n\n \/\/ Reset and disable receiver and transmitter\n _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;\n\n \/\/ Configure mode\n _pUart->UART_MR = config ;\n\n \/\/ Configure baudrate (asynchronous, no oversampling)\n _pUart->UART_BRGR = (SystemCoreClock \/ dwBaudRate) >> 4 ;\n\n \/\/ Configure interrupts\n _pUart->UART_IDR = 0xFFFFFFFF;\n _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;\n\n \/\/ Enable UART interrupt in NVIC\n NVIC_EnableIRQ(_dwIrq);\n\n \/\/make sure both ring buffers are initialized back to empty.\n _rx_buffer->_iHead = _rx_buffer->_iTail = 0;\n _tx_buffer->_iHead = _tx_buffer->_iTail = 0;\n\n \/\/ Enable receiver and transmitter\n _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;\n}\n\nvoid UARTClass::end( void )\n{\n \/\/ clear any received data\n _rx_buffer->_iHead = _rx_buffer->_iTail ;\n\n \/\/ Wait for any outstanding data to be sent\n flush();\n\n \/\/ Disable UART interrupt in NVIC\n NVIC_DisableIRQ( _dwIrq ) ;\n\n pmc_disable_periph_clk( _dwId ) ;\n}\n\nvoid UARTClass::setInterruptPriority(uint32_t priority)\n{\n\tNVIC_SetPriority(_dwIrq, priority & 0x0F);\n}\n\nuint32_t UARTClass::getInterruptPriority()\n{\n\treturn NVIC_GetPriority(_dwIrq);\n}\n\nint UARTClass::available( void )\n{\n return (uint32_t)(SERIAL_BUFFER_SIZE + _rx_buffer->_iHead - _rx_buffer->_iTail) % SERIAL_BUFFER_SIZE ;\n}\n\nint UARTClass::availableForWrite(void)\n{\n int head = _tx_buffer->_iHead;\n int tail = _tx_buffer->_iTail;\n if (head >= tail) return SERIAL_BUFFER_SIZE - 1 - head + tail;\n return tail - head - 1;\n}\n\nint UARTClass::peek( void )\n{\n if ( _rx_buffer->_iHead == _rx_buffer->_iTail )\n return -1 ;\n\n return _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ;\n}\n\nint UARTClass::read( void )\n{\n \/\/ if the head isn't ahead of the tail, we don't have any characters\n if ( _rx_buffer->_iHead == _rx_buffer->_iTail )\n return -1 ;\n\n uint8_t uc = _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ;\n _rx_buffer->_iTail = (unsigned int)(_rx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE ;\n return uc ;\n}\n\nvoid UARTClass::flush( void )\n{\n while (_tx_buffer->_iHead != _tx_buffer->_iTail); \/\/wait for transmit data to be sent\n \/\/ Wait for transmission to complete\n while ((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY)\n ;\n}\n\nsize_t UARTClass::write( const uint8_t uc_data )\n{\n if (((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) | (_tx_buffer->_iTail != _tx_buffer->_iHead)) \/\/is the hardware currently busy?\n {\n\t \/\/if busy we buffer\n\t unsigned int l = (_tx_buffer->_iHead + 1) % SERIAL_BUFFER_SIZE;\n\t while (_tx_buffer->_iTail == l); \/\/spin locks if we're about to overwrite the buffer. This continues once the data is sent\n\n\t _tx_buffer->_aucBuffer[_tx_buffer->_iHead] = uc_data;\n\t _tx_buffer->_iHead = l;\n\t _pUart->UART_IER = UART_IER_TXRDY; \/\/make sure TX interrupt is enabled\n }\n else \n {\n \/\/ Send character\n _pUart->UART_THR = uc_data ;\n }\n return 1;\n}\n\nvoid UARTClass::IrqHandler( void )\n{\n uint32_t status = _pUart->UART_SR;\n\n \/\/ Did we receive data ?\n if ((status & UART_SR_RXRDY) == UART_SR_RXRDY)\n _rx_buffer->store_char(_pUart->UART_RHR);\n\n \/\/Do we need to keep sending data?\n if ((status & UART_SR_TXRDY) == UART_SR_TXRDY) \n {\n\t if (_tx_buffer->_iTail != _tx_buffer->_iHead) { \/\/just in case\n\t\t_pUart->UART_THR = _tx_buffer->_aucBuffer[_tx_buffer->_iTail];\n\t\t_tx_buffer->_iTail = (unsigned int)(_tx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE;\n\t }\n\t else\n\t {\n\t\t_pUart->UART_IDR = UART_IDR_TXRDY; \/\/mask off transmit interrupt so we don't get it anymore\n\t }\n }\n\n \/\/ Acknowledge errors\n if ((status & UART_SR_OVRE) == UART_SR_OVRE ||\n\t\t (status & UART_SR_FRAME) == UART_SR_FRAME)\n {\n\t\/\/ TODO: error reporting outside ISR\n _pUart->UART_CR |= UART_CR_RSTSTA;\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"line_printer.h\"\n\n#include \n#include \n#ifdef _WIN32\n#include \n#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING\n#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4\n#endif\n#else\n#include \n#include \n#include \n#include \n#endif\n\n#include \"util.h\"\n\nLinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {\n#ifndef _WIN32\n const char* term = getenv(\"TERM\");\n smart_terminal_ = isatty(1) && term && string(term) != \"dumb\";\n#else\n \/\/ Disable output buffer. It'd be nice to use line buffering but\n \/\/ MSDN says: \"For some systems, [_IOLBF] provides line\n \/\/ buffering. However, for Win32, the behavior is the same as _IOFBF\n \/\/ - Full Buffering.\"\n setvbuf(stdout, NULL, _IONBF, 0);\n console_ = GetStdHandle(STD_OUTPUT_HANDLE);\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi);\n#endif\n supports_color_ = smart_terminal_;\n if (!supports_color_) {\n const char* clicolor_force = getenv(\"CLICOLOR_FORCE\");\n supports_color_ = clicolor_force && string(clicolor_force) != \"0\";\n }\n#ifdef _WIN32\n \/\/ Try enabling ANSI escape sequence support on Windows 10 terminals.\n if (supports_color_) {\n DWORD mode;\n if (GetConsoleMode(console_, &mode)) {\n SetConsoleMode(console_, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);\n }\n }\n#endif\n}\n\nvoid LinePrinter::Print(string to_print, LineType type) {\n if (console_locked_) {\n line_buffer_ = to_print;\n line_type_ = type;\n return;\n }\n\n if (smart_terminal_) {\n printf(\"\\r\"); \/\/ Print over previous line, if any.\n \/\/ On Windows, calling a C library function writing to stdout also handles\n \/\/ pausing the executable when the \"Pause\" key or Ctrl-S is pressed.\n }\n\n if (smart_terminal_ && type == ELIDE) {\n#ifdef _WIN32\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n GetConsoleScreenBufferInfo(console_, &csbi);\n\n to_print = ElideMiddle(to_print, static_cast(csbi.dwSize.X));\n \/\/ We don't want to have the cursor spamming back and forth, so instead of\n \/\/ printf use WriteConsoleOutput which updates the contents of the buffer,\n \/\/ but doesn't move the cursor position.\n COORD buf_size = { csbi.dwSize.X, 1 };\n COORD zero_zero = { 0, 0 };\n SMALL_RECT target = {\n csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y,\n static_cast(csbi.dwCursorPosition.X + csbi.dwSize.X - 1),\n csbi.dwCursorPosition.Y\n };\n vector char_data(csbi.dwSize.X);\n for (size_t i = 0; i < static_cast(csbi.dwSize.X); ++i) {\n char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' ';\n char_data[i].Attributes = csbi.wAttributes;\n }\n WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target);\n#else\n \/\/ Limit output to width of the terminal if provided so we don't cause\n \/\/ line-wrapping.\n winsize size;\n if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) && size.ws_col) {\n to_print = ElideMiddle(to_print, size.ws_col);\n }\n printf(\"%s\", to_print.c_str());\n printf(\"\\x1B[K\"); \/\/ Clear to end of line.\n fflush(stdout);\n#endif\n\n have_blank_line_ = false;\n } else {\n printf(\"%s\\n\", to_print.c_str());\n }\n}\n\nvoid LinePrinter::PrintOrBuffer(const char* data, size_t size) {\n if (console_locked_) {\n output_buffer_.append(data, size);\n } else {\n \/\/ Avoid printf and C strings, since the actual output might contain null\n \/\/ bytes like UTF-16 does (yuck).\n fwrite(data, 1, size, stdout);\n }\n}\n\nvoid LinePrinter::PrintOnNewLine(const string& to_print) {\n if (console_locked_ && !line_buffer_.empty()) {\n output_buffer_.append(line_buffer_);\n output_buffer_.append(1, '\\n');\n line_buffer_.clear();\n }\n if (!have_blank_line_) {\n PrintOrBuffer(\"\\n\", 1);\n }\n if (!to_print.empty()) {\n PrintOrBuffer(&to_print[0], to_print.size());\n }\n have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\\n';\n}\n\nvoid LinePrinter::SetConsoleLocked(bool locked) {\n if (locked == console_locked_)\n return;\n\n if (locked)\n PrintOnNewLine(\"\");\n\n console_locked_ = locked;\n\n if (!locked) {\n PrintOnNewLine(output_buffer_);\n if (!line_buffer_.empty()) {\n Print(line_buffer_, line_type_);\n }\n output_buffer_.clear();\n line_buffer_.clear();\n }\n}\nUnset suports_color_ if SetConsoleMode fails on WIN32\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"line_printer.h\"\n\n#include \n#include \n#ifdef _WIN32\n#include \n#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING\n#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4\n#endif\n#else\n#include \n#include \n#include \n#include \n#endif\n\n#include \"util.h\"\n\nLinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {\n#ifndef _WIN32\n const char* term = getenv(\"TERM\");\n smart_terminal_ = isatty(1) && term && string(term) != \"dumb\";\n#else\n \/\/ Disable output buffer. It'd be nice to use line buffering but\n \/\/ MSDN says: \"For some systems, [_IOLBF] provides line\n \/\/ buffering. However, for Win32, the behavior is the same as _IOFBF\n \/\/ - Full Buffering.\"\n setvbuf(stdout, NULL, _IONBF, 0);\n console_ = GetStdHandle(STD_OUTPUT_HANDLE);\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi);\n#endif\n supports_color_ = smart_terminal_;\n if (!supports_color_) {\n const char* clicolor_force = getenv(\"CLICOLOR_FORCE\");\n supports_color_ = clicolor_force && string(clicolor_force) != \"0\";\n }\n#ifdef _WIN32\n \/\/ Try enabling ANSI escape sequence support on Windows 10 terminals.\n if (supports_color_) {\n DWORD mode;\n if (GetConsoleMode(console_, &mode)) {\n if (!SetConsoleMode(console_, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {\n supports_color_ = false;\n }\n }\n }\n#endif\n}\n\nvoid LinePrinter::Print(string to_print, LineType type) {\n if (console_locked_) {\n line_buffer_ = to_print;\n line_type_ = type;\n return;\n }\n\n if (smart_terminal_) {\n printf(\"\\r\"); \/\/ Print over previous line, if any.\n \/\/ On Windows, calling a C library function writing to stdout also handles\n \/\/ pausing the executable when the \"Pause\" key or Ctrl-S is pressed.\n }\n\n if (smart_terminal_ && type == ELIDE) {\n#ifdef _WIN32\n CONSOLE_SCREEN_BUFFER_INFO csbi;\n GetConsoleScreenBufferInfo(console_, &csbi);\n\n to_print = ElideMiddle(to_print, static_cast(csbi.dwSize.X));\n \/\/ We don't want to have the cursor spamming back and forth, so instead of\n \/\/ printf use WriteConsoleOutput which updates the contents of the buffer,\n \/\/ but doesn't move the cursor position.\n COORD buf_size = { csbi.dwSize.X, 1 };\n COORD zero_zero = { 0, 0 };\n SMALL_RECT target = {\n csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y,\n static_cast(csbi.dwCursorPosition.X + csbi.dwSize.X - 1),\n csbi.dwCursorPosition.Y\n };\n vector char_data(csbi.dwSize.X);\n for (size_t i = 0; i < static_cast(csbi.dwSize.X); ++i) {\n char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' ';\n char_data[i].Attributes = csbi.wAttributes;\n }\n WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target);\n#else\n \/\/ Limit output to width of the terminal if provided so we don't cause\n \/\/ line-wrapping.\n winsize size;\n if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) && size.ws_col) {\n to_print = ElideMiddle(to_print, size.ws_col);\n }\n printf(\"%s\", to_print.c_str());\n printf(\"\\x1B[K\"); \/\/ Clear to end of line.\n fflush(stdout);\n#endif\n\n have_blank_line_ = false;\n } else {\n printf(\"%s\\n\", to_print.c_str());\n }\n}\n\nvoid LinePrinter::PrintOrBuffer(const char* data, size_t size) {\n if (console_locked_) {\n output_buffer_.append(data, size);\n } else {\n \/\/ Avoid printf and C strings, since the actual output might contain null\n \/\/ bytes like UTF-16 does (yuck).\n fwrite(data, 1, size, stdout);\n }\n}\n\nvoid LinePrinter::PrintOnNewLine(const string& to_print) {\n if (console_locked_ && !line_buffer_.empty()) {\n output_buffer_.append(line_buffer_);\n output_buffer_.append(1, '\\n');\n line_buffer_.clear();\n }\n if (!have_blank_line_) {\n PrintOrBuffer(\"\\n\", 1);\n }\n if (!to_print.empty()) {\n PrintOrBuffer(&to_print[0], to_print.size());\n }\n have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\\n';\n}\n\nvoid LinePrinter::SetConsoleLocked(bool locked) {\n if (locked == console_locked_)\n return;\n\n if (locked)\n PrintOnNewLine(\"\");\n\n console_locked_ = locked;\n\n if (!locked) {\n PrintOnNewLine(output_buffer_);\n if (!line_buffer_.empty()) {\n Print(line_buffer_, line_type_);\n }\n output_buffer_.clear();\n line_buffer_.clear();\n }\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n\r\nconst int DRIVE_TELEGRAM_SIZE = 4;\r\n\r\n\/\/declarations\r\nvoid driveTelegramCallback(const std_msgs::UInt8MultiArray::ConstPtr &msg);\r\nvoid setDriveTelegram(unsigned char drive_telegram[], int velocity);\r\n\r\n\/\/Main function\r\nint main(int argc, char *argv[])\r\n{\r\n ros::init(argc, argv, \"cp1616_sinamics_tutorial_node\");\r\n ros::NodeHandle nh;\r\n\r\n \/\/Subscribe to drive topic defined in yaml config file\r\n ros::Subscriber sub_drive = nh.subscribe(\"\/drive_1_input_topic\", 1,\r\n\t\t\t\t\t &driveTelegramCallback);\r\n\r\n \/\/Create publihser for drive topic defined in yaml config file\r\n ros::Publisher pub_drive = nh.advertise\r\n (\"\/drive_1_output_topic\", 1);\r\n\r\n \/\/Telegram 111 \r\n unsigned char drive_telegram_1[DRIVE_TELEGRAM_SIZE];\r\n\r\n \/\/std_msgs::MultiArray variables\r\n std_msgs::MultiArrayDimension msg_dim;\r\n std_msgs::UInt8MultiArray msg;\r\n\r\n \/\/Wait until communication starts properly\r\n ros::Duration(10).sleep();\r\n \r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n\r\n msg.data.clear();\r\n\r\n drive_telegram_1[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram_1[1] = 0b00000000; \/\/STW1 low\r\n drive_telegram_1[2] = 0b00000000; \/\/NSOLL_A high\r\n drive_telegram_1[3] = 0b00000000; \/\/NSOLL_A low\r\n \r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n pub_drive.publish(msg);\r\n \r\n \/\/Wait 2 seconds \r\n ros::Duration(2).sleep();\r\n \r\n \/\/-------------------------------------------\r\n \/\/Send initialization DRIVE telegram\r\n \/\/ - set all necessary bytes except ON\/OFF1 to true\r\n \/\/-------------------------------------------\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n\r\n msg.data.clear();\r\n\r\n drive_telegram_1[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram_1[1] = 0b11111110; \/\/STW1 low\r\n drive_telegram_1[2] = 0b00000000; \/\/NSOLL_A high\r\n drive_telegram_1[3] = 0b00000000; \/\/NSOLL_A low\r\n \r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n pub_drive.publish(msg);\r\n \r\n \/\/Wait 2 seconds before entering loop\r\n ros::Duration(2).sleep();\r\n \r\n \/\/-------------------------------------------\r\n \/\/ Main loop\r\n \/\/-------------------------------------------\r\n while(ros::ok())\r\n {\r\n \r\n ROS_INFO(\"Goal speed: 500\");\r\n \/\/message header\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n \r\n setDriveTelegram(drive_telegram_1, 5000);\r\n \r\n \/\/copy telegram data\r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n \/\/publish\r\n pub_drive.publish(msg);\r\n \r\n \/\/wait for 5 seconds\r\n ros::Duration(5).sleep();\r\n ros::spinOnce();\r\n \r\n \/\/======================================================\r\n \r\n ROS_INFO(\"Goal speed: 1000\");\r\n \/\/message header\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n \r\n setDriveTelegram(drive_telegram_1, 10000);\r\n \r\n \/\/copy telegram data\r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n \r\n \/\/publish\r\n pub_drive.publish(msg);\r\n \r\n \/\/wait for 5 seconds\r\n ros::Duration(5).sleep();\r\n ros::spinOnce();\r\n } \r\n \r\n return (EXIT_SUCCESS);\r\n} \r\n \r\nvoid setDriveTelegram(unsigned char drive_telegram[], int velocity) \r\n{ \r\n \r\n \/\/Decompose velocity from int to 4*unsigned char\r\n unsigned char velocity_bytes[2]; \r\n \r\n velocity_bytes[0] = (velocity >> 8) & 0xFF;\r\n velocity_bytes[1] = velocity & 0xFF; \r\n \r\n \/\/Set telegram data\r\n drive_telegram[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram[1] = 0b11111111; \/\/STW1 low\r\n drive_telegram[2] = velocity_bytes[0]; \/\/NSOLL_A high \r\n drive_telegram[3] = velocity_bytes[1]; \/\/NSOLL_A low\r\n}\r\n\r\nvoid driveTelegramCallback(const std_msgs::UInt8MultiArray::ConstPtr &msg)\r\n{\r\n unsigned int received_byte_array[DRIVE_TELEGRAM_SIZE];\r\n\r\n for(unsigned int i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n received_byte_array[i] = msg->data[i];\r\n}\r\ntested with real hardware#include \r\n#include \r\n#include \r\n\r\nconst int DRIVE_TELEGRAM_SIZE = 4;\r\nconst int N_MAX = 1500;\r\n\r\n\/\/declarations\r\nvoid driveTelegramCallback(const std_msgs::UInt8MultiArray::ConstPtr &msg);\r\nvoid setDriveTelegram(unsigned char drive_telegram[], int velocity);\r\n\r\n\/\/Main function\r\nint main(int argc, char *argv[])\r\n{\r\n ros::init(argc, argv, \"cp1616_sinamics_tutorial_node\");\r\n ros::NodeHandle nh;\r\n\r\n \/\/Subscribe to drive topic defined in yaml config file\r\n ros::Subscriber sub_drive = nh.subscribe(\"\/drive_1_input_topic\", 1, &driveTelegramCallback);\r\n\r\n \/\/Create publihser for drive topic defined in yaml config file\r\n ros::Publisher pub_drive = nh.advertise(\"\/drive_1_output_topic\", 1);\r\n\r\n \/\/Telegram 111 \r\n unsigned char drive_telegram_1[DRIVE_TELEGRAM_SIZE];\r\n\r\n \/\/std_msgs::MultiArray variables\r\n std_msgs::MultiArrayDimension msg_dim;\r\n std_msgs::UInt8MultiArray msg;\r\n\r\n \/\/Wait until communication starts properly\r\n ros::Duration(10).sleep();\r\n \r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n\r\n msg.data.clear();\r\n\r\n drive_telegram_1[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram_1[1] = 0b00000000; \/\/STW1 low\r\n drive_telegram_1[2] = 0b00000000; \/\/NSOLL_A high\r\n drive_telegram_1[3] = 0b00000000; \/\/NSOLL_A low\r\n \r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n pub_drive.publish(msg);\r\n \r\n \/\/Wait for 2 seconds\r\n ros::Duration(2).sleep();\r\n \r\n \/\/-------------------------------------------\r\n \/\/Send initialization DRIVE telegram\r\n \/\/ - set ON\/OFF2 ON\/OFF\/3 to true\r\n \/\/-------------------------------------------\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n\r\n msg.data.clear();\r\n\r\n drive_telegram_1[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram_1[1] = 0b10000110; \/\/STW1 low\r\n drive_telegram_1[2] = 0b00000000; \/\/NSOLL_A high\r\n drive_telegram_1[3] = 0b00000000; \/\/NSOLL_A low\r\n \r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n pub_drive.publish(msg);\r\n \r\n \/\/Wait for 2 seconds\r\n ros::Duration(2).sleep();\r\n \r\n \/\/-------------------------------------------\r\n \/\/Send initialization DRIVE telegram\r\n \/\/ - set all necessary bytes except ON\/OFF1 to true\r\n \/\/-------------------------------------------\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n\r\n msg.data.clear();\r\n\r\n drive_telegram_1[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram_1[1] = 0b11111110; \/\/STW1 low\r\n drive_telegram_1[2] = 0b00000000; \/\/NSOLL_A high\r\n drive_telegram_1[3] = 0b00000000; \/\/NSOLL_A low\r\n \r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n pub_drive.publish(msg);\r\n \r\n \/\/Wait for 2 seconds\r\n ros::Duration(2).sleep();\r\n \r\n \/\/-------------------------------------------\r\n \/\/ Main loop\r\n \/\/-------------------------------------------\r\n while(ros::ok())\r\n {\r\n \r\n ROS_INFO(\"Goal speed: 500\");\r\n \/\/message header\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n \r\n setDriveTelegram(drive_telegram_1, 500);\r\n \r\n \/\/copy telegram data\r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n\r\n \/\/publish\r\n pub_drive.publish(msg);\r\n \r\n \/\/wait for 5 seconds\r\n ros::Duration(5).sleep();\r\n ros::spinOnce();\r\n \r\n \/\/======================================================\r\n \r\n ROS_INFO(\"Goal speed: 1000\");\r\n \/\/message header\r\n msg_dim.label = \"Drive_1_output\";\r\n msg_dim.size = DRIVE_TELEGRAM_SIZE;\r\n msg.layout.dim.clear();\r\n msg.layout.dim.push_back(msg_dim);\r\n \r\n setDriveTelegram(drive_telegram_1, 1000);\r\n \r\n \/\/copy telegram data\r\n msg.data.clear();\r\n for(size_t i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n msg.data.push_back(drive_telegram_1[i]);\r\n \r\n \/\/publish\r\n pub_drive.publish(msg);\r\n \r\n \/\/wait for 5 seconds\r\n ros::Duration(5).sleep();\r\n ros::spinOnce();\r\n } \r\n \r\n return (EXIT_SUCCESS);\r\n}\r\n \r\n \r\nvoid setDriveTelegram(unsigned char drive_telegram[], int velocity) \r\n{ \r\n \/\/Scale to 0x4000 = 100% ratio\r\n int velocity_rel = (velocity * 0x4000) \/ N_MAX; \r\n \r\n \/\/Decompose velocity from int to 4*unsigned char\r\n unsigned char velocity_bytes[2]; \r\n \r\n velocity_bytes[0] = (velocity_rel >> 8) & 0xFF;\r\n velocity_bytes[1] = velocity_rel & 0xFF; \r\n \r\n \/\/Set telegram data\r\n drive_telegram[0] = 0b00000100; \/\/STW1 high\r\n drive_telegram[1] = 0b11111111; \/\/STW1 low\r\n drive_telegram[2] = velocity_bytes[0]; \/\/NSOLL_A high \r\n drive_telegram[3] = velocity_bytes[1]; \/\/NSOLL_A low\r\n\r\n}\r\n\r\nvoid driveTelegramCallback(const std_msgs::UInt8MultiArray::ConstPtr &msg)\r\n{\r\n unsigned int received_byte_array[DRIVE_TELEGRAM_SIZE];\r\n\r\n for(unsigned int i = 0; i < DRIVE_TELEGRAM_SIZE; i++)\r\n received_byte_array[i] = msg->data[i];\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \r\n#define BOOST_TEST_MODULE DenseMIAAddSubtractTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include \r\n#else\r\n#include \r\n#endif\n\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\r\ntemplate\r\nvoid do_work(size_t dim1,size_t dim2){\r\n\r\n LibMIA::MIAINDEX i;\n LibMIA::MIAINDEX j;\n LibMIA::MIAINDEX k;\r\n LibMIA::MIAINDEX l;\r\n\/\/ LibMIA::MIAINDEX m;\r\n\/\/ LibMIA::MIAINDEX n;\r\n\/\/ LibMIA::MIAINDEX o;\r\n\/\/ LibMIA::MIAINDEX p;\n\n LibMIA::DenseMIA<_data_type,4> a(dim1,dim1,dim2,dim2);\r\n LibMIA::DenseMIA<_data_type,4> b(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> c(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> c2(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> b2(dim1,dim1,dim2,dim2);\r\n\r\n\r\n a.ones();\r\n b.ones();\r\n\r\n\r\n c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n c2.init(2);\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)+=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n b.init(3);\r\n c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)-=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIAAddSubtractTests )\n{\n\n\r\n\r\n do_work(8,10);\n do_work(8,10);\r\n do_work(8,10);\n do_work(8,10);\r\n\r\n\r\n\n\n}\nAdded a second set of dense add\/subtract unit tests#include \n#include \r\n#define BOOST_TEST_MODULE DenseMIAAddSubtractTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include \r\n#else\r\n#include \r\n#endif\n\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\r\ntemplate\r\nvoid do_work(size_t dim1,size_t dim2){\r\n\r\n LibMIA::MIAINDEX i;\n LibMIA::MIAINDEX j;\n LibMIA::MIAINDEX k;\r\n LibMIA::MIAINDEX l;\r\n\/\/ LibMIA::MIAINDEX m;\r\n\/\/ LibMIA::MIAINDEX n;\r\n\/\/ LibMIA::MIAINDEX o;\r\n\/\/ LibMIA::MIAINDEX p;\n\n LibMIA::DenseMIA<_data_type,4> a(dim1,dim1,dim2,dim2);\r\n LibMIA::DenseMIA<_data_type,4> b(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> c(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> c2(dim2,dim1,dim2,dim1);\r\n LibMIA::DenseMIA<_data_type,4> b2(dim1,dim1,dim2,dim2);\r\n\r\n\r\n a.ones();\r\n b.ones();\r\n\r\n\r\n c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n c2.init(2);\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)+=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Add 1 for \")+typeid(_data_type).name());\r\n\r\n b.init(3);\r\n c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)-=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Subtract 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n a.zeros();\r\n b.zeros();\r\n a.at(dim1-1,dim1-1,dim2-1,dim2-1)=1;\r\n b.at(dim2-1,dim1-1,dim2-1,dim1-1)=1;\r\n\r\n\r\n c(i,j,k,l)=b(i,j,k,l)+a(j,l,i,k);\r\n c2.zeros();\r\n c2.at(dim2-1,dim1-1,dim2-1,dim1-1)=2;\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Add 2 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)+=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Add 2 for \")+typeid(_data_type).name());\r\n\r\n a.at(dim1-1,dim1-1,dim2-1,dim2-1)=3;\r\n b.at(dim2-1,dim1-1,dim2-1,dim1-1)=5;\r\n c(i,j,k,l)=b(i,j,k,l)-a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(c==c2,std::string(\"Non-destructive Subtract 2 for \")+typeid(_data_type).name());\r\n\r\n\r\n b(i,j,k,l)-=a(j,l,i,k);\r\n BOOST_CHECK_MESSAGE(b==c2,std::string(\"Destructive Subtract 2 for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIAAddSubtractTests )\n{\n\n\r\n\r\n do_work(8,10);\n do_work(8,10);\r\n do_work(8,10);\n do_work(8,10);\r\n\r\n do_work(10,8);\n do_work(10,8);\r\n do_work(10,8);\n do_work(10,8);\r\n\r\n\r\n\n\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of KDE Kontact.\n\n Copyright (c) 2001 Matthias Hoelzer-Kluepfel \n Copyright (c) 2002-2003 Daniel Molkentin \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#if (QT_VERSION-0 >= 0x030200)\n#include \n#else\n#include \"splash.h\"\n#endif\n\n#include \"mainwindow.h\"\n\nstatic const char *description =\n I18N_NOOP( \"A KDE Personal Information Manager\" );\n\nstatic const char *version = \"0.2.9 (CVS)\";\n\nint main(int argc, char **argv)\n{\n KAboutData about( \"kontact\", I18N_NOOP( \"Kontact\" ), version, description,\n KAboutData::License_GPL, \"(C) 2001-2003 The Kontact developers\", 0, \"http:\/\/kontact.kde.org\", \"kde-pim@kde.org\" );\n about.addAuthor( \"Matthias Hoelzer-Kluepfel\", 0, \"mhk@kde.org\" );\n about.addAuthor( \"Daniel Molkentin\", 0, \"molkentin@kde.org\" );\n about.addAuthor( \"Don Sanders\", 0, \"sanders@kde.org\" );\n about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n about.addAuthor( \"Sven Lüppken\", 0, \"sven@kde.org\" );\n about.addAuthor( \"Tobias Koenig\", I18N_NOOP( \"Summary view widgets\" ),\n \"tokoe@kde.org\" );\n\n KCmdLineArgs::init( argc, argv, &about );\n KUniqueApplication app;\n\n \/\/ show splash\n#if (QT_VERSION-0 >= 0x030200)\n QPixmap splashPixmap( UserIcon( \"splash\" ) );\n\n QSplashScreen *splash = new QSplashScreen( splashPixmap );\n splash->show();\n#else\n Kontact::Splash *splash = new Kontact::Splash( 0, \"splash\" );\n splash->show();\n#endif\n\n \/\/ see if we are starting with session management\n if ( app.isRestored() )\n RESTORE( Kontact::MainWindow )\n else {\n \/\/ no session.. just start up normally\n Kontact::MainWindow *mw = new Kontact::MainWindow;\n mw->show();\n }\n\n \/\/ delete splash\n delete splash;\n\n return app.exec();\n}\nSome credits shuffeling: - Ordered project members chronoligically (date of join) - Tobias did far more than just the summary view, I hope he is fine with removing the attribution. If not, please speak up - Moved mhk to the bottom and marked him as original author as requested by him quite a while ago\/*\n This file is part of KDE Kontact.\n\n Copyright (c) 2001 Matthias Hoelzer-Kluepfel \n Copyright (c) 2002-2003 Daniel Molkentin \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#if (QT_VERSION-0 >= 0x030200)\n#include \n#else\n#include \"splash.h\"\n#endif\n\n#include \"mainwindow.h\"\n\nstatic const char *description =\n I18N_NOOP( \"A KDE Personal Information Manager\" );\n\nstatic const char *version = \"0.2.9 (CVS)\";\n\nint main(int argc, char **argv)\n{\n KAboutData about( \"kontact\", I18N_NOOP( \"Kontact\" ), version, description,\n KAboutData::License_GPL, \"(C) 2001-2003 The Kontact developers\", 0, \"http:\/\/kontact.kde.org\", \"kde-pim@kde.org\" );\n about.addAuthor( \"Daniel Molkentin\", 0, \"molkentin@kde.org\" );\n about.addAuthor( \"Don Sanders\", 0, \"sanders@kde.org\" );\n about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n about.addAuthor( \"Tobias Koenig\", 0, \"tokoe@kde.org\" );\n about.addAuthor( \"Sven Lüppken\", 0, \"sven@kde.org\" );\n about.addAuthor( \"Matthias Hoelzer-Kluepfel\", I18N_NOOP(\"Original Author\"), \"mhk@kde.org\" );\n\n KCmdLineArgs::init( argc, argv, &about );\n KUniqueApplication app;\n\n \/\/ show splash\n#if (QT_VERSION-0 >= 0x030200)\n QPixmap splashPixmap( UserIcon( \"splash\" ) );\n\n QSplashScreen *splash = new QSplashScreen( splashPixmap );\n splash->show();\n#else\n Kontact::Splash *splash = new Kontact::Splash( 0, \"splash\" );\n splash->show();\n#endif\n\n \/\/ see if we are starting with session management\n if ( app.isRestored() )\n RESTORE( Kontact::MainWindow )\n else {\n \/\/ no session.. just start up normally\n Kontact::MainWindow *mw = new Kontact::MainWindow;\n mw->show();\n }\n\n \/\/ delete splash\n delete splash;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n#define CAF_SUITE local_migration\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/all.hpp\"\n\n#include \"caf\/detail\/actor_registry.hpp\"\n\nusing namespace caf;\n\nusing std::endl;\n\nnamespace {\n\nstruct migratable_state {\n int value = 0;\n static const char* name;\n};\n\nconst char* migratable_state::name = \"migratable_actor\";\n\ntemplate \nvoid serialize(Archive& ar, migratable_state& x, const unsigned int) {\n ar & x.value;\n}\n\nstruct migratable_actor : stateful_actor {\n behavior make_behavior() override {\n return {\n [=](get_atom) {\n return state.value;\n },\n [=](put_atom, int value) {\n state.value = value;\n }\n };\n }\n};\n\n\/\/ always migrates to `dest`\nbehavior pseudo_mm(event_based_actor* self, const actor& dest) {\n return {\n [=](migrate_atom, const std::string& name, std::vector& buf) {\n CAF_CHECK(name == \"migratable_actor\");\n self->delegate(dest, sys_atom::value, migrate_atom::value,\n std::move(buf));\n }\n };\n}\n\n} \/\/ namespace \n\nCAF_TEST(migrate_locally) {\n auto a = spawn();\n auto b = spawn();\n auto mm1 = spawn(pseudo_mm, b);\n scoped_actor self;\n self->send(a, put_atom::value, 42);\n \/\/ migrate from a to b\n self->sync_send(a, sys_atom::value, migrate_atom::value, mm1).await(\n [&](ok_atom, const actor_addr& dest) {\n CAF_CHECK(dest == b);\n }\n );\n self->sync_send(a, get_atom::value).await(\n [&](int result) {\n CAF_CHECK(result == 42);\n CAF_CHECK(self->current_sender() == b.address());\n }\n );\n auto mm2 = spawn(pseudo_mm, a);\n self->send(b, put_atom::value, 23);\n \/\/ migrate back from b to a\n self->sync_send(b, sys_atom::value, migrate_atom::value, mm2).await(\n [&](ok_atom, const actor_addr& dest) {\n CAF_CHECK(dest == a);\n }\n );\n self->sync_send(b, get_atom::value).await(\n [&](int result) {\n CAF_CHECK(result == 23);\n CAF_CHECK(self->current_sender() == a.address());\n }\n );\n self->send_exit(a, exit_reason::kill);\n self->send_exit(b, exit_reason::kill);\n self->send_exit(mm1, exit_reason::kill);\n self->send_exit(mm2, exit_reason::kill);\n self->await_all_other_actors_done();\n shutdown();\n}\nFix heap-use-after-free in local_migration unit-test\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n#define CAF_SUITE local_migration\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/all.hpp\"\n\n#include \"caf\/detail\/actor_registry.hpp\"\n\nusing namespace caf;\n\nusing std::endl;\n\nnamespace {\n\nstruct migratable_state {\n int value = 0;\n static const char* name;\n};\n\nconst char* migratable_state::name = \"migratable_actor\";\n\ntemplate \nvoid serialize(Archive& ar, migratable_state& x, const unsigned int) {\n ar & x.value;\n}\n\nstruct migratable_actor : stateful_actor {\n behavior make_behavior() override {\n return {\n [=](get_atom) {\n return state.value;\n },\n [=](put_atom, int value) {\n state.value = value;\n }\n };\n }\n};\n\n\/\/ always migrates to `dest`\nbehavior pseudo_mm(event_based_actor* self, const actor& dest) {\n return {\n [=](migrate_atom, const std::string& name, std::vector& buf) {\n CAF_CHECK(name == \"migratable_actor\");\n self->delegate(dest, sys_atom::value, migrate_atom::value,\n std::move(buf));\n }\n };\n}\n\n} \/\/ namespace \n\nCAF_TEST(migrate_locally) {\n auto a = spawn();\n auto b = spawn();\n auto mm1 = spawn(pseudo_mm, b);\n { \/\/ Lifetime scope of scoped_actor\n scoped_actor self;\n self->send(a, put_atom::value, 42);\n \/\/ migrate from a to b\n self->sync_send(a, sys_atom::value, migrate_atom::value, mm1).await(\n [&](ok_atom, const actor_addr& dest) {\n CAF_CHECK(dest == b);\n }\n );\n self->sync_send(a, get_atom::value).await(\n [&](int result) {\n CAF_CHECK(result == 42);\n CAF_CHECK(self->current_sender() == b.address());\n }\n );\n auto mm2 = spawn(pseudo_mm, a);\n self->send(b, put_atom::value, 23);\n \/\/ migrate back from b to a\n self->sync_send(b, sys_atom::value, migrate_atom::value, mm2).await(\n [&](ok_atom, const actor_addr& dest) {\n CAF_CHECK(dest == a);\n }\n );\n self->sync_send(b, get_atom::value).await(\n [&](int result) {\n CAF_CHECK(result == 23);\n CAF_CHECK(self->current_sender() == a.address());\n }\n );\n self->send_exit(a, exit_reason::kill);\n self->send_exit(b, exit_reason::kill);\n self->send_exit(mm1, exit_reason::kill);\n self->send_exit(mm2, exit_reason::kill);\n self->await_all_other_actors_done();\n }\n shutdown();\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.4 2001\/03\/02 14:39:21 tng\n * Enabling libWWW NetAccessor support under UNIX. Tested with latest tarball of libWWW\n * (w3c-libwww-5.3.2) under RedHat Linux 6.1. Added by Martin Kalen.\n *\n * There is one MAJOR problem with the use of libwww and the patches\n * below, which someone with knowledge of libwww filters etc. might want\n * to look into. Default behavior for content-type text\/xml is to consume\n * all xml data before it reaches the simple HTML presenter. Hence, only\n * files with content-type text\/html will actually reach the xerces-c\n * library. If you have a *.xml file on the webbserver, processing of the\n * file will throw an exception stating \"The main XML document cannot be\n * empty\" (correct in a xerces point of view since if you enable debug\n * build you will see that libwww \"eats\" all text\/xml).\n *\n * See \"Diffs for enabling libWWW NetAccessor support under UNIX\" posted in March 1, 2001\n * in the xerces-c-dev mailing list for further information.\n *\n * Revision 1.3 2000\/05\/15 22:31:31 andyh\n * Replace #include with everywhere.\n *\n * Revision 1.2 2000\/02\/26 07:56:36 rahulj\n * Fixed the license header as pointed out by Bill Schindler \n *\n * Revision 1.1 2000\/02\/17 22:06:19 rahulj\n * Moved the four LibWWW files to its own sub-directory in the\n * NetAccessor directory.\n *\n *\n * Revision 1.1 2000\/01\/15 01:08:04 rahulj\n * Added support for HTTP to the parser.\n * Error handling is not very good. Also cannot guarantee that\n * there are no memory leaks.\n * Only tested under NT 4.0 SP 5 using libWWW 5.2.8.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/\n\/\/ This define specifies the size of the buffer used to read chunks\n\/\/ out of the URL input stream.\n\/\/\n\n#define URLISBUFMAXSIZE 8192\n\n\n\/\/\n\/\/ We assume here that the URL is essentially composed of just ASCII characters\n\/\/ and hence converting it to a 'char *' requires just to drop the leading zero\n\/\/ byte. The reason, we can get away with this is that libWWW currently provides\n\/\/ no wide character API's.\n\/\/\n\/\/ The input Unicode string is assumed to be 0 terminated.\n\/\/ The caller is responsible to free the memory allocated to store the resultant\n\/\/ 'char *' string.\n\/\/\n\nstatic char* localTranscode(const XMLCh* latinStrInUnicode)\n{\n unsigned int lent = XMLString::stringLen(latinStrInUnicode);\n char* retval = new char[lent + 1];\n unsigned int i = 0;\n for (i = 0; i < lent; i++)\n retval[i] = (char) latinStrInUnicode[i]; \/\/ drop the leading byte.\n retval[lent] = 0;\n return retval;\n}\n\n\n\nBinURLInputStream::BinURLInputStream(const XMLURL& urlSource)\n : fBuffer(0)\n , fBufferSize(0)\n , fBufferIndex(0)\n , fRemoteFileSize(0)\n , fAnchor(0)\n , fBytesProcessed(0)\n{\n fBuffer = new XMLByte[URLISBUFMAXSIZE];\n const XMLCh* uri = urlSource.getURLText();\n char* uriAsCharStar = localTranscode(uri);\n\n \/\/\n \/\/ First find the size of the remote resource being asked for.\n \/\/ We use the ContentCounter stream provided by libWWW.\n \/\/\n\n fAnchor = HTAnchor_findAddress(uriAsCharStar);\n HTRequest* request = HTRequest_new();\n HTRequest_setOutputFormat(request, WWW_SOURCE);\n HTStream* counterStrm = HTContentCounter(HTBlackHole(), request, 0xFFFF);\n BOOL status = HTLoadToStream(uriAsCharStar, counterStrm, request);\n if (status == YES)\n {\n \/\/ I am not happy at all with the error handling. So that needs to\n \/\/ happen.\n HTParentAnchor* parentAnchor = HTAnchor_parent(fAnchor);\n fRemoteFileSize = HTAnchor_length(parentAnchor);\n }\n\n \/\/ Cleanup, before you throw any errors.\n delete [] uriAsCharStar;\n HTRequest_delete(request);\n \/\/ Don't know whether I am supposed to delete counterStrm.\n \n if (status == NO)\n {\n ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError,\n \"Cannot determine length of remote file.\");\n }\n}\n\n\n\nBinURLInputStream::~BinURLInputStream()\n{\n delete [] fBuffer;\n fBuffer = 0;\n \/\/ Do not delete the fAnchor. Its deleted when the destructor of\n \/\/ libWWWNetAccessor is called.\n}\n\n\nvoid BinURLInputStream::reset()\n{\n fBufferSize = 0;\n fBytesProcessed = 0;\n fBufferIndex = 0;\n memset((void*) fBuffer, 0x00, sizeof(XMLByte) * URLISBUFMAXSIZE);\n}\n\n\nunsigned int BinURLInputStream::curPos() const\n{\n return fBytesProcessed;\n}\n\n\nunsigned int BinURLInputStream::bytesAvail() const\n{\n unsigned int retval = fBufferSize - fBufferIndex;\n return retval;\n}\n\n\nunsigned int BinURLInputStream::readBytes(XMLByte* const toFill\n , const unsigned int maxToRead)\n{\n unsigned int retval = 0;\n unsigned int bytesAsked = maxToRead;\n unsigned int bytesForCopy = 0;\n\n \/\/ Wipe out the old stuff from the destination buffer to fill.\n\n memset((void*)toFill, 0x00, sizeof(XMLByte) * maxToRead);\n \n \/\/ You can only read till the end of the remote resource file.\n \/\/ So, adjust the count of bytes you want to read now.\n\n if (fBytesProcessed + bytesAsked >= fRemoteFileSize)\n {\n bytesAsked = fRemoteFileSize - fBytesProcessed;\n }\n\n if (fBufferSize > 0)\n bytesForCopy = fBufferSize - fBufferIndex;\n\n if (bytesAsked <= bytesForCopy)\n {\n \/\/ ...then you can satisfy this request completely from fBuffer.\n \/\/ Simply copy over the bytes to the destination array.\n memcpy((void*) toFill, (void*) (fBuffer + fBufferIndex), bytesAsked);\n fBufferIndex += bytesAsked;\n if (fBufferIndex >= fBufferSize)\n {\n fBufferSize = 0;\n fBufferIndex = 0;\n }\n fBytesProcessed += bytesAsked;\n retval = bytesAsked;\n }\n\n else\n {\n \/\/ ...will need to read some more bytes out of the stream.\n unsigned int bufToFillIndex = 0;\n HTRequest* request = HTRequest_new();\n HTChunk* result = NULL;\n char ranges[64];\n\n \/\/ First copy over what is left in fBuffer, before reading another\n \/\/ chunk out of the stream.\n\n if (bytesForCopy != 0)\n {\n memcpy((void*) toFill, (void*) (fBuffer + fBufferSize), bytesForCopy);\n fBufferSize = 0;\n fBufferIndex = 0;\n fBytesProcessed += bytesForCopy;\n bufToFillIndex = bytesForCopy;\n retval = bytesForCopy;\n }\n\n unsigned int bytesRemainingForCopy = bytesAsked - bytesForCopy;\n\n \/\/ Now read a new chunk from the stream. HTTP lets you specify the\n \/\/ range of bytes that you would like.\n\n sprintf(ranges, \"%ld-%ld\", \n fBytesProcessed, fBytesProcessed + URLISBUFMAXSIZE - 1);\n HTRequest_addRange(request, \"bytes\", ranges);\n HTRequest_setOutputFormat(request, WWW_SOURCE);\n result = HTLoadAnchorToChunk(fAnchor, request);\n fBufferSize = HTChunk_size(result);\n if (fBufferSize > 0)\n {\n \/\/ Store the read chunk in fBuffer.\n memset((void*) fBuffer, 0x00, URLISBUFMAXSIZE);\n memcpy((void*) fBuffer, (void*) HTChunk_data(result), fBufferSize);\n fBufferIndex = 0;\n }\n\n HTRequest_delete(request);\n HTChunk_delete(result);\n\n \/\/ Now fill the destination buffer with the new data just read.\n\n bytesForCopy = fBufferSize;\n if (bytesRemainingForCopy > fBufferSize)\n {\n bytesRemainingForCopy = fBufferSize;\n }\n memcpy((void*) (toFill + bufToFillIndex),\n (void*) fBuffer,\n bytesRemainingForCopy);\n\n \/\/ Update counters.\n retval += bytesRemainingForCopy;\n fBufferIndex += bytesRemainingForCopy;\n fBytesProcessed += bytesRemainingForCopy;\n }\n\n return retval;\n}\nBug 2237: fix by Artur Klauser\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.5 2001\/11\/28 19:11:33 knoaman\n * Bug 2237: fix by Artur Klauser\n *\n * Revision 1.4 2001\/03\/02 14:39:21 tng\n * Enabling libWWW NetAccessor support under UNIX. Tested with latest tarball of libWWW\n * (w3c-libwww-5.3.2) under RedHat Linux 6.1. Added by Martin Kalen.\n *\n * There is one MAJOR problem with the use of libwww and the patches\n * below, which someone with knowledge of libwww filters etc. might want\n * to look into. Default behavior for content-type text\/xml is to consume\n * all xml data before it reaches the simple HTML presenter. Hence, only\n * files with content-type text\/html will actually reach the xerces-c\n * library. If you have a *.xml file on the webbserver, processing of the\n * file will throw an exception stating \"The main XML document cannot be\n * empty\" (correct in a xerces point of view since if you enable debug\n * build you will see that libwww \"eats\" all text\/xml).\n *\n * See \"Diffs for enabling libWWW NetAccessor support under UNIX\" posted in March 1, 2001\n * in the xerces-c-dev mailing list for further information.\n *\n * Revision 1.3 2000\/05\/15 22:31:31 andyh\n * Replace #include with everywhere.\n *\n * Revision 1.2 2000\/02\/26 07:56:36 rahulj\n * Fixed the license header as pointed out by Bill Schindler \n *\n * Revision 1.1 2000\/02\/17 22:06:19 rahulj\n * Moved the four LibWWW files to its own sub-directory in the\n * NetAccessor directory.\n *\n *\n * Revision 1.1 2000\/01\/15 01:08:04 rahulj\n * Added support for HTTP to the parser.\n * Error handling is not very good. Also cannot guarantee that\n * there are no memory leaks.\n * Only tested under NT 4.0 SP 5 using libWWW 5.2.8.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/\n\/\/ This define specifies the size of the buffer used to read chunks\n\/\/ out of the URL input stream.\n\/\/\n\n#define URLISBUFMAXSIZE 8192\n\n\n\/\/\n\/\/ We assume here that the URL is essentially composed of just ASCII characters\n\/\/ and hence converting it to a 'char *' requires just to drop the leading zero\n\/\/ byte. The reason, we can get away with this is that libWWW currently provides\n\/\/ no wide character API's.\n\/\/\n\/\/ The input Unicode string is assumed to be 0 terminated.\n\/\/ The caller is responsible to free the memory allocated to store the resultant\n\/\/ 'char *' string.\n\/\/\n\nstatic char* localTranscode(const XMLCh* latinStrInUnicode)\n{\n unsigned int lent = XMLString::stringLen(latinStrInUnicode);\n char* retval = new char[lent + 1];\n unsigned int i = 0;\n for (i = 0; i < lent; i++)\n retval[i] = (char) latinStrInUnicode[i]; \/\/ drop the leading byte.\n retval[lent] = 0;\n return retval;\n}\n\n\n\nBinURLInputStream::BinURLInputStream(const XMLURL& urlSource)\n : fBuffer(0)\n , fBufferSize(0)\n , fBufferIndex(0)\n , fRemoteFileSize(0)\n , fAnchor(0)\n , fBytesProcessed(0)\n{\n fBuffer = new XMLByte[URLISBUFMAXSIZE];\n const XMLCh* uri = urlSource.getURLText();\n char* uriAsCharStar = localTranscode(uri);\n\n \/\/\n \/\/ First find the size of the remote resource being asked for.\n \/\/ We use the ContentCounter stream provided by libWWW.\n \/\/\n\n fAnchor = HTAnchor_findAddress(uriAsCharStar);\n HTRequest* request = HTRequest_new();\n HTRequest_setOutputFormat(request, WWW_SOURCE);\n HTStream* counterStrm = HTContentCounter(HTBlackHole(), request, 0xFFFF);\n BOOL status = HTLoadToStream(uriAsCharStar, counterStrm, request);\n if (status == YES)\n {\n \/\/ Patch by Artur Klauser\n \/\/ When a redirection is processed in libWWW, it seems that\n \/\/ HTAnchor_length(anchor) == -1 on the original anchor, whereas\n \/\/ HTResponse_length(response) gives the correct content length of\n \/\/ the redirection target. This has confusedfRemoteFileSize and it was\n \/\/ not checked for a -1 response at all.\n HTResponse * response = HTRequest_response (request);\n fRemoteFileSize = HTResponse_length(response);\n if (fRemoteFileSize < 0) {\n ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError,\n \"Cannot determine length of remote file.\");\n }\n }\n\n \/\/ Cleanup, before you throw any errors.\n delete [] uriAsCharStar;\n HTRequest_delete(request);\n \/\/ Don't know whether I am supposed to delete counterStrm.\n \n if (status == NO)\n {\n ThrowXML1(NetAccessorException, XMLExcepts::NetAcc_InternalError,\n \"Cannot determine length of remote file.\");\n }\n}\n\n\n\nBinURLInputStream::~BinURLInputStream()\n{\n delete [] fBuffer;\n fBuffer = 0;\n \/\/ Do not delete the fAnchor. Its deleted when the destructor of\n \/\/ libWWWNetAccessor is called.\n}\n\n\nvoid BinURLInputStream::reset()\n{\n fBufferSize = 0;\n fBytesProcessed = 0;\n fBufferIndex = 0;\n memset((void*) fBuffer, 0x00, sizeof(XMLByte) * URLISBUFMAXSIZE);\n}\n\n\nunsigned int BinURLInputStream::curPos() const\n{\n return fBytesProcessed;\n}\n\n\nunsigned int BinURLInputStream::bytesAvail() const\n{\n unsigned int retval = fBufferSize - fBufferIndex;\n return retval;\n}\n\n\nunsigned int BinURLInputStream::readBytes(XMLByte* const toFill\n , const unsigned int maxToRead)\n{\n unsigned int retval = 0;\n unsigned int bytesAsked = maxToRead;\n unsigned int bytesForCopy = 0;\n\n \/\/ Wipe out the old stuff from the destination buffer to fill.\n\n memset((void*)toFill, 0x00, sizeof(XMLByte) * maxToRead);\n \n \/\/ You can only read till the end of the remote resource file.\n \/\/ So, adjust the count of bytes you want to read now.\n\n if (fBytesProcessed + bytesAsked >= fRemoteFileSize)\n {\n bytesAsked = fRemoteFileSize - fBytesProcessed;\n }\n\n if (fBufferSize > 0)\n bytesForCopy = fBufferSize - fBufferIndex;\n\n if (bytesAsked <= bytesForCopy)\n {\n \/\/ ...then you can satisfy this request completely from fBuffer.\n \/\/ Simply copy over the bytes to the destination array.\n memcpy((void*) toFill, (void*) (fBuffer + fBufferIndex), bytesAsked);\n fBufferIndex += bytesAsked;\n if (fBufferIndex >= fBufferSize)\n {\n fBufferSize = 0;\n fBufferIndex = 0;\n }\n fBytesProcessed += bytesAsked;\n retval = bytesAsked;\n }\n\n else\n {\n \/\/ ...will need to read some more bytes out of the stream.\n unsigned int bufToFillIndex = 0;\n HTRequest* request = HTRequest_new();\n HTChunk* result = NULL;\n char ranges[64];\n\n \/\/ First copy over what is left in fBuffer, before reading another\n \/\/ chunk out of the stream.\n\n if (bytesForCopy != 0)\n {\n memcpy((void*) toFill, (void*) (fBuffer + fBufferSize), bytesForCopy);\n fBufferSize = 0;\n fBufferIndex = 0;\n fBytesProcessed += bytesForCopy;\n bufToFillIndex = bytesForCopy;\n retval = bytesForCopy;\n }\n\n unsigned int bytesRemainingForCopy = bytesAsked - bytesForCopy;\n\n \/\/ Now read a new chunk from the stream. HTTP lets you specify the\n \/\/ range of bytes that you would like.\n\n sprintf(ranges, \"%ld-%ld\", \n fBytesProcessed, fBytesProcessed + URLISBUFMAXSIZE - 1);\n HTRequest_addRange(request, \"bytes\", ranges);\n HTRequest_setOutputFormat(request, WWW_SOURCE);\n result = HTLoadAnchorToChunk(fAnchor, request);\n fBufferSize = HTChunk_size(result);\n if (fBufferSize > 0)\n {\n \/\/ Store the read chunk in fBuffer.\n memset((void*) fBuffer, 0x00, URLISBUFMAXSIZE);\n memcpy((void*) fBuffer, (void*) HTChunk_data(result), fBufferSize);\n fBufferIndex = 0;\n }\n\n HTRequest_delete(request);\n HTChunk_delete(result);\n\n \/\/ Now fill the destination buffer with the new data just read.\n\n bytesForCopy = fBufferSize;\n if (bytesRemainingForCopy > fBufferSize)\n {\n bytesRemainingForCopy = fBufferSize;\n }\n memcpy((void*) (toFill + bufToFillIndex),\n (void*) fBuffer,\n bytesRemainingForCopy);\n\n \/\/ Update counters.\n retval += bytesRemainingForCopy;\n fBufferIndex += bytesRemainingForCopy;\n fBytesProcessed += bytesRemainingForCopy;\n }\n\n return retval;\n}\n<|endoftext|>"} {"text":"#include \"llvm\/runner.hpp\"\n\nRunner::Runner(ModuleCompiler::Link v): v(v) {\n llvm::InitializeNativeTarget();\n llvm::InitializeNativeTargetAsmPrinter();\n llvm::InitializeNativeTargetAsmParser();\n \n std::string onError = \"\";\n auto eb = new llvm::EngineBuilder(std::unique_ptr(v->getModule()));\n engine = eb\n ->setErrorStr(&onError)\n .setEngineKind(llvm::EngineKind::JIT)\n .create();\n for (const auto& pair : nameToFunPtr) {\n auto funPtr = v->getModule()->getFunction(pair.first);\n if (funPtr == nullptr) continue; \/\/ Function not used\n engine->addGlobalMapping(funPtr, pair.second);\n }\n using namespace std::placeholders;\n if (auto funPtr = v->getModule()->getFunction(\"_xyl_dynAllocType\")) {\n auto boundToThis = std::bind(&Runner::dynAllocType, this, _1);\n engine->addGlobalMapping(funPtr, &boundToThis);\n }\n engine->finalizeObject();\n if (onError != \"\") throw InternalError(\"ExecutionEngine error\", {\n METADATA_PAIRS,\n {\"supplied error string\", onError}\n });\n}\n\nint Runner::run() {\n return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});\n}\n\nvoid* Runner::dynAllocType(UniqueIdentifier typeId) {\n llvm::DataLayout d(v->getModule());\n auto id = *std::find_if(ALL(*v->getTypeSetPtr().get()), [=](auto id) {\n return *id == typeId;\n });\n return std::malloc(d.getTypeAllocSize(id->getAllocaType()));\n}\nFix shadowing#include \"llvm\/runner.hpp\"\n\nRunner::Runner(ModuleCompiler::Link v): v(v) {\n llvm::InitializeNativeTarget();\n llvm::InitializeNativeTargetAsmPrinter();\n llvm::InitializeNativeTargetAsmParser();\n \n std::string onError = \"\";\n auto eb = new llvm::EngineBuilder(std::unique_ptr(v->getModule()));\n engine = eb\n ->setErrorStr(&onError)\n .setEngineKind(llvm::EngineKind::JIT)\n .create();\n for (const auto& pair : nameToFunPtr) {\n auto funPtr = v->getModule()->getFunction(pair.first);\n if (funPtr == nullptr) continue; \/\/ Function not used\n engine->addGlobalMapping(funPtr, pair.second);\n }\n using namespace std::placeholders;\n if (auto funPtr = v->getModule()->getFunction(\"_xyl_dynAllocType\")) {\n auto boundToThis = std::bind(&Runner::dynAllocType, this, _1);\n engine->addGlobalMapping(funPtr, &boundToThis);\n }\n engine->finalizeObject();\n if (onError != \"\") throw InternalError(\"ExecutionEngine error\", {\n METADATA_PAIRS,\n {\"supplied error string\", onError}\n });\n}\n\nint Runner::run() {\n return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});\n}\n\nvoid* Runner::dynAllocType(UniqueIdentifier typeId) {\n llvm::DataLayout d(v->getModule());\n auto id = *std::find_if(ALL(*v->getTypeSetPtr().get()), [=](auto tid) {\n return *tid == typeId;\n });\n return std::malloc(d.getTypeAllocSize(id->getAllocaType()));\n}\n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n **\/\n\n#include \"tmb\/message_bus.h\"\n\n#include \/\/ NOLINT(build\/c++11)\n#include \n#include \n#include \/\/ NOLINT(build\/c++11)\n\n#include \"gflags\/gflags.h\"\n\nnamespace tmb {\n\nstatic bool ValidateTmbReceivePollInterval(const char *flagname,\n std::int32_t value) {\n if (value > 0) {\n return true;\n } else {\n std::fprintf(stderr, \"--%s must be at least 1\\n\", flagname);\n return false;\n }\n}\nDEFINE_int32(tmb_receive_poll_interval, 50,\n \"The number of milliseconds to sleep between calls to ReceiveIfAvailableImpl() \"\n \"in the default active-polling implementation of ReceiveImpl().\");\nstatic const bool tmb_receive_poll_interval_dummy = gflags::RegisterFlagValidator(\n &FLAGS_tmb_receive_poll_interval,\n &ValidateTmbReceivePollInterval);\n\ninternal::NetMessageRemovalInterface*\n MessageBus::GetNetMessageRemovalInterface() {\n std::fprintf(stderr,\n \"FATAL: TMB internal error. Called \"\n \"GetNetMessageRemovalInterface() on a MessageBus that does not \"\n \"support it.\");\n std::exit(1);\n}\n\nstd::size_t MessageBus::ReceiveImpl(const client_id receiver_id,\n const Priority minimum_priority,\n const std::size_t max_messages,\n const bool delete_immediately,\n internal::ContainerPusher *pusher) {\n std::size_t received = ReceiveIfAvailableImpl(receiver_id,\n minimum_priority,\n max_messages,\n delete_immediately,\n pusher);\n while (received == 0) {\n std::this_thread::sleep_for(\n std::chrono::milliseconds(FLAGS_tmb_receive_poll_interval));\n received = ReceiveIfAvailableImpl(receiver_id,\n minimum_priority,\n max_messages,\n delete_immediately,\n pusher);\n }\n\n return received;\n}\n\n} \/\/ namespace tmb\nvolatile keyword fixes gcc compile error\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n **\/\n\n#include \"tmb\/message_bus.h\"\n\n#include \/\/ NOLINT(build\/c++11)\n#include \n#include \n#include \/\/ NOLINT(build\/c++11)\n\n#include \"gflags\/gflags.h\"\n\nnamespace tmb {\n\nstatic bool ValidateTmbReceivePollInterval(const char *flagname,\n std::int32_t value) {\n if (value > 0) {\n return true;\n } else {\n std::fprintf(stderr, \"--%s must be at least 1\\n\", flagname);\n return false;\n }\n}\nDEFINE_int32(tmb_receive_poll_interval, 50,\n \"The number of milliseconds to sleep between calls to ReceiveIfAvailableImpl() \"\n \"in the default active-polling implementation of ReceiveImpl().\");\nstatic volatile const bool tmb_receive_poll_interval_dummy = gflags::RegisterFlagValidator(\n &FLAGS_tmb_receive_poll_interval,\n &ValidateTmbReceivePollInterval);\n\ninternal::NetMessageRemovalInterface*\n MessageBus::GetNetMessageRemovalInterface() {\n std::fprintf(stderr,\n \"FATAL: TMB internal error. Called \"\n \"GetNetMessageRemovalInterface() on a MessageBus that does not \"\n \"support it.\");\n std::exit(1);\n}\n\nstd::size_t MessageBus::ReceiveImpl(const client_id receiver_id,\n const Priority minimum_priority,\n const std::size_t max_messages,\n const bool delete_immediately,\n internal::ContainerPusher *pusher) {\n std::size_t received = ReceiveIfAvailableImpl(receiver_id,\n minimum_priority,\n max_messages,\n delete_immediately,\n pusher);\n while (received == 0) {\n std::this_thread::sleep_for(\n std::chrono::milliseconds(FLAGS_tmb_receive_poll_interval));\n received = ReceiveIfAvailableImpl(receiver_id,\n minimum_priority,\n max_messages,\n delete_immediately,\n pusher);\n }\n\n return received;\n}\n\n} \/\/ namespace tmb\n<|endoftext|>"} {"text":"\/\/ (C) Copyright Gennadiy Rozental 2001-2008.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/ See http:\/\/www.boost.org\/libs\/test for the library home page.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Revision$\n\/\/\n\/\/ Description : simple implementation for Unit Test Framework parameter\n\/\/ handling routines. May be rewritten in future to use some kind of\n\/\/ command-line arguments parsing facility and environment variable handling\n\/\/ facility\n\/\/ ***************************************************************************\n\n#ifndef BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\n#define BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\n\n\/\/ Boost.Test\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Boost\n#include \n#include \n#include \n#include \n\n\/\/ STL\n#include \n#include \n\n#include \n\n\/\/____________________________________________________________________________\/\/\n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::getenv; using ::strncmp; using ::strcmp; }\n# endif\n\nnamespace boost {\n\nnamespace unit_test {\n\nnamespace {\n\n\/\/ framework parameters and there corresponding command-line arguments\nliteral_string LOG_LEVEL = \"BOOST_TEST_LOG_LEVEL\";\nliteral_string NO_RESULT_CODE = \"BOOST_TEST_RESULT_CODE\";\nliteral_string REPORT_LEVEL = \"BOOST_TEST_REPORT_LEVEL\";\nliteral_string TESTS_TO_RUN = \"BOOST_TESTS_TO_RUN\";\nliteral_string SAVE_TEST_PATTERN = \"BOOST_TEST_SAVE_PATTERN\";\nliteral_string BUILD_INFO = \"BOOST_TEST_BUILD_INFO\";\nliteral_string SHOW_PROGRESS = \"BOOST_TEST_SHOW_PROGRESS\";\nliteral_string CATCH_SYS_ERRORS = \"BOOST_TEST_CATCH_SYSTEM_ERRORS\";\nliteral_string AUTO_START_DBG = \"BOOST_TEST_AUTO_START_DBG\";\nliteral_string USE_ALT_STACK = \"BOOST_TEST_USE_ALT_STACK\";\nliteral_string DETECT_FP_EXCEPT = \"BOOST_TEST_DETECT_FP_EXCEPTIONS\";\nliteral_string REPORT_FORMAT = \"BOOST_TEST_REPORT_FORMAT\";\nliteral_string LOG_FORMAT = \"BOOST_TEST_LOG_FORMAT\";\nliteral_string OUTPUT_FORMAT = \"BOOST_TEST_OUTPUT_FORMAT\";\nliteral_string DETECT_MEM_LEAK = \"BOOST_TEST_DETECT_MEMORY_LEAK\";\nliteral_string RANDOM_SEED = \"BOOST_TEST_RANDOM\";\nliteral_string BREAK_EXEC_PATH = \"BOOST_TEST_BREAK_EXEC_PATH\";\n\nunit_test::log_level s_log_level;\nbool s_no_result_code;\nunit_test::report_level s_report_level;\nconst_string s_tests_to_run;\nconst_string s_exec_path_to_break;\nbool s_save_pattern;\nbool s_show_build_info;\nbool s_show_progress;\nbool s_catch_sys_errors;\nbool s_auto_start_dbg;\nbool s_use_alt_stack;\nbool s_detect_fp_except;\noutput_format s_report_format;\noutput_format s_log_format;\nlong s_detect_mem_leaks;\nunsigned int s_random_seed;\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** runtime_config ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nconst_string\nretrieve_framework_parameter( const_string parameter_name, int* argc, char** argv )\n{\n static fixed_mapping parameter_2_cla_name_map(\n LOG_LEVEL , \"--log_level\",\n NO_RESULT_CODE , \"--result_code\",\n REPORT_LEVEL , \"--report_level\",\n TESTS_TO_RUN , \"--run_test\",\n SAVE_TEST_PATTERN , \"--save_pattern\",\n BUILD_INFO , \"--build_info\",\n SHOW_PROGRESS , \"--show_progress\",\n CATCH_SYS_ERRORS , \"--catch_system_errors\",\n AUTO_START_DBG , \"--auto_start_dbg\",\n USE_ALT_STACK , \"--use_alt_stack\", \n DETECT_FP_EXCEPT , \"--detect_fp_exceptions\", \n REPORT_FORMAT , \"--report_format\",\n LOG_FORMAT , \"--log_format\",\n OUTPUT_FORMAT , \"--output_format\",\n DETECT_MEM_LEAK , \"--detect_memory_leaks\",\n RANDOM_SEED , \"--random\",\n BREAK_EXEC_PATH , \"--break_exec_path\",\n \n \"\"\n );\n\n \/\/ first try to find parameter among command line arguments if present\n if( argc ) {\n \/\/ locate corresponding cla name\n const_string cla_name = parameter_2_cla_name_map[parameter_name];\n\n if( !cla_name.is_empty() ) {\n for( int i = 1; i < *argc; ++i ) {\n if( cla_name == const_string( argv[i], cla_name.size() ) && argv[i][cla_name.size()] == '=' ) {\n const_string result = argv[i] + cla_name.size() + 1;\n\n for( int j = i; j < *argc; ++j ) {\n argv[j] = argv[j+1];\n }\n --(*argc);\n\n return result;\n }\n }\n }\n }\n\n return std::getenv( parameter_name.begin() );\n}\n\nlong interpret_long( const_string from )\n{\n bool negative = false;\n long res = 0;\n\n if( first_char( from ) == '-' ) {\n negative = true;\n from.trim_left( 1 );\n }\n\n const_string::iterator it = from.begin();\n for( ;it != from.end(); ++it ) {\n int d = *it - '0';\n\n res = 10 * res + d;\n }\n\n if( negative )\n res = -res;\n\n return res;\n}\n\n} \/\/ local namespace\n\n\/\/____________________________________________________________________________\/\/\n\nnamespace runtime_config {\n\nvoid\ninit( int* argc, char** argv )\n{\n fixed_mapping > log_level_name(\n \"all\" , log_successful_tests,\n \"success\" , log_successful_tests,\n \"test_suite\" , log_test_units,\n \"unit_scope\" , log_test_units,\n \"message\" , log_messages,\n \"warning\" , log_warnings,\n \"error\" , log_all_errors,\n \"cpp_exception\" , log_cpp_exception_errors,\n \"system_error\" , log_system_errors,\n \"fatal_error\" , log_fatal_errors,\n \"nothing\" , log_nothing,\n\n invalid_log_level\n );\n\n fixed_mapping > report_level_name (\n \"confirm\", CONFIRMATION_REPORT,\n \"short\", SHORT_REPORT,\n \"detailed\", DETAILED_REPORT,\n \"no\", NO_REPORT,\n\n INV_REPORT_LEVEL\n );\n\n fixed_mapping > output_format_name (\n \"HRF\", CLF,\n \"CLF\", CLF,\n \"XML\", XML,\n\n CLF\n );\n\n s_no_result_code = retrieve_framework_parameter( NO_RESULT_CODE, argc, argv ) == \"no\";\n s_save_pattern = retrieve_framework_parameter( SAVE_TEST_PATTERN, argc, argv ) == \"yes\";\n s_show_build_info = retrieve_framework_parameter( BUILD_INFO, argc, argv ) == \"yes\";\n s_show_progress = retrieve_framework_parameter( SHOW_PROGRESS, argc, argv ) == \"yes\";\n s_catch_sys_errors = retrieve_framework_parameter( CATCH_SYS_ERRORS, argc, argv ) != \"no\";\n s_use_alt_stack = retrieve_framework_parameter( USE_ALT_STACK, argc, argv ) != \"no\";\n s_detect_fp_except = retrieve_framework_parameter( DETECT_FP_EXCEPT, argc, argv ) == \"yes\";\n s_tests_to_run = retrieve_framework_parameter( TESTS_TO_RUN, argc, argv );\n s_exec_path_to_break= retrieve_framework_parameter( BREAK_EXEC_PATH, argc, argv );\n\n const_string rs_str = retrieve_framework_parameter( RANDOM_SEED, argc, argv );\n s_random_seed = rs_str.is_empty() ? 0 : lexical_cast( rs_str );\n \n s_log_level = log_level_name[retrieve_framework_parameter( LOG_LEVEL, argc, argv )];\n s_report_level = report_level_name[retrieve_framework_parameter( REPORT_LEVEL, argc, argv )];\n\n s_report_format = output_format_name[retrieve_framework_parameter( REPORT_FORMAT, argc, argv )];\n s_log_format = output_format_name[retrieve_framework_parameter( LOG_FORMAT, argc, argv )];\n\n const_string output_format = retrieve_framework_parameter( OUTPUT_FORMAT, argc, argv );\n if( !output_format.is_empty() ) {\n s_report_format = output_format_name[output_format];\n s_log_format = output_format_name[output_format];\n }\n\n const_string ml_str = retrieve_framework_parameter( DETECT_MEM_LEAK, argc, argv );\n s_detect_mem_leaks = ml_str.is_empty() ? 1 : interpret_long( ml_str );\n\n const_string dbg = retrieve_framework_parameter( AUTO_START_DBG, argc, argv );\n\n if( dbg.is_empty() || dbg == \"no\" )\n s_auto_start_dbg = false;\n else {\n s_auto_start_dbg = true;\n\n if( dbg != \"yes\" )\n debug::set_debugger( dbg );\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nunit_test::log_level\nlog_level()\n{\n return s_log_level;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nno_result_code()\n{\n return s_no_result_code;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nunit_test::report_level\nreport_level()\n{\n return s_report_level;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nconst_string\ntest_to_run()\n{\n return s_tests_to_run;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nconst_string\nbreak_exec_path()\n{\n return s_exec_path_to_break;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nsave_pattern()\n{\n return s_save_pattern;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nshow_progress()\n{\n return s_show_progress;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nshow_build_info()\n{\n return s_show_build_info;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ncatch_sys_errors()\n{\n return s_catch_sys_errors;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nauto_start_dbg()\n{\n return s_auto_start_dbg;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nuse_alt_stack()\n{\n return s_use_alt_stack;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ndetect_fp_exceptions()\n{\n return s_detect_fp_except;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_format\nreport_format()\n{\n return s_report_format;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_format\nlog_format()\n{\n return s_log_format;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nlong\ndetect_memory_leaks()\n{\n return s_detect_mem_leaks;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nint\nrandom_seed()\n{\n return s_random_seed;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace runtime_config\n\n} \/\/ namespace unit_test\n\n} \/\/ namespace boost\n\n\/\/____________________________________________________________________________\/\/\n\n#include \n\n#endif \/\/ BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\ncompile time switch to change default for catch_system_error parameter\/\/ (C) Copyright Gennadiy Rozental 2001-2008.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/ See http:\/\/www.boost.org\/libs\/test for the library home page.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Revision$\n\/\/\n\/\/ Description : simple implementation for Unit Test Framework parameter\n\/\/ handling routines. May be rewritten in future to use some kind of\n\/\/ command-line arguments parsing facility and environment variable handling\n\/\/ facility\n\/\/ ***************************************************************************\n\n#ifndef BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\n#define BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\n\n\/\/ Boost.Test\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Boost\n#include \n#include \n#include \n#include \n\n\/\/ STL\n#include \n#include \n\n#include \n\n\/\/____________________________________________________________________________\/\/\n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::getenv; using ::strncmp; using ::strcmp; }\n# endif\n\nnamespace boost {\n\nnamespace unit_test {\n\nnamespace {\n\n\/\/ framework parameters and there corresponding command-line arguments\nliteral_string LOG_LEVEL = \"BOOST_TEST_LOG_LEVEL\";\nliteral_string NO_RESULT_CODE = \"BOOST_TEST_RESULT_CODE\";\nliteral_string REPORT_LEVEL = \"BOOST_TEST_REPORT_LEVEL\";\nliteral_string TESTS_TO_RUN = \"BOOST_TESTS_TO_RUN\";\nliteral_string SAVE_TEST_PATTERN = \"BOOST_TEST_SAVE_PATTERN\";\nliteral_string BUILD_INFO = \"BOOST_TEST_BUILD_INFO\";\nliteral_string SHOW_PROGRESS = \"BOOST_TEST_SHOW_PROGRESS\";\nliteral_string CATCH_SYS_ERRORS = \"BOOST_TEST_CATCH_SYSTEM_ERRORS\";\nliteral_string AUTO_START_DBG = \"BOOST_TEST_AUTO_START_DBG\";\nliteral_string USE_ALT_STACK = \"BOOST_TEST_USE_ALT_STACK\";\nliteral_string DETECT_FP_EXCEPT = \"BOOST_TEST_DETECT_FP_EXCEPTIONS\";\nliteral_string REPORT_FORMAT = \"BOOST_TEST_REPORT_FORMAT\";\nliteral_string LOG_FORMAT = \"BOOST_TEST_LOG_FORMAT\";\nliteral_string OUTPUT_FORMAT = \"BOOST_TEST_OUTPUT_FORMAT\";\nliteral_string DETECT_MEM_LEAK = \"BOOST_TEST_DETECT_MEMORY_LEAK\";\nliteral_string RANDOM_SEED = \"BOOST_TEST_RANDOM\";\nliteral_string BREAK_EXEC_PATH = \"BOOST_TEST_BREAK_EXEC_PATH\";\n\nunit_test::log_level s_log_level;\nbool s_no_result_code;\nunit_test::report_level s_report_level;\nconst_string s_tests_to_run;\nconst_string s_exec_path_to_break;\nbool s_save_pattern;\nbool s_show_build_info;\nbool s_show_progress;\nbool s_catch_sys_errors;\nbool s_auto_start_dbg;\nbool s_use_alt_stack;\nbool s_detect_fp_except;\noutput_format s_report_format;\noutput_format s_log_format;\nlong s_detect_mem_leaks;\nunsigned int s_random_seed;\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** runtime_config ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nconst_string\nretrieve_framework_parameter( const_string parameter_name, int* argc, char** argv )\n{\n static fixed_mapping parameter_2_cla_name_map(\n LOG_LEVEL , \"--log_level\",\n NO_RESULT_CODE , \"--result_code\",\n REPORT_LEVEL , \"--report_level\",\n TESTS_TO_RUN , \"--run_test\",\n SAVE_TEST_PATTERN , \"--save_pattern\",\n BUILD_INFO , \"--build_info\",\n SHOW_PROGRESS , \"--show_progress\",\n CATCH_SYS_ERRORS , \"--catch_system_errors\",\n AUTO_START_DBG , \"--auto_start_dbg\",\n USE_ALT_STACK , \"--use_alt_stack\", \n DETECT_FP_EXCEPT , \"--detect_fp_exceptions\", \n REPORT_FORMAT , \"--report_format\",\n LOG_FORMAT , \"--log_format\",\n OUTPUT_FORMAT , \"--output_format\",\n DETECT_MEM_LEAK , \"--detect_memory_leaks\",\n RANDOM_SEED , \"--random\",\n BREAK_EXEC_PATH , \"--break_exec_path\",\n \n \"\"\n );\n\n \/\/ first try to find parameter among command line arguments if present\n if( argc ) {\n \/\/ locate corresponding cla name\n const_string cla_name = parameter_2_cla_name_map[parameter_name];\n\n if( !cla_name.is_empty() ) {\n for( int i = 1; i < *argc; ++i ) {\n if( cla_name == const_string( argv[i], cla_name.size() ) && argv[i][cla_name.size()] == '=' ) {\n const_string result = argv[i] + cla_name.size() + 1;\n\n for( int j = i; j < *argc; ++j ) {\n argv[j] = argv[j+1];\n }\n --(*argc);\n\n return result;\n }\n }\n }\n }\n\n return std::getenv( parameter_name.begin() );\n}\n\nlong interpret_long( const_string from )\n{\n bool negative = false;\n long res = 0;\n\n if( first_char( from ) == '-' ) {\n negative = true;\n from.trim_left( 1 );\n }\n\n const_string::iterator it = from.begin();\n for( ;it != from.end(); ++it ) {\n int d = *it - '0';\n\n res = 10 * res + d;\n }\n\n if( negative )\n res = -res;\n\n return res;\n}\n\n} \/\/ local namespace\n\n\/\/____________________________________________________________________________\/\/\n\nnamespace runtime_config {\n\nvoid\ninit( int* argc, char** argv )\n{\n fixed_mapping > log_level_name(\n \"all\" , log_successful_tests,\n \"success\" , log_successful_tests,\n \"test_suite\" , log_test_units,\n \"unit_scope\" , log_test_units,\n \"message\" , log_messages,\n \"warning\" , log_warnings,\n \"error\" , log_all_errors,\n \"cpp_exception\" , log_cpp_exception_errors,\n \"system_error\" , log_system_errors,\n \"fatal_error\" , log_fatal_errors,\n \"nothing\" , log_nothing,\n\n invalid_log_level\n );\n\n fixed_mapping > report_level_name (\n \"confirm\", CONFIRMATION_REPORT,\n \"short\", SHORT_REPORT,\n \"detailed\", DETAILED_REPORT,\n \"no\", NO_REPORT,\n\n INV_REPORT_LEVEL\n );\n\n fixed_mapping > output_format_name (\n \"HRF\", CLF,\n \"CLF\", CLF,\n \"XML\", XML,\n\n CLF\n );\n\n s_no_result_code = retrieve_framework_parameter( NO_RESULT_CODE, argc, argv ) == \"no\";\n s_save_pattern = retrieve_framework_parameter( SAVE_TEST_PATTERN, argc, argv ) == \"yes\";\n s_show_build_info = retrieve_framework_parameter( BUILD_INFO, argc, argv ) == \"yes\";\n s_show_progress = retrieve_framework_parameter( SHOW_PROGRESS, argc, argv ) == \"yes\";\n#ifdef BOOST_TEST_DEFAULTS_TO_CORE_DUMP\n s_catch_sys_errors = retrieve_framework_parameter( CATCH_SYS_ERRORS, argc, argv ) == \"yes\";\n#else\n s_catch_sys_errors = retrieve_framework_parameter( CATCH_SYS_ERRORS, argc, argv ) != \"no\";\n#endif\n s_use_alt_stack = retrieve_framework_parameter( USE_ALT_STACK, argc, argv ) != \"no\";\n s_detect_fp_except = retrieve_framework_parameter( DETECT_FP_EXCEPT, argc, argv ) == \"yes\";\n s_tests_to_run = retrieve_framework_parameter( TESTS_TO_RUN, argc, argv );\n s_exec_path_to_break= retrieve_framework_parameter( BREAK_EXEC_PATH, argc, argv );\n\n const_string rs_str = retrieve_framework_parameter( RANDOM_SEED, argc, argv );\n s_random_seed = rs_str.is_empty() ? 0 : lexical_cast( rs_str );\n \n s_log_level = log_level_name[retrieve_framework_parameter( LOG_LEVEL, argc, argv )];\n s_report_level = report_level_name[retrieve_framework_parameter( REPORT_LEVEL, argc, argv )];\n\n s_report_format = output_format_name[retrieve_framework_parameter( REPORT_FORMAT, argc, argv )];\n s_log_format = output_format_name[retrieve_framework_parameter( LOG_FORMAT, argc, argv )];\n\n const_string output_format = retrieve_framework_parameter( OUTPUT_FORMAT, argc, argv );\n if( !output_format.is_empty() ) {\n s_report_format = output_format_name[output_format];\n s_log_format = output_format_name[output_format];\n }\n\n const_string ml_str = retrieve_framework_parameter( DETECT_MEM_LEAK, argc, argv );\n s_detect_mem_leaks = ml_str.is_empty() ? 1 : interpret_long( ml_str );\n\n const_string dbg = retrieve_framework_parameter( AUTO_START_DBG, argc, argv );\n\n if( dbg.is_empty() || dbg == \"no\" )\n s_auto_start_dbg = false;\n else {\n s_auto_start_dbg = true;\n\n if( dbg != \"yes\" )\n debug::set_debugger( dbg );\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nunit_test::log_level\nlog_level()\n{\n return s_log_level;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nno_result_code()\n{\n return s_no_result_code;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nunit_test::report_level\nreport_level()\n{\n return s_report_level;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nconst_string\ntest_to_run()\n{\n return s_tests_to_run;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nconst_string\nbreak_exec_path()\n{\n return s_exec_path_to_break;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nsave_pattern()\n{\n return s_save_pattern;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nshow_progress()\n{\n return s_show_progress;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nshow_build_info()\n{\n return s_show_build_info;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ncatch_sys_errors()\n{\n return s_catch_sys_errors;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nauto_start_dbg()\n{\n return s_auto_start_dbg;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nuse_alt_stack()\n{\n return s_use_alt_stack;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ndetect_fp_exceptions()\n{\n return s_detect_fp_except;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_format\nreport_format()\n{\n return s_report_format;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_format\nlog_format()\n{\n return s_log_format;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nlong\ndetect_memory_leaks()\n{\n return s_detect_mem_leaks;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nint\nrandom_seed()\n{\n return s_random_seed;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace runtime_config\n\n} \/\/ namespace unit_test\n\n} \/\/ namespace boost\n\n\/\/____________________________________________________________________________\/\/\n\n#include \n\n#endif \/\/ BOOST_TEST_UNIT_TEST_PARAMETERS_IPP_012205GER\n<|endoftext|>"} {"text":"\n\/****************************************************************************\n** Copyright (c) 2006 - 2011, the LibQxt project.\n** See the Qxt AUTHORS file for a list of authors and copyright holders.\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in the\n** documentation and\/or other materials provided with the distribution.\n** * Neither the name of the LibQxt project nor the\n** names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n** \n*****************************************************************************\/\n\n\n\/*!\n \\class QxtJSON\n \\inmodule QxtCore\n \\brief The QxtJSON class implements serializing\/deserializing from\/to JSON\n\n implements JSON (JavaScript Object Notation) is a lightweight data-interchange format. \n see http:\/\/www.json.org\/\n\n \\section2 Type Conversion\n \\table 80%\n \\header \\o JSON Type \\o Qt Type\n \\row \\o object \\o QVariantMap\/QVariantHash\n \\row \\o array \\o QVariantList\/QStringList\n \\row \\o string \\o QString\n \\row \\o number \\o int,double\n \\row \\o true \\o bool\n \\row \\o false \\o bool\n \\row \\o null \\o QVariant()\n\n \\endtable\n\n*\/\n\n#include \"qxtjson.h\"\n#include \n#include \n#include \n#include \n\nQString QxtJSON::stringify(QVariant v){\n if (v.isNull()){\n return \"null\";\n }\n int t = v.type();\n if (t == QVariant::String){\n QString in = v.toString();\n QString out;\n for(QString::ConstIterator i = in.constBegin(); i != in.constEnd(); i++){\n if( (*i) == QChar('\\b'))\n out.append(\"\\\\b\");\n else if( (*i) == QChar('\\f'))\n out.append(\"\\\\f\");\n else if( (*i) == QChar('\\n'))\n out.append(\"\\\\n\");\n else if( (*i) == QChar('\\r'))\n out.append(\"\\\\r\");\n else if( (*i) == QChar('\\t'))\n out.append(\"\\\\t\");\n else if( (*i) == QChar('\\f'))\n out.append(\"\\\\f\");\n else if( (*i) == QChar('\\\\'))\n out.append(\"\\\\\\\\\");\n else if( (*i) == QChar('\/'))\n out.append(\"\\\\\/\");\n else\n out.append(*i);\n }\n return \"\\\"\"+out+\"\\\"\";\n }\n else if (t == QVariant::Bool){\n return v.toBool()?\"true\":\"false\";\n }else if (t == QVariant::Int){\n return QString::number(v.toInt());\n }else if (t == QVariant::Double){\n return QString::number(v.toDouble());\n }else if (t == QVariant::Map){\n QString r=\"{\";\n QMap map = v.toMap();\n QMapIterator i(map);\n while (i.hasNext()){\n i.next();\n r+=\"\\\"\"+i.key()+\"\\\":\"+stringify(i.value())+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"}\";\n return r;\n#if QT_VERSION >= 0x040500\n }else if (t == QVariant::Hash){\n QString r=\"{\";\n QHash map = v.toHash();\n QHashIterator i(map);\n while (i.hasNext()){\n i.next();\n r+=\"\\\"\"+i.key()+\"\\\":\"+stringify(i.value())+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"}\";\n return r;\n#endif\n }else if (t == QVariant::StringList){\n QString r=\"[\";\n QStringList l = v.toStringList();\n foreach(QString i, l){\n r+=\"\\\"\"+i+\"\\\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"]\";\n return r;\n }else if (t == QVariant::List){\n QString r=\"[\";\n QVariantList l = v.toList();\n foreach(QVariant i, l){\n r+=stringify(i)+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"]\";\n return r;\n }\n\n return QString();\n}\n\nstatic QVariant parseValue(QTextStream &s,bool & error);\nstatic QVariantMap parseObject (QTextStream & s,bool & error);\nstatic QVariantList parseArray (QTextStream & s,bool & error);\nstatic QString parseString (QTextStream & s,bool & error);\nstatic QVariant parseLiteral (QTextStream & s,bool & error);\n\nQVariant QxtJSON::parse(QString string){\n QTextStream s(&string);\n bool error=false;\n QVariant v=parseValue(s,error);\n if(error)\n return QVariant();\n return v;\n}\n\n\n\nstatic QVariant parseValue(QTextStream &s,bool & error){\n s.skipWhiteSpace();\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='{'){\n return parseObject(s,error);\n } else if (c=='\"'){\n return parseString(s,error);\n } else if (c=='['){\n return parseArray(s,error);\n } else {\n return parseLiteral(s,error);\n }\n s.skipWhiteSpace();\n }\n return QVariant();\n}\n\nstatic QVariantMap parseObject (QTextStream & s,bool & error){\n s.skipWhiteSpace();\n QVariantMap o;\n QString key;\n bool atVal=false;\n\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='}'){\n return o;\n } else if (c==',' || c==':'){\n \/*\n They're syntactic sugar, since key:value come in bundles anyway\n Could check for error handling. too lazy.\n *\/\n } else if (c=='\"'){\n if(atVal){\n o[key]=parseString(s,error);\n atVal=false;\n }else{\n key=parseString(s,error);\n atVal=true;\n }\n } else if (c=='['){\n if(atVal){\n o[key]=parseArray(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n } else if (c=='{'){\n if(atVal){\n o[key]=parseObject(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n } else {\n if(atVal){\n o[key]=parseLiteral(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n }\n s.skipWhiteSpace();\n }\n error=true;\n return QVariantMap();\n}\nstatic QVariantList parseArray (QTextStream & s,bool & error){\n s.skipWhiteSpace();\n QVariantList l;\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c==']'){\n return l;\n } else if (c==','){\n } else if (c=='\"'){\n l.append(QVariant(parseString(s,error)));\n } else if (c=='['){\n l.append(QVariant(parseArray(s,error)));\n } else if (c=='{'){\n l.append(QVariant(parseObject(s,error)));\n } else {\n l.append(QVariant(parseLiteral(s,error)));\n }\n s.skipWhiteSpace();\n }\n error=true;\n return QVariantList();\n}\nstatic QString parseString (QTextStream & s,bool & error){\n QString str;\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if(c=='\"'){\n return str;\n }else if(c=='\\\\'){\n s>>c;\n if(c=='b'){\n str.append('\\b');\n }else if(c=='f'){\n str.append('\\f');\n }else if(c=='n'){\n str.append('\\n');\n }else if(c=='r'){\n str.append('\\r');\n }else if(c=='t'){\n str.append('\\t');\n }else if(c=='f'){\n str.append('\\f');\n }else if(c=='u'){\n QString k;\n for (int i = 0; i < 4; i++ ) {\n s >> c;\n k.append(c);\n }\n bool ok;\n int i = k.toInt(&ok, 16);\n if (ok)\n str.append(QChar(i));\n }else{\n str.append(c);\n }\n }else{\n str.append(c);\n }\n }\n error=true;\n return QString();\n}\nstatic QVariant parseLiteral (QTextStream & s,bool & error){\n s.seek(s.pos()-1);\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='t'){\n s>>c;\/\/r\n s>>c;\/\/u\n s>>c;\/\/e\n return true;\n } else if (c=='f'){\n s>>c;\/\/a\n s>>c;\/\/l\n s>>c;\/\/s\n s>>c;\/\/e\n return false;\n }else if (c=='n'){\n s>>c;\/\/u\n s>>c;\/\/l\n s>>c;\/\/l\n return QVariant();\n }else if (c=='-' || c.isDigit()){\n QString n;\n while(( c.isDigit() || (c=='.') || (c=='E') || (c=='e') || (c=='-') || (c=='+') )){\n n.append(c);\n if(s.atEnd() || error)\n break;\n s>>c;\n }\n s.seek(s.pos()-1);\n if(n.contains('.')) {\n return n.toDouble();\n } else {\n bool ok = false;\n int result = n.toInt(&ok);\n if(ok) return result;\n return n.toLongLong();\n }\n }\n }\n error=true;\n return QVariant();\n}\nqxtjson: handle uint correctly\n\/****************************************************************************\n** Copyright (c) 2006 - 2011, the LibQxt project.\n** See the Qxt AUTHORS file for a list of authors and copyright holders.\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in the\n** documentation and\/or other materials provided with the distribution.\n** * Neither the name of the LibQxt project nor the\n** names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n** \n*****************************************************************************\/\n\n\n\/*!\n \\class QxtJSON\n \\inmodule QxtCore\n \\brief The QxtJSON class implements serializing\/deserializing from\/to JSON\n\n implements JSON (JavaScript Object Notation) is a lightweight data-interchange format. \n see http:\/\/www.json.org\/\n\n \\section2 Type Conversion\n \\table 80%\n \\header \\o JSON Type \\o Qt Type\n \\row \\o object \\o QVariantMap\/QVariantHash\n \\row \\o array \\o QVariantList\/QStringList\n \\row \\o string \\o QString\n \\row \\o number \\o int,double\n \\row \\o true \\o bool\n \\row \\o false \\o bool\n \\row \\o null \\o QVariant()\n\n \\endtable\n\n*\/\n\n#include \"qxtjson.h\"\n#include \n#include \n#include \n#include \n\nQString QxtJSON::stringify(QVariant v){\n if (v.isNull()){\n return \"null\";\n }\n switch (v.type()) {\n case QVariant::Bool:\n return v.toBool()?\"true\":\"false\";\n break;\n case QVariant::ULongLong:\n case QVariant::UInt:\n return QString::number(v.toULongLong());\n break;\n case QVariant::LongLong:\n case QVariant::Int:\n return QString::number(v.toLongLong());\n break;\n case QVariant::Double:\n return QString::number(v.toDouble());\n break;\n case QVariant::Map:\n {\n QString r=\"{\";\n QMap map = v.toMap();\n QMapIterator i(map);\n while (i.hasNext()){\n i.next();\n r+=\"\\\"\"+i.key()+\"\\\":\"+stringify(i.value())+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"}\";\n return r;\n }\n break;\n#if QT_VERSION >= 0x040500\n case QVariant::Hash:\n {\n QString r=\"{\";\n QHash map = v.toHash();\n QHashIterator i(map);\n while (i.hasNext()){\n i.next();\n r+=\"\\\"\"+i.key()+\"\\\":\"+stringify(i.value())+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"}\";\n return r;\n }\n break;\n#endif\n case QVariant::StringList:\n {\n QString r=\"[\";\n QStringList l = v.toStringList();\n foreach(QString i, l){\n r+=\"\\\"\"+i+\"\\\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"]\";\n return r;\n }\n case QVariant::List:\n {\n QString r=\"[\";\n QVariantList l = v.toList();\n foreach(QVariant i, l){\n r+=stringify(i)+\",\";\n }\n if(r.length()>1)\n r.chop(1);\n r+=\"]\";\n return r;\n }\n break;\n case QVariant::String:\n default:\n {\n QString in = v.toString();\n QString out;\n for(QString::ConstIterator i = in.constBegin(); i != in.constEnd(); i++){\n if( (*i) == QChar('\\b'))\n out.append(\"\\\\b\");\n else if( (*i) == QChar('\\f'))\n out.append(\"\\\\f\");\n else if( (*i) == QChar('\\n'))\n out.append(\"\\\\n\");\n else if( (*i) == QChar('\\r'))\n out.append(\"\\\\r\");\n else if( (*i) == QChar('\\t'))\n out.append(\"\\\\t\");\n else if( (*i) == QChar('\\f'))\n out.append(\"\\\\f\");\n else if( (*i) == QChar('\\\\'))\n out.append(\"\\\\\\\\\");\n else if( (*i) == QChar('\/'))\n out.append(\"\\\\\/\");\n else\n out.append(*i);\n }\n return \"\\\"\"+out+\"\\\"\";\n }\n break;\n }\n return QString();\n}\n\nstatic QVariant parseValue(QTextStream &s,bool & error);\nstatic QVariantMap parseObject (QTextStream & s,bool & error);\nstatic QVariantList parseArray (QTextStream & s,bool & error);\nstatic QString parseString (QTextStream & s,bool & error);\nstatic QVariant parseLiteral (QTextStream & s,bool & error);\n\nQVariant QxtJSON::parse(QString string){\n QTextStream s(&string);\n bool error=false;\n QVariant v=parseValue(s,error);\n if(error)\n return QVariant();\n return v;\n}\n\n\n\nstatic QVariant parseValue(QTextStream &s,bool & error){\n s.skipWhiteSpace();\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='{'){\n return parseObject(s,error);\n } else if (c=='\"'){\n return parseString(s,error);\n } else if (c=='['){\n return parseArray(s,error);\n } else {\n return parseLiteral(s,error);\n }\n s.skipWhiteSpace();\n }\n return QVariant();\n}\n\nstatic QVariantMap parseObject (QTextStream & s,bool & error){\n s.skipWhiteSpace();\n QVariantMap o;\n QString key;\n bool atVal=false;\n\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='}'){\n return o;\n } else if (c==',' || c==':'){\n \/*\n They're syntactic sugar, since key:value come in bundles anyway\n Could check for error handling. too lazy.\n *\/\n } else if (c=='\"'){\n if(atVal){\n o[key]=parseString(s,error);\n atVal=false;\n }else{\n key=parseString(s,error);\n atVal=true;\n }\n } else if (c=='['){\n if(atVal){\n o[key]=parseArray(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n } else if (c=='{'){\n if(atVal){\n o[key]=parseObject(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n } else {\n if(atVal){\n o[key]=parseLiteral(s,error);\n atVal=false;\n }else{\n error=true;\n return QVariantMap();\n }\n }\n s.skipWhiteSpace();\n }\n error=true;\n return QVariantMap();\n}\nstatic QVariantList parseArray (QTextStream & s,bool & error){\n s.skipWhiteSpace();\n QVariantList l;\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c==']'){\n return l;\n } else if (c==','){\n } else if (c=='\"'){\n l.append(QVariant(parseString(s,error)));\n } else if (c=='['){\n l.append(QVariant(parseArray(s,error)));\n } else if (c=='{'){\n l.append(QVariant(parseObject(s,error)));\n } else {\n l.append(QVariant(parseLiteral(s,error)));\n }\n s.skipWhiteSpace();\n }\n error=true;\n return QVariantList();\n}\nstatic QString parseString (QTextStream & s,bool & error){\n QString str;\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if(c=='\"'){\n return str;\n }else if(c=='\\\\'){\n s>>c;\n if(c=='b'){\n str.append('\\b');\n }else if(c=='f'){\n str.append('\\f');\n }else if(c=='n'){\n str.append('\\n');\n }else if(c=='r'){\n str.append('\\r');\n }else if(c=='t'){\n str.append('\\t');\n }else if(c=='f'){\n str.append('\\f');\n }else if(c=='u'){\n QString k;\n for (int i = 0; i < 4; i++ ) {\n s >> c;\n k.append(c);\n }\n bool ok;\n int i = k.toInt(&ok, 16);\n if (ok)\n str.append(QChar(i));\n }else{\n str.append(c);\n }\n }else{\n str.append(c);\n }\n }\n error=true;\n return QString();\n}\nstatic QVariant parseLiteral (QTextStream & s,bool & error){\n s.seek(s.pos()-1);\n QChar c;\n while(!s.atEnd() && !error){\n s>>c;\n if (c=='t'){\n s>>c;\/\/r\n s>>c;\/\/u\n s>>c;\/\/e\n return true;\n } else if (c=='f'){\n s>>c;\/\/a\n s>>c;\/\/l\n s>>c;\/\/s\n s>>c;\/\/e\n return false;\n }else if (c=='n'){\n s>>c;\/\/u\n s>>c;\/\/l\n s>>c;\/\/l\n return QVariant();\n }else if (c=='-' || c.isDigit()){\n QString n;\n while(( c.isDigit() || (c=='.') || (c=='E') || (c=='e') || (c=='-') || (c=='+') )){\n n.append(c);\n if(s.atEnd() || error)\n break;\n s>>c;\n }\n s.seek(s.pos()-1);\n if(n.contains('.')) {\n return n.toDouble();\n } else {\n bool ok = false;\n int result = n.toInt(&ok);\n if(ok) return result;\n return n.toLongLong();\n }\n }\n }\n error=true;\n return QVariant();\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n\n#if BOOST_VERSION < 103500\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#include \n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/enum_net.hpp\"\n#include \"libtorrent\/broadcast_socket.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tbool is_local(address const& a)\n\t{\n\t\tif (a.is_v6()) return a.to_v6().is_link_local();\n\t\taddress_v4 a4 = a.to_v4();\n\t\tunsigned long ip = a4.to_ulong();\n\t\treturn ((ip & 0xff000000) == 0x0a000000\n\t\t\t|| (ip & 0xfff00000) == 0xac100000\n\t\t\t|| (ip & 0xffff0000) == 0xc0a80000);\n\t}\n\n\tbool is_loopback(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t return addr.to_v4() == address_v4::loopback();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::loopback();\n\t}\n\n\tbool is_multicast(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4().is_multicast();\n\t\telse\n\t\t\treturn addr.to_v6().is_multicast();\n\t}\n\n\tbool is_any(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4() == address_v4::any();\n\t\telse if (addr.to_v6().is_v4_mapped())\n\t\t\treturn (addr.to_v6().to_v4() == address_v4::any());\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::any();\n\t}\n\n\taddress guess_local_address(io_service& ios)\n\t{\n\t\t\/\/ make a best guess of the interface we're using and its IP\n\t\terror_code ec;\n\t\tstd::vector const& interfaces = enum_net_interfaces(ios, ec);\n\t\taddress ret = address_v4::any();\n\t\tfor (std::vector::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\taddress const& a = i->interface_address;\n\t\t\tif (is_loopback(a)\n\t\t\t\t|| is_multicast(a)\n\t\t\t\t|| is_any(a)) continue;\n\n\t\t\t\/\/ prefer a v4 address, but return a v6 if\n\t\t\t\/\/ there are no v4\n\t\t\tif (a.is_v4()) return a;\n\n\t\t\tif (ret != address_v4::any())\n\t\t\t\tret = a;\n\t\t}\n\t\treturn ret;\n\t}\n\n\t\/\/ count the length of the common bit prefix\n\tint common_bits(unsigned char const* b1\n\t\t, unsigned char const* b2, int n)\n\t{\n\t\tfor (int i = 0; i < n; ++i, ++b1, ++b2)\n\t\t{\n\t\t\tunsigned char a = *b1 ^ *b2;\n\t\t\tif (a == 0) continue;\n\t\t\tint ret = i * 8 + 8;\n\t\t\tfor (; a > 0; a >>= 1) --ret;\n\t\t\treturn ret;\n\t\t}\n\t\treturn n * 8;\n\t}\n\n\t\/\/ returns the number of bits in that differ from the right\n\t\/\/ between the addresses.\n\tint cidr_distance(address const& a1, address const& a2)\n\t{\n\t\tif (a1.is_v4() == a2.is_v4())\n\t\t{\n\t\t\t\/\/ both are v4\n\t\t\taddress_v4::bytes_type b1 = a1.to_v4().to_bytes();\n\t\t\taddress_v4::bytes_type b2 = a2.to_v4().to_bytes();\n\t\t\treturn address_v4::bytes_type::static_size * 8\n\t\t\t\t- common_bits(b1.c_array(), b2.c_array(), b1.size());\n\t\t}\n\t\n\t\taddress_v6::bytes_type b1;\n\t\taddress_v6::bytes_type b2;\n\t\tif (a1.is_v4()) b1 = address_v6::v4_mapped(a1.to_v4()).to_bytes();\n\t\telse b1 = a1.to_v6().to_bytes();\n\t\tif (a2.is_v4()) b2 = address_v6::v4_mapped(a2.to_v4()).to_bytes();\n\t\telse b2 = a2.to_v6().to_bytes();\n\t\treturn address_v6::bytes_type::static_size * 8\n\t\t\t- common_bits(b1.c_array(), b2.c_array(), b1.size());\n\t}\n\n\tbroadcast_socket::broadcast_socket(io_service& ios\n\t\t, udp::endpoint const& multicast_endpoint\n\t\t, receive_handler_t const& handler\n\t\t, bool loopback)\n\t\t: m_multicast_endpoint(multicast_endpoint)\n\t\t, m_on_receive(handler)\n\t{\n\t\tTORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));\n\n\t\tusing namespace asio::ip::multicast;\n\t\n\t\terror_code ec;\n\t\tstd::vector interfaces = enum_net_interfaces(ios, ec);\n\n\t\tif (multicast_endpoint.address().is_v4())\n\t\t\topen_multicast_socket(ios, address_v4::any(), loopback);\n\t\telse\n\t\t\topen_multicast_socket(ios, address_v6::any(), loopback);\n\n\t\tfor (std::vector::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\t\/\/ only broadcast to IPv4 addresses that are not local\n\t\t\tif (!is_local(i->interface_address)) continue;\n\t\t\t\/\/ only multicast on compatible networks\n\t\t\tif (i->interface_address.is_v4() != multicast_endpoint.address().is_v4()) continue;\n\t\t\t\/\/ ignore any loopback interface\n\t\t\tif (is_loopback(i->interface_address)) continue;\n\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \"broadcast socket [ if: \" << i->to_v4().to_string()\n\/\/\t\t\t\t<< \" group: \" << multicast_endpoint.address() << \" ]\" << std::endl;\n#endif\n\t\t\topen_unicast_socket(ios, i->interface_address);\n\t\t}\n\t}\n\n\tvoid broadcast_socket::open_multicast_socket(io_service& ios\n\t\t, address const& addr, bool loopback)\n\t{\n\t\tusing namespace asio::ip::multicast;\n\n\t\terror_code ec;\n\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\tif (addr.is_v4())\n\t\t\ts->open(udp::v4(), ec);\n\t\telse\n\t\t\ts->open(udp::v6(), ec);\n\t\tif (ec) return;\n\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\tif (ec) return;\n\t\ts->bind(udp::endpoint(addr, m_multicast_endpoint.port()), ec);\n\t\tif (ec) return;\n\t\ts->set_option(join_group(m_multicast_endpoint.address()), ec);\n\t\tif (ec) return;\n\t\ts->set_option(hops(255), ec);\n\t\tif (ec) return;\n\t\ts->set_option(enable_loopback(loopback), ec);\n\t\tif (ec) return;\n\t\tm_sockets.push_back(socket_entry(s));\n\t\tsocket_entry& se = m_sockets.back();\n\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n\t}\n\n\tvoid broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)\n\t{\n\t\tusing namespace asio::ip::multicast;\n\t\terror_code ec;\n\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\ts->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);\n\t\tif (ec) return;\n\t\ts->bind(udp::endpoint(addr, 0), ec);\n\t\tif (ec) return;\n\t\tif (addr.is_v4())\n\t\t\ts->set_option(outbound_interface(addr.to_v4()), ec);\n\t\tif (ec) return;\n\t\tm_unicast_sockets.push_back(socket_entry(s));\n\t\tsocket_entry& se = m_unicast_sockets.back();\n\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n\t}\n\n\tvoid broadcast_socket::send(char const* buffer, int size, error_code& ec)\n\t{\n\t\tfor (std::list::iterator i = m_unicast_sockets.begin()\n\t\t\t, end(m_unicast_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\tif (!i->socket) continue;\n\t\t\terror_code e;\n\t\t\ti->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \" sending on \" << i->socket->local_endpoint().address().to_string() << \" to: \" << m_multicast_endpoint << std::endl;\n#endif\n\t\t\tif (e)\n\t\t\t{\n\t\t\t\ti->socket->close(e);\n\t\t\t\ti->socket.reset();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid broadcast_socket::on_receive(socket_entry* s, error_code const& ec\n\t\t, std::size_t bytes_transferred)\n\t{\n\t\tif (ec || bytes_transferred == 0 || !m_on_receive) return;\n\t\tm_on_receive(s->remote, s->buffer, bytes_transferred);\n\t\tif (!s->socket) return;\n\t\ts->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))\n\t\t\t, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));\n\t}\n\n\tvoid broadcast_socket::close()\n\t{\n\t\tstd::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));\n\t\tstd::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));\n\n\t\tm_on_receive.clear();\n\t}\n}\n\n\nfixed bug in broadcast socket (made local service discovery not work)\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n\n#if BOOST_VERSION < 103500\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#include \n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/enum_net.hpp\"\n#include \"libtorrent\/broadcast_socket.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tbool is_local(address const& a)\n\t{\n\t\tif (a.is_v6()) return a.to_v6().is_link_local();\n\t\taddress_v4 a4 = a.to_v4();\n\t\tunsigned long ip = a4.to_ulong();\n\t\treturn ((ip & 0xff000000) == 0x0a000000\n\t\t\t|| (ip & 0xfff00000) == 0xac100000\n\t\t\t|| (ip & 0xffff0000) == 0xc0a80000);\n\t}\n\n\tbool is_loopback(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t return addr.to_v4() == address_v4::loopback();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::loopback();\n\t}\n\n\tbool is_multicast(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4().is_multicast();\n\t\telse\n\t\t\treturn addr.to_v6().is_multicast();\n\t}\n\n\tbool is_any(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4() == address_v4::any();\n\t\telse if (addr.to_v6().is_v4_mapped())\n\t\t\treturn (addr.to_v6().to_v4() == address_v4::any());\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::any();\n\t}\n\n\taddress guess_local_address(io_service& ios)\n\t{\n\t\t\/\/ make a best guess of the interface we're using and its IP\n\t\terror_code ec;\n\t\tstd::vector const& interfaces = enum_net_interfaces(ios, ec);\n\t\taddress ret = address_v4::any();\n\t\tfor (std::vector::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\taddress const& a = i->interface_address;\n\t\t\tif (is_loopback(a)\n\t\t\t\t|| is_multicast(a)\n\t\t\t\t|| is_any(a)) continue;\n\n\t\t\t\/\/ prefer a v4 address, but return a v6 if\n\t\t\t\/\/ there are no v4\n\t\t\tif (a.is_v4()) return a;\n\n\t\t\tif (ret != address_v4::any())\n\t\t\t\tret = a;\n\t\t}\n\t\treturn ret;\n\t}\n\n\t\/\/ count the length of the common bit prefix\n\tint common_bits(unsigned char const* b1\n\t\t, unsigned char const* b2, int n)\n\t{\n\t\tfor (int i = 0; i < n; ++i, ++b1, ++b2)\n\t\t{\n\t\t\tunsigned char a = *b1 ^ *b2;\n\t\t\tif (a == 0) continue;\n\t\t\tint ret = i * 8 + 8;\n\t\t\tfor (; a > 0; a >>= 1) --ret;\n\t\t\treturn ret;\n\t\t}\n\t\treturn n * 8;\n\t}\n\n\t\/\/ returns the number of bits in that differ from the right\n\t\/\/ between the addresses.\n\tint cidr_distance(address const& a1, address const& a2)\n\t{\n\t\tif (a1.is_v4() == a2.is_v4())\n\t\t{\n\t\t\t\/\/ both are v4\n\t\t\taddress_v4::bytes_type b1 = a1.to_v4().to_bytes();\n\t\t\taddress_v4::bytes_type b2 = a2.to_v4().to_bytes();\n\t\t\treturn address_v4::bytes_type::static_size * 8\n\t\t\t\t- common_bits(b1.c_array(), b2.c_array(), b1.size());\n\t\t}\n\t\n\t\taddress_v6::bytes_type b1;\n\t\taddress_v6::bytes_type b2;\n\t\tif (a1.is_v4()) b1 = address_v6::v4_mapped(a1.to_v4()).to_bytes();\n\t\telse b1 = a1.to_v6().to_bytes();\n\t\tif (a2.is_v4()) b2 = address_v6::v4_mapped(a2.to_v4()).to_bytes();\n\t\telse b2 = a2.to_v6().to_bytes();\n\t\treturn address_v6::bytes_type::static_size * 8\n\t\t\t- common_bits(b1.c_array(), b2.c_array(), b1.size());\n\t}\n\n\tbroadcast_socket::broadcast_socket(io_service& ios\n\t\t, udp::endpoint const& multicast_endpoint\n\t\t, receive_handler_t const& handler\n\t\t, bool loopback)\n\t\t: m_multicast_endpoint(multicast_endpoint)\n\t\t, m_on_receive(handler)\n\t{\n\t\tTORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));\n\n\t\tusing namespace asio::ip::multicast;\n\t\n\t\terror_code ec;\n\t\tstd::vector interfaces = enum_net_interfaces(ios, ec);\n\n\t\tif (multicast_endpoint.address().is_v4())\n\t\t\topen_multicast_socket(ios, address_v4::any(), loopback);\n\t\telse\n\t\t\topen_multicast_socket(ios, address_v6::any(), loopback);\n\n\t\tfor (std::vector::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\t\/\/ only broadcast to IPv4 addresses that are not local\n\t\t\tif (is_local(i->interface_address)) continue;\n\t\t\t\/\/ only multicast on compatible networks\n\t\t\tif (i->interface_address.is_v4() != multicast_endpoint.address().is_v4()) continue;\n\t\t\t\/\/ ignore any loopback interface\n\t\t\tif (is_loopback(i->interface_address)) continue;\n\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \"broadcast socket [ if: \" << i->to_v4().to_string()\n\/\/\t\t\t\t<< \" group: \" << multicast_endpoint.address() << \" ]\" << std::endl;\n#endif\n\t\t\topen_unicast_socket(ios, i->interface_address);\n\t\t}\n\t}\n\n\tvoid broadcast_socket::open_multicast_socket(io_service& ios\n\t\t, address const& addr, bool loopback)\n\t{\n\t\tusing namespace asio::ip::multicast;\n\n\t\terror_code ec;\n\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\tif (addr.is_v4())\n\t\t\ts->open(udp::v4(), ec);\n\t\telse\n\t\t\ts->open(udp::v6(), ec);\n\t\tif (ec) return;\n\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\tif (ec) return;\n\t\ts->bind(udp::endpoint(addr, m_multicast_endpoint.port()), ec);\n\t\tif (ec) return;\n\t\ts->set_option(join_group(m_multicast_endpoint.address()), ec);\n\t\tif (ec) return;\n\t\ts->set_option(hops(255), ec);\n\t\tif (ec) return;\n\t\ts->set_option(enable_loopback(loopback), ec);\n\t\tif (ec) return;\n\t\tm_sockets.push_back(socket_entry(s));\n\t\tsocket_entry& se = m_sockets.back();\n\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n\t}\n\n\tvoid broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)\n\t{\n\t\tusing namespace asio::ip::multicast;\n\t\terror_code ec;\n\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\ts->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);\n\t\tif (ec) return;\n\t\ts->bind(udp::endpoint(addr, 0), ec);\n\t\tif (ec) return;\n\t\tif (addr.is_v4())\n\t\t\ts->set_option(outbound_interface(addr.to_v4()), ec);\n\t\tif (ec) return;\n\t\tm_unicast_sockets.push_back(socket_entry(s));\n\t\tsocket_entry& se = m_unicast_sockets.back();\n\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n\t}\n\n\tvoid broadcast_socket::send(char const* buffer, int size, error_code& ec)\n\t{\n\t\tfor (std::list::iterator i = m_unicast_sockets.begin()\n\t\t\t, end(m_unicast_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\tif (!i->socket) continue;\n\t\t\terror_code e;\n\t\t\ti->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \" sending on \" << i->socket->local_endpoint().address().to_string() << \" to: \" << m_multicast_endpoint << std::endl;\n#endif\n\t\t\tif (e)\n\t\t\t{\n\t\t\t\ti->socket->close(e);\n\t\t\t\ti->socket.reset();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid broadcast_socket::on_receive(socket_entry* s, error_code const& ec\n\t\t, std::size_t bytes_transferred)\n\t{\n\t\tif (ec || bytes_transferred == 0 || !m_on_receive) return;\n\t\tm_on_receive(s->remote, s->buffer, bytes_transferred);\n\t\tif (!s->socket) return;\n\t\ts->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))\n\t\t\t, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));\n\t}\n\n\tvoid broadcast_socket::close()\n\t{\n\t\tstd::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));\n\t\tstd::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));\n\n\t\tm_on_receive.clear();\n\t}\n}\n\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/enum_net.hpp\"\n#include \"libtorrent\/broadcast_socket.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tbool is_local(address const& a)\n\t{\n\t\tif (a.is_v6()) return a.to_v6().is_link_local();\n\t\taddress_v4 a4 = a.to_v4();\n\t\tunsigned long ip = a4.to_ulong();\n\t\treturn ((ip & 0xff000000) == 0x0a000000\n\t\t\t|| (ip & 0xfff00000) == 0xac100000\n\t\t\t|| (ip & 0xffff0000) == 0xc0a80000);\n\t}\n\n\tbool is_loopback(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t return addr.to_v4() == address_v4::loopback();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::loopback();\n\t}\n\n\tbool is_multicast(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4().is_multicast();\n\t\telse\n\t\t\treturn addr.to_v6().is_multicast();\n\t}\n\n\tbool is_any(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4() == address_v4::any();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::any();\n\t}\n\n\taddress guess_local_address(asio::io_service& ios)\n\t{\n\t\t\/\/ make a best guess of the interface we're using and its IP\n\t\tasio::error_code ec;\n\t\tstd::vector

const& interfaces = enum_net_interfaces(ios, ec);\n\t\taddress ret = address_v4::any();\n\t\tfor (std::vector
::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\taddress const& a = *i;\n\t\t\tif (is_loopback(a)\n\t\t\t\t|| is_multicast(a)\n\t\t\t\t|| is_any(a)) continue;\n\n\t\t\t\/\/ prefer a v4 address, but return a v6 if\n\t\t\t\/\/ there are no v4\n\t\t\tif (a.is_v4()) return a;\n\n\t\t\tif (ret != address_v4::any())\n\t\t\t\tret = a;\n\t\t}\n\t\treturn ret;\n\t}\n\n\tbroadcast_socket::broadcast_socket(asio::io_service& ios\n\t\t, udp::endpoint const& multicast_endpoint\n\t\t, receive_handler_t const& handler\n\t\t, bool loopback)\n\t\t: m_multicast_endpoint(multicast_endpoint)\n\t\t, m_on_receive(handler)\n\t{\n\t\tTORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));\n\n\t\tusing namespace asio::ip::multicast;\n\t\n\t\tasio::error_code ec;\n\t\tstd::vector
interfaces = enum_net_interfaces(ios, ec);\n\n\t\tfor (std::vector
::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\t\/\/ only broadcast to IPv4 addresses that are not local\n\t\t\tif (!is_local(*i)) continue;\n\t\t\t\/\/ only multicast on compatible networks\n\t\t\tif (i->is_v4() != multicast_endpoint.address().is_v4()) continue;\n\t\t\t\/\/ ignore any loopback interface\n\t\t\tif (is_loopback(*i)) continue;\n\n\t\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\t\tif (i->is_v4())\n\t\t\t{\n\t\t\t\ts->open(udp::v4(), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(join_group(multicast_endpoint.address()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(outbound_interface(i->to_v4()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts->open(udp::v6(), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(join_group(multicast_endpoint.address()), ec);\n\t\t\t\tif (ec) continue;\n\/\/\t\t\t\ts->set_option(outbound_interface(i->to_v6()), ec);\n\/\/\t\t\t\tif (ec) continue;\n\t\t\t}\n\t\t\ts->set_option(hops(255), ec);\n\t\t\tif (ec) continue;\n\t\t\ts->set_option(enable_loopback(loopback), ec);\n\t\t\tif (ec) continue;\n\t\t\tm_sockets.push_back(socket_entry(s));\n\t\t\tsocket_entry& se = m_sockets.back();\n\t\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \"broadcast socket [ if: \" << i->to_v4().to_string()\n\/\/\t\t\t\t<< \" group: \" << multicast_endpoint.address() << \" ]\" << std::endl;\n#endif\n\t\t}\n\t}\n\n\tvoid broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)\n\t{\n\t\tfor (std::list::iterator i = m_sockets.begin()\n\t\t\t, end(m_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\tasio::error_code e;\n\t\t\ti->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \" sending on \" << i->socket->local_endpoint().address().to_string() << std::endl;\n#endif\n\t\t\tif (e) ec = e;\n\t\t}\n\t}\n\n\tvoid broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec\n\t\t, std::size_t bytes_transferred)\n\t{\n\t\tif (ec || bytes_transferred == 0) return;\n\t\tm_on_receive(s->remote, s->buffer, bytes_transferred);\n\t\ts->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))\n\t\t\t, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));\n\t}\n\n\tvoid broadcast_socket::close()\n\t{\n\t\tm_on_receive.clear();\n\n\t\tfor (std::list::iterator i = m_sockets.begin()\n\t\t\t, end(m_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\ti->socket->close();\n\t\t}\n\t}\n}\n\n\nfixed potential call to empty boost.function\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/enum_net.hpp\"\n#include \"libtorrent\/broadcast_socket.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tbool is_local(address const& a)\n\t{\n\t\tif (a.is_v6()) return a.to_v6().is_link_local();\n\t\taddress_v4 a4 = a.to_v4();\n\t\tunsigned long ip = a4.to_ulong();\n\t\treturn ((ip & 0xff000000) == 0x0a000000\n\t\t\t|| (ip & 0xfff00000) == 0xac100000\n\t\t\t|| (ip & 0xffff0000) == 0xc0a80000);\n\t}\n\n\tbool is_loopback(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t return addr.to_v4() == address_v4::loopback();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::loopback();\n\t}\n\n\tbool is_multicast(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4().is_multicast();\n\t\telse\n\t\t\treturn addr.to_v6().is_multicast();\n\t}\n\n\tbool is_any(address const& addr)\n\t{\n\t\tif (addr.is_v4())\n\t\t\treturn addr.to_v4() == address_v4::any();\n\t\telse\n\t\t\treturn addr.to_v6() == address_v6::any();\n\t}\n\n\taddress guess_local_address(asio::io_service& ios)\n\t{\n\t\t\/\/ make a best guess of the interface we're using and its IP\n\t\tasio::error_code ec;\n\t\tstd::vector
const& interfaces = enum_net_interfaces(ios, ec);\n\t\taddress ret = address_v4::any();\n\t\tfor (std::vector
::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\taddress const& a = *i;\n\t\t\tif (is_loopback(a)\n\t\t\t\t|| is_multicast(a)\n\t\t\t\t|| is_any(a)) continue;\n\n\t\t\t\/\/ prefer a v4 address, but return a v6 if\n\t\t\t\/\/ there are no v4\n\t\t\tif (a.is_v4()) return a;\n\n\t\t\tif (ret != address_v4::any())\n\t\t\t\tret = a;\n\t\t}\n\t\treturn ret;\n\t}\n\n\tbroadcast_socket::broadcast_socket(asio::io_service& ios\n\t\t, udp::endpoint const& multicast_endpoint\n\t\t, receive_handler_t const& handler\n\t\t, bool loopback)\n\t\t: m_multicast_endpoint(multicast_endpoint)\n\t\t, m_on_receive(handler)\n\t{\n\t\tTORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));\n\n\t\tusing namespace asio::ip::multicast;\n\t\n\t\tasio::error_code ec;\n\t\tstd::vector
interfaces = enum_net_interfaces(ios, ec);\n\n\t\tfor (std::vector
::const_iterator i = interfaces.begin()\n\t\t\t, end(interfaces.end()); i != end; ++i)\n\t\t{\n\t\t\t\/\/ only broadcast to IPv4 addresses that are not local\n\t\t\tif (!is_local(*i)) continue;\n\t\t\t\/\/ only multicast on compatible networks\n\t\t\tif (i->is_v4() != multicast_endpoint.address().is_v4()) continue;\n\t\t\t\/\/ ignore any loopback interface\n\t\t\tif (is_loopback(*i)) continue;\n\n\t\t\tboost::shared_ptr s(new datagram_socket(ios));\n\t\t\tif (i->is_v4())\n\t\t\t{\n\t\t\t\ts->open(udp::v4(), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(join_group(multicast_endpoint.address()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(outbound_interface(i->to_v4()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts->open(udp::v6(), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(datagram_socket::reuse_address(true), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec);\n\t\t\t\tif (ec) continue;\n\t\t\t\ts->set_option(join_group(multicast_endpoint.address()), ec);\n\t\t\t\tif (ec) continue;\n\/\/\t\t\t\ts->set_option(outbound_interface(i->to_v6()), ec);\n\/\/\t\t\t\tif (ec) continue;\n\t\t\t}\n\t\t\ts->set_option(hops(255), ec);\n\t\t\tif (ec) continue;\n\t\t\ts->set_option(enable_loopback(loopback), ec);\n\t\t\tif (ec) continue;\n\t\t\tm_sockets.push_back(socket_entry(s));\n\t\t\tsocket_entry& se = m_sockets.back();\n\t\t\ts->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))\n\t\t\t\t, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \"broadcast socket [ if: \" << i->to_v4().to_string()\n\/\/\t\t\t\t<< \" group: \" << multicast_endpoint.address() << \" ]\" << std::endl;\n#endif\n\t\t}\n\t}\n\n\tvoid broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)\n\t{\n\t\tfor (std::list::iterator i = m_sockets.begin()\n\t\t\t, end(m_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\tasio::error_code e;\n\t\t\ti->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);\n#ifndef NDEBUG\n\/\/\t\t\tstd::cerr << \" sending on \" << i->socket->local_endpoint().address().to_string() << std::endl;\n#endif\n\t\t\tif (e) ec = e;\n\t\t}\n\t}\n\n\tvoid broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec\n\t\t, std::size_t bytes_transferred)\n\t{\n\t\tif (ec || bytes_transferred == 0 || !m_on_receive) return;\n\t\tm_on_receive(s->remote, s->buffer, bytes_transferred);\n\t\ts->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))\n\t\t\t, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));\n\t}\n\n\tvoid broadcast_socket::close()\n\t{\n\t\tm_on_receive.clear();\n\n\t\tfor (std::list::iterator i = m_sockets.begin()\n\t\t\t, end(m_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\ti->socket->close();\n\t\t}\n\t}\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 nyorain\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file LICENSE or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\n\/\/\/ file Contains the Span template class for not-owned contigous ranges.\n\n#pragma once\n\n#ifndef NYTL_INCLUDE_SPAN\n#define NYTL_INCLUDE_SPAN\n\n#include \/\/ nytl::Span default template parameter\n#include \/\/ nytl::constants::dynamicSize\n\n#include \/\/ std::size_t\n#include \/\/ std::out_of_range\n#include \/\/ std::array\n\nnamespace nytl {\nnamespace detail {\n\ttemplate struct ValidContainerT;\n\ttemplate using ValidContainer = typename ValidContainerT::type;\n} \/\/ namespace nytl::detail\n\n\/\/\/ The underlaying storage type of spans that is specialized for dyanmic size.\ntemplate struct SpanStorage;\n\n\/\/\/ \\brief Describes a contigous, non-owned range of elements of type 'T'.\n\/\/\/ \\details Spans can be used to pass sequences of elements around in a lightweight manner.\n\/\/\/ Its main use are function parameters sine instead of a std::vector it will not allocate\n\/\/\/ any memory or copy any elements but instead just reference them.\n\/\/\/ \\tparam T The type the range is defined over. Use const types for non-mutable ranges.\n\/\/\/ \\tparam N The size of the range. If not known at compile\n\/\/\/ time, use nytl::constants::dynamicSize (also defaulted to dynamicSize).\n\/\/\/\n\/\/\/ Some examples below. Note that Spans must be used carefully outside of temporary\n\/\/\/ expressions since they are only valid as long the object they reference is valid.\n\/\/\/ ```cpp\n\/\/\/ void foo(nytl::Span names); \/\/ takes dyanmic amount of strings, might modify it\n\/\/\/ void bar(nytl::Span names); \/\/ takes exactly 3 const strings\n\/\/\/ void baz(nytl::Span names); \/\/ takes exactly 5 const strings\n\/\/\/\n\/\/\/ int main()\n\/\/\/ {\n\/\/\/\t\tstd::array namesArray {\"foo\", \"bar\", \"baz\"};\n\/\/\/\t\tfoo(namesArray); \/\/ works\n\/\/\/ \tbar(namesArray); \/\/ works\n\/\/\/\t\tbaz(namesArray); \/\/ will throw std::logic_error since baz requires exactly 5 strings\n\/\/\/\n\/\/\/\t\tstd::vector namesVector {\"foo\", \"bar\", \"baz\", \"abz\", \"bla\"};\n\/\/\/\t\tfoo(namesVector); \/\/ works\n\/\/\/\t\tbar(namesVector); \/\/ will throw std::logic_error since bar requires exactly 3 strings\n\/\/\/\t\tbaz(namesVector); \/\/ works\n\/\/\/\n\/\/\/ \t\/\/ If we only want the first 3 elements from namesVector as range we can do it like this\n\/\/\/\t\tbar({namesVector.data(), 3}); \/\/ works, takes the first 3 elements\n\/\/\/\t\tfoo({*namesVector.data(), 4}); \/\/ we can also use references\n\/\/\/\n\/\/\/\t\t\/\/ careful when using span outside of temporary expressions\n\/\/\/\t\tauto span = nytl::Span(std::vector{4, 1, 2, 0});\n\/\/\/ \t\/\/ std::cout << span[0] << \"\\n\"; \/\/ undefined behaviour!\n\/\/\/ }\n\/\/\/\n\/\/\/ void foo(nytl::Span names)\n\/\/\/ {\n\/\/\/\t\t\/\/ Some usage possibilities for span.\n\/\/\/\/\t\/\/ The main usage is iterating over it:\n\/\/\/\t\tfor(auto& name : names)\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\t\/\/ We might alternatively do this with a traditional for loop\n\/\/\/\t\tfor(auto i = 0u; i < names.size(); ++i)\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\t\/\/ In this case we have a span of std::string, not const std::string,\n\/\/\/\t\t\/\/ therefore we might also change it. This will change the names in the actual\n\/\/\/\t\t\/\/ sequence this span references. Usually nytl::Span is used when the\n\/\/\/\t\t\/\/ span is only read\n\/\/\/\t\tif(!names.empty()) {\n\/\/\/\t\t\tnames.front() = \"first name\";\n\/\/\/\t\t\tnames.back() = \"last name\";\n\/\/\/\t\t}\n\/\/\/\n\/\/\/\t\t\/\/ A span can additionally be sliced into a subspan. This can either be\n\/\/\/\t\t\/\/ done with a size known at compile time (which will result in a fixed-size span)\n\/\/\/\t\t\/\/ or dynamically for a dynamic-sized span.\n\/\/\/\t\tif(names.size() <= 2) return;\n\/\/\/\t\tfor(auto& name : names.slice(2, names.size() - 2)) \/\/ output everything but the first two\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\tfor(auto& name : names.slice<2>(0)) \/\/ output only the first two names\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/ }\n\/\/\/ ```\ntemplate\nclass Span : public SpanStorage {\npublic:\n\tusing Value = T;\n\tusing Iterator = T*;\n\tusing ReverseIterator = std::reverse_iterator;\n\tusing Reference = T&;\n\tusing Pointer = T*;\n\tusing Difference = std::ptrdiff_t;\n\tusing Size = std::size_t;\n\npublic:\n\tusing SpanStorage::SpanStorage;\n\tconstexpr Span() noexcept = default;\n\tconstexpr Span(std::nullptr_t) noexcept : Span(nullptr, 0) {}\n\n\ttemplate>\n\tconstexpr Span(C& c) : Span(c.data(), c.size()) {}\n\n\ttemplate, std::size_t S = C::size()>\n\tconstexpr Span(C& c) : Span(c.data()) {}\n\n\tconstexpr Pointer data() const noexcept { return this->data_; }\n\tconstexpr Size size() const noexcept { return this->size_; }\n\tconstexpr bool empty() const noexcept { return size() == 0; }\n\n\tconstexpr Iterator begin() const noexcept { return data(); }\n\tconstexpr Iterator end() const noexcept { return data() + size(); }\n\n\tconstexpr ReverseIterator rbegin() const noexcept { return {end()}; }\n\tconstexpr ReverseIterator rend() const noexcept { return {begin()}; }\n\n\tconstexpr Reference operator[](Size i) const noexcept { return *(data() + i); }\n\tconstexpr Reference at(Size i) const { checkThrow(i); return data()[i]; }\n\n\tconstexpr Reference front() const noexcept { return *data(); }\n\tconstexpr Reference back() const noexcept { return *(data() + size() - 1); }\n\n\tconstexpr Span slice(Size pos, Size size) const { return {data() + pos, size}; }\n\ttemplate constexpr Span slice(Size pos) const { return {data() + pos}; }\n\nprotected:\n\tvoid checkThrow(Size i) const { if(i >= size()) throw std::out_of_range(\"nytl::Span::at\"); }\n};\n\n\/\/ Default SpanStorage implementation for compile-time size\ntemplate\nstruct SpanStorage {\n\tconstexpr SpanStorage() noexcept = default;\n\tconstexpr SpanStorage(T* pointer, std::size_t size = N) : data_(pointer)\n\t{\n\t\tif(size != N) throw std::logic_error(\"nytl::Span:: invalid size\");\n\t\tif(!pointer && size != 0) throw std::logic_error(\"nytl::Span:: invalid data\");\n\t}\n\tconstexpr SpanStorage(T& ref, std::size_t size = N) : SpanStorage(&ref, size) {}\n\tconstexpr SpanStorage(T (&arr)[N]) : SpanStorage(arr, N) {}\n\n\tT* data_;\n\tconstexpr static auto size_ = N;\n};\n\n\/\/ SpanStorage specialization for runtime size. Stored an extra size value.\ntemplate\nstruct SpanStorage {\n\tconstexpr SpanStorage() noexcept = default;\n\tconstexpr SpanStorage(T* pointer, std::size_t size) : data_(pointer), size_(size)\n\t{\n\t\tif(!pointer && size != 0) throw std::logic_error(\"nytl::Span:: invalid data\");\n\t}\n\tconstexpr SpanStorage(T& ref, std::size_t size) : SpanStorage(&ref, size) {}\n\ttemplate constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}\n\n\tT* data_;\n\tstd::size_t size_;\n};\n\nnamespace detail {\n\n\/\/ Returns whether 'C' is a valid container to construct a Span from\ntemplate\nstruct ValidContainerT().data()),\n\t\t\tT*\n\t\t>::value &&\n\t\tstd::is_convertible<\n\t\t\tdecltype(std::declval().size()),\n\t\t\tstd::size_t\n\t\t>::value\n\t>::type\n> { using type = void; };\n\n} \/\/ namespace detail\n} \/\/ namespace nytl\n\n#endif \/\/ header guard\nUpdate span.hpp\/\/ Copyright (c) 2017 nyorain\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ See accompanying file LICENSE or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\n\/\/\/ file Contains the Span template class for not-owned contigous ranges.\n\n#pragma once\n\n#ifndef NYTL_INCLUDE_SPAN\n#define NYTL_INCLUDE_SPAN\n\n#include \/\/ nytl::Span default template parameter\n#include \/\/ nytl::constants::dynamicSize\n\n#include \/\/ std::size_t\n#include \/\/ std::out_of_range\n#include \/\/ std::array\n\nnamespace nytl {\nnamespace detail {\n\ttemplate struct ValidContainerT;\n\ttemplate using ValidContainer = typename ValidContainerT::type;\n} \/\/ namespace nytl::detail\n\n\/\/\/ The underlaying storage type of spans that is specialized for dyanmic size.\ntemplate struct SpanStorage;\n\n\/\/\/ \\brief Describes a contigous, non-owned range of elements of type 'T'.\n\/\/\/ \\details Spans can be used to pass sequences of elements around in a lightweight manner.\n\/\/\/ Its main use are function parameters sine instead of a std::vector it will not allocate\n\/\/\/ any memory or copy any elements but instead just reference them.\n\/\/\/ \\tparam T The type the range is defined over. Use const types for non-mutable ranges.\n\/\/\/ \\tparam N The size of the range. If not known at compile\n\/\/\/ time, use nytl::constants::dynamicSize (also defaulted to dynamicSize).\n\/\/\/\n\/\/\/ Some examples below. Note that Spans must be used carefully outside of temporary\n\/\/\/ expressions since they are only valid as long the object they reference is valid.\n\/\/\/ ```cpp\n\/\/\/ void foo(nytl::Span names); \/\/ takes dyanmic amount of strings, might modify it\n\/\/\/ void bar(nytl::Span names); \/\/ takes exactly 3 const strings\n\/\/\/ void baz(nytl::Span names); \/\/ takes exactly 5 const strings\n\/\/\/\n\/\/\/ int main()\n\/\/\/ {\n\/\/\/\t\tstd::array namesArray {\"foo\", \"bar\", \"baz\"};\n\/\/\/\t\tfoo(namesArray); \/\/ works\n\/\/\/ \tbar(namesArray); \/\/ works\n\/\/\/\t\tbaz(namesArray); \/\/ will throw std::logic_error since baz requires exactly 5 strings\n\/\/\/\n\/\/\/\t\tstd::vector namesVector {\"foo\", \"bar\", \"baz\", \"abz\", \"bla\"};\n\/\/\/\t\tfoo(namesVector); \/\/ works\n\/\/\/\t\tbar(namesVector); \/\/ will throw std::logic_error since bar requires exactly 3 strings\n\/\/\/\t\tbaz(namesVector); \/\/ works\n\/\/\/\n\/\/\/ \t\/\/ If we only want the first 3 elements from namesVector as range we can do it like this\n\/\/\/\t\tbar({namesVector.data(), 3}); \/\/ works, takes the first 3 elements\n\/\/\/\t\tfoo({*namesVector.data(), 4}); \/\/ we can also use references\n\/\/\/\n\/\/\/\t\t\/\/ careful when using span outside of temporary expressions\n\/\/\/\t\tauto span = nytl::Span(std::vector{4, 1, 2, 0});\n\/\/\/ \t\/\/ std::cout << span[0] << \"\\n\"; \/\/ undefined behaviour!\n\/\/\/ }\n\/\/\/\n\/\/\/ void foo(nytl::Span names)\n\/\/\/ {\n\/\/\/\t\t\/\/ Some usage possibilities for span.\n\/\/\/\/\t\/\/ The main usage is iterating over it:\n\/\/\/\t\tfor(auto& name : names)\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\t\/\/ We might alternatively do this with a traditional for loop\n\/\/\/\t\tfor(auto i = 0u; i < names.size(); ++i)\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\t\/\/ In this case we have a span of std::string, not const std::string,\n\/\/\/\t\t\/\/ therefore we might also change it. This will change the names in the actual\n\/\/\/\t\t\/\/ sequence this span references. Usually nytl::Span is used when the\n\/\/\/\t\t\/\/ span is only read\n\/\/\/\t\tif(!names.empty()) {\n\/\/\/\t\t\tnames.front() = \"first name\";\n\/\/\/\t\t\tnames.back() = \"last name\";\n\/\/\/\t\t}\n\/\/\/\n\/\/\/\t\t\/\/ A span can additionally be sliced into a subspan. This can either be\n\/\/\/\t\t\/\/ done with a size known at compile time (which will result in a fixed-size span)\n\/\/\/\t\t\/\/ or dynamically for a dynamic-sized span.\n\/\/\/\t\tif(names.size() <= 2) return;\n\/\/\/\t\tfor(auto& name : names.slice(2, names.size() - 2)) \/\/ output everything but the first two\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/\n\/\/\/\t\tfor(auto& name : names.slice<2>(0)) \/\/ output only the first two names\n\/\/\/\t\t\tstd::cout << name << \"\\n\";\n\/\/\/ }\n\/\/\/ ```\ntemplate\nclass Span : public SpanStorage {\npublic:\n\tusing Value = T;\n\tusing Iterator = T*;\n\tusing ReverseIterator = std::reverse_iterator;\n\tusing Reference = T&;\n\tusing Pointer = T*;\n\tusing Difference = std::ptrdiff_t;\n\tusing Size = std::size_t;\n\npublic:\n\tusing SpanStorage::SpanStorage;\n\tconstexpr Span() noexcept = default;\n\tconstexpr Span(std::nullptr_t) noexcept : Span(nullptr, 0) {}\n\n\ttemplate>\n\tconstexpr Span(C& c) : Span(c.data(), c.size()) {}\n\n\ttemplate, std::size_t S = C::size()>\n\tconstexpr Span(C& c) : Span(c.data()) {}\n\n\tconstexpr Pointer data() const noexcept { return this->data_; }\n\tconstexpr Size size() const noexcept { return this->size_; }\n\tconstexpr bool empty() const noexcept { return size() == 0; }\n\n\tconstexpr Iterator begin() const noexcept { return data(); }\n\tconstexpr Iterator end() const noexcept { return data() + size(); }\n\n\tconstexpr ReverseIterator rbegin() const noexcept { return {end()}; }\n\tconstexpr ReverseIterator rend() const noexcept { return {begin()}; }\n\n\tconstexpr Reference operator[](Size i) const noexcept { return *(data() + i); }\n\tconstexpr Reference at(Size i) const { checkThrow(i); return data()[i]; }\n\n\tconstexpr Reference front() const noexcept { return *data(); }\n\tconstexpr Reference back() const noexcept { return *(data() + size() - 1); }\n\n\tconstexpr Span slice(Size pos, Size size) const { return {data() + pos, size}; }\n\ttemplate constexpr Span slice(Size pos) const { return {data() + pos}; }\n\nprotected:\n\tvoid checkThrow(Size i) const { if(i >= size()) throw std::out_of_range(\"nytl::Span::at\"); }\n};\n\n\/\/ Default SpanStorage implementation for compile-time size\ntemplate\nstruct SpanStorage {\n\tconstexpr SpanStorage() noexcept = default;\n\tconstexpr SpanStorage(T* pointer, std::size_t size = N) : data_(pointer)\n\t{\n\t\tif(size != N) throw std::logic_error(\"nytl::Span:: invalid size\");\n\t\tif(!pointer && size != 0) throw std::logic_error(\"nytl::Span:: invalid data\");\n\t}\n\tconstexpr SpanStorage(T& ref, std::size_t size = N) : SpanStorage(&ref, size) {}\n\tconstexpr SpanStorage(T (&arr)[N]) : SpanStorage(arr, N) {}\n\n\tT* data_;\n\tconstexpr static auto size_ = N;\n};\n\n\/\/ SpanStorage specialization for runtime size. Stored an extra size value.\ntemplate\nstruct SpanStorage {\n\tconstexpr SpanStorage() noexcept = default;\n\tconstexpr SpanStorage(T* pointer, std::size_t size = 1) : data_(pointer), size_(size)\n\t{\n\t\tif(!pointer && size != 0) throw std::logic_error(\"nytl::Span:: invalid data\");\n\t}\n\tconstexpr SpanStorage(T& ref, std::size_t size = 1) : SpanStorage(&ref, size) {}\n\ttemplate constexpr SpanStorage(T (&arr)[S]) : SpanStorage(arr, S) {}\n\n\tT* data_;\n\tstd::size_t size_;\n};\n\nnamespace detail {\n\n\/\/ Returns whether 'C' is a valid container to construct a Span from\ntemplate\nstruct ValidContainerT().data()),\n\t\t\tT*\n\t\t>::value &&\n\t\tstd::is_convertible<\n\t\t\tdecltype(std::declval().size()),\n\t\t\tstd::size_t\n\t\t>::value\n\t>::type\n> { using type = void; };\n\n} \/\/ namespace detail\n} \/\/ namespace nytl\n\n#endif \/\/ header guard\n<|endoftext|>"} {"text":"#include \n\n#include \"..\/request.hh\"\n\nnamespace mimosa\n{\n namespace http\n {\n namespace\n {\n#define METHOD_TEST(Meth) \\\n TEST(RequestParser, Meth##Simple) \\\n { \\\n char str[] = #Meth \" \/ HTTP\/1.0\\r\\n\\r\\n\"; \\\n Request rq; \\\n EXPECT_EQ(1, rq.parse(str, sizeof (str))); \\\n }\n\n METHOD_TEST(GET)\n METHOD_TEST(HEAD)\n METHOD_TEST(PUT)\n METHOD_TEST(POST)\n METHOD_TEST(DELETE)\n METHOD_TEST(TRACE)\n METHOD_TEST(OPTIONS)\n METHOD_TEST(CONNECT)\n METHOD_TEST(PATCH)\n\n TEST(RequestParser, CheckFields)\n {\n char str[] = \"GET \/ HTTP\/1.0\\r\\n\"\n \"Host: www.toto.com\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Content-Length: 854\\r\\n\"\n \"Content-Type: text\/*\\r\\n\"\n \"Referer: http:\/\/tutu.com\/hoho%34\/?tutu=tata;#anchor\\r\\n\"\n \"User-Agent: TomBoy (esapce compatible)\\r\\n\"\n \"SomeKey: SomeValue\\r\\n\"\n \"Cookie: attr0; attr01; attr02; attr1=value1; attr2=value2;\"\n \" attr3; attr4=value4; attr5=\\\"xvalue\\\\o\\\\\\\"\\\"\\r\\n\"\n \"Cookie: attr6 = value6 ; attr7 ; attr8 = \\\" value 8 \\\" \\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n EXPECT_EQ(rq.host(), \"www.toto.com\");\n EXPECT_EQ(rq.keepAlive(), true);\n EXPECT_EQ(rq.port(), 80);\n EXPECT_EQ(rq.contentLength(), 854);\n EXPECT_EQ(rq.contentType(), \"text\/*\");\n EXPECT_EQ(rq.referrer(), \"http:\/\/tutu.com\/hoho%34\/?tutu=tata;#anchor\");\n EXPECT_EQ(rq.userAgent(), \"TomBoy (esapce compatible)\");\n\n auto it = rq.cookies().find(\"attr1\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"value1\");\n it = rq.cookies().find(\"attr5\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, std::string(\"xvalueo\\\"\"));\n\n it = rq.unparsedHeaders().find(\"SomeKey\");\n EXPECT_NE(it, rq.unparsedHeaders().end());\n if (it != rq.unparsedHeaders().end())\n EXPECT_EQ(it->second, \"SomeValue\");\n }\n\n TEST(RequestParser, PostHeader)\n {\n const char str[] = \"POST \/post-echo HTTP\/1.1\\r\\n\"\n \"Host: localhost:4242\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:6.0) Gecko\/20100101 Firefox\/6.0\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: http:\/\/localhost:4242\/post-echo\\r\\n\"\n \"Cache-Control: max-age=0\\r\\n\"\n \"Content-Type: application\/x-www-form-urlencoded\\r\\n\"\n \"Content-Length: 29\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n EXPECT_EQ(rq.port(), 4242);\n }\n\n TEST(RequestParser, EmptyCookie)\n {\n const char str[] = \"GET \/ HTTP\/1.1\\r\\n\"\n \"Cookie: key=\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, 2EmptyCookie)\n {\n const char str[] = \"GET \/ HTTP\/1.1\\r\\n\"\n \"Cookie: key=; val=\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, Fail1)\n {\n const char str[] = \"POST \/login HTTP\/1.1\\r\\n\"\n \"Host: localhost:19042\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko\/20100101 Firefox\/9.0.1\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: UTF-8,*\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: https:\/\/localhost:19042\/login\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Cache-Control: max-age=0\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, Fail2)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Host: localhost:19042\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko\/20100101 Firefox\/9.0.1\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: UTF-8,*\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: https:\/\/localhost:19042\/login\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Content-Type: application\/x-www-form-urlencoded\\r\\n\"\n \"Content-Length: 38\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n ASSERT_EQ(38, rq.contentLength());\n }\n\n TEST(RequestParser, ContentLength1)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Content-Length: 38\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n ASSERT_EQ(38, rq.contentLength());\n }\n\n TEST(RequestParser, HardCookie1)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Cookie: __utma=172764660.1465859375.1319666592.1320071393.1323170743.5; __utmz=172764660.1320071393.4.4.utmcsr=portail.free.fr|utmccn=(referral)|utmcmd=referral|utmcct=\/\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n }\n }\n}\nimprove http test suite#include \n\n#include \"..\/request.hh\"\n\nnamespace mimosa\n{\n namespace http\n {\n namespace\n {\n#define METHOD_TEST(Meth) \\\n TEST(RequestParser, Meth##Simple) \\\n { \\\n char str[] = #Meth \" \/ HTTP\/1.0\\r\\n\\r\\n\"; \\\n Request rq; \\\n EXPECT_EQ(1, rq.parse(str, sizeof (str))); \\\n }\n\n METHOD_TEST(GET)\n METHOD_TEST(HEAD)\n METHOD_TEST(PUT)\n METHOD_TEST(POST)\n METHOD_TEST(DELETE)\n METHOD_TEST(TRACE)\n METHOD_TEST(OPTIONS)\n METHOD_TEST(CONNECT)\n METHOD_TEST(PATCH)\n\n TEST(RequestParser, CheckFields)\n {\n char str[] = \"GET \/ HTTP\/1.0\\r\\n\"\n \"Host: www.toto.com\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Content-Length: 854\\r\\n\"\n \"Content-Type: text\/*\\r\\n\"\n \"Referer: http:\/\/tutu.com\/hoho%34\/?tutu=tata;#anchor\\r\\n\"\n \"User-Agent: TomBoy (esapce compatible)\\r\\n\"\n \"SomeKey: SomeValue\\r\\n\"\n \"Cookie: attr0; attr01; attr02; attr1=value1; attr2=value2;\"\n \" attr3; attr4=value4; attr5=\\\"xvalue\\\\o\\\\\\\"\\\"\\r\\n\"\n \"Cookie: attr6 = value6 ; attr7 ; attr8 = \\\" value 8 \\\" \\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n EXPECT_EQ(rq.host(), \"www.toto.com\");\n EXPECT_EQ(rq.keepAlive(), true);\n EXPECT_EQ(rq.port(), 80);\n EXPECT_EQ(rq.contentLength(), 854);\n EXPECT_EQ(rq.contentType(), \"text\/*\");\n EXPECT_EQ(rq.referrer(), \"http:\/\/tutu.com\/hoho%34\/?tutu=tata;#anchor\");\n EXPECT_EQ(rq.userAgent(), \"TomBoy (esapce compatible)\");\n\n auto it = rq.cookies().find(\"attr0\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"\");\n\n it = rq.cookies().find(\"attr01\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"\");\n\n it = rq.cookies().find(\"attr1\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"value1\");\n\n it = rq.cookies().find(\"attr2\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"value2\");\n\n it = rq.cookies().find(\"attr5\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, std::string(\"xvalueo\\\"\"));\n\n it = rq.unparsedHeaders().find(\"SomeKey\");\n EXPECT_NE(it, rq.unparsedHeaders().end());\n if (it != rq.unparsedHeaders().end())\n EXPECT_EQ(it->second, \"SomeValue\");\n }\n\n TEST(RequestParser, PostHeader)\n {\n const char str[] = \"POST \/post-echo HTTP\/1.1\\r\\n\"\n \"Host: localhost:4242\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:6.0) Gecko\/20100101 Firefox\/6.0\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: http:\/\/localhost:4242\/post-echo\\r\\n\"\n \"Cache-Control: max-age=0\\r\\n\"\n \"Content-Type: application\/x-www-form-urlencoded\\r\\n\"\n \"Content-Length: 29\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n EXPECT_EQ(rq.port(), 4242);\n }\n\n TEST(RequestParser, EmptyCookie)\n {\n const char str[] = \"GET \/ HTTP\/1.1\\r\\n\"\n \"Cookie: key=\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, 2EmptyCookie)\n {\n const char str[] = \"GET \/ HTTP\/1.1\\r\\n\"\n \"Cookie: key=; val=\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, Fail1)\n {\n const char str[] = \"POST \/login HTTP\/1.1\\r\\n\"\n \"Host: localhost:19042\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko\/20100101 Firefox\/9.0.1\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: UTF-8,*\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: https:\/\/localhost:19042\/login\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Cache-Control: max-age=0\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, Fail2)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Host: localhost:19042\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko\/20100101 Firefox\/9.0.1\\r\\n\"\n \"Accept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8\\r\\n\"\n \"Accept-Language: en,fr;q=0.5\\r\\n\"\n \"Accept-Encoding: gzip, deflate\\r\\n\"\n \"Accept-Charset: UTF-8,*\\r\\n\"\n \"DNT: 1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Referer: https:\/\/localhost:19042\/login\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Content-Type: application\/x-www-form-urlencoded\\r\\n\"\n \"Content-Length: 38\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n ASSERT_EQ(38, rq.contentLength());\n }\n\n TEST(RequestParser, ContentLength1)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Cookie: login=; auth=\\r\\n\"\n \"Content-Length: 38\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n ASSERT_EQ(38, rq.contentLength());\n }\n\n TEST(RequestParser, HardCookie1)\n {\n const char str[] =\n \"POST \/login HTTP\/1.1\\r\\n\"\n \"Cookie: __utma=172764660.1465859375.1319666592.1320071393.1323170743.5; __utmz=172764660.1320071393.4.4.utmcsr=portail.free.fr|utmccn=(referral)|utmcmd=referral|utmcct=\/\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n }\n\n TEST(RequestParser, Cookie1)\n {\n const char str[] =\n \"GET \/favicon.ico HTTP\/1.1\\r\\n\"\n \"Host: localhost:19042\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Accept: *\/*\\r\\n\"\n \"User-Agent: Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/535.19 (KHTML, like Gecko) Chrome\/18.0.1025.162 Safari\/535.19\\r\\n\"\n \"Accept-Encoding: gzip,deflate,sdch\\r\\n\"\n \"Cookie: login=abique; auth=1fc8f6730ca6349face3c667bb2cb71037cb3e90b85149fbc32963a2d1cd6d72\\r\\n\"\n \"Accept-Language: en-US,en;q=0.8\\r\\n\"\n \"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\\r\\n\"\n \"\\r\\n\";\n Request rq;\n ASSERT_EQ(true, rq.parse(str, sizeof (str)));\n\n auto it = rq.cookies().find(\"login\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"abique\");\n\n it = rq.cookies().find(\"auth\");\n EXPECT_NE(it, rq.cookies().end());\n if (it != rq.cookies().end())\n EXPECT_EQ(it->second, \"1fc8f6730ca6349face3c667bb2cb71037cb3e90b85149fbc32963a2d1cd6d72\");\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Teng -- a general purpose templating engine.\n * Copyright (C) 2004 Seznam.cz, a.s.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Seznam.cz, a.s.\n * Naskove 1, Praha 5, 15000, Czech Republic\n * http:\/\/www.seznam.cz, mailto:teng@firma.seznam.cz\n *\n * $Id: tengcontenttype.cc,v 1.3 2005-01-02 16:32:16 vasek Exp $\n *\n * DESCRIPTION\n * Teng language descriptor -- implementation.\n *\n * AUTHORS\n * Vaclav Blazek \n *\n * HISTORY\n * 2003-09-24 (vasek)\n * Created.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"tengcontenttype.h\"\n\nusing namespace std;\n\nusing namespace Teng;\n\nnamespace {\n map *descriptors = 0;\n vector *descriptorIndex = 0;\n\n ContentType_t::Descriptor_t *unknown = 0;\n}\n\nContentType_t::ContentType_t()\n : lineComment(), blockComment(), escapes(),\n unescaper()\n{\n \/\/ set escape bitmap to all -1 (character not escaped)\n int *end = escapeBitmap + 256;\n int *i = escapeBitmap;\n while (i != end) *i++ = -1;\n \/\/ create empty automaton\n unescaper.push_back(pair(0, 0));\n}\n\nint ContentType_t::addEscape(unsigned char c, const string &escape) {\n \/\/ if escape already present in bitmap make it error\n if (escapeBitmap[c] != -1) return -1;\n \/\/ add escape entry\n escapes.push_back(pair(c, escape));\n \/\/ update entry in escape bitmap\n return escapeBitmap[c] = escapes.size() - 1;\n}\n\nstring ContentType_t::escape(const string &src) const {\n \/\/ output string\n string dest;\n dest.reserve(src.length());\n\n \/\/ run through input string\n for (string::const_iterator isrc = src.begin();\n isrc != src.end(); ++isrc) {\n \/\/ find entry in bitmap\n int pos = escapeBitmap[static_cast(*isrc)];\n \/\/ if position is negative pass source character to output\n if (pos < 0) dest.push_back(*isrc);\n \/\/ else append escape sequence\n else dest.append(escapes[pos].second);\n }\n \/\/ return output\n return dest;\n}\n\nstring ContentType_t::unescape(const string &src) const {\n \/\/ output string\n string dest;\n dest.reserve(src.length());\n\n \/\/ run through input string\n for (string::const_iterator isrc = src.begin();\n isrc != src.end(); ) {\n \/\/ help iterator\n string::const_iterator bsrc = isrc;\n \/\/ index in automaton\n int state = 0;\n \/\/ run through remaining characters\n for (; bsrc != src.end(); ++bsrc) {\n \/\/ move to next state\n state = nextState(*bsrc, state);\n \/\/ we stop here if state is not positive\n if (state <= 0) break;\n }\n\n \/\/ check final state\n if (state < 0) {\n \/\/ state is negative => it's negated character!\n dest.push_back(-state);\n \/\/ move after so far eaten escape sequence\n isrc = bsrc + 1;\n } else {\n \/\/ sequence not matcher pass input verbatim to output\n dest.push_back(*isrc++);\n }\n }\n \/\/ return output\n return dest;\n}\n\nint ContentType_t::nextState(unsigned char c, int state) const {\n \/\/ stop when state outside automaton \n if ((static_cast(state) >= unescaper.size()) ||\n (state < 0)) return 0;\n\n \/\/ iterator to state\n vector >::const_iterator i = unescaper.begin() + state;\n\n \/\/ find rule to move to next state\n for (; i->first > 0; ++i)\n if (i->first == c)\n return i->second;\n \/\/ no rule => stop\n return 0;\n}\n\n\/**\n * @short State in unescaper automaton.\n *\/\nstruct UnescaperState_t {\n \/**\n * @short Vector of next states.\n *\/\n typedef vector UnescaperStateVector_t;\n\n \/**\n * @short Create new state.\n * @param rule matched character\n *\/\n UnescaperState_t(int rule = 0)\n : rule(rule), nextState(0)\n {}\n \n \/**\n * @short Matched character.\n *\/\n int rule;\n\n \/**\n * @short Next state of automaton (positive) or replacement\n * character (negative) or stop state (zero).\n *\/\n int nextState;\n \n \/**\n * @short Next states.\n *\/\n UnescaperStateVector_t nextStates;\n \n \/**\n * @short Add new next state.\n * @param o rule for new state\n * @return added state\n *\/\n UnescaperState_t& add(int o) {\n \/\/ try to find existing state\n for (UnescaperStateVector_t::iterator i = nextStates.begin();\n i != nextStates.end(); ++i) {\n \/\/ rule found => return it\n if (i->rule == o) return *i;\n }\n \/\/ no state found, create it\n nextStates.push_back(UnescaperState_t(o));\n \/\/ return it\n return nextStates.back();\n }\n\n \/**\n * @short Linearize automaton tree.\n *\/\n void linearize(vector > &unescaper) const {\n \/\/ remember link holders\n vector referrers;\n \/\/ run throgh next states and write rule for each\n for (UnescaperStateVector_t::const_iterator i = nextStates.begin();\n i != nextStates.end(); ++i) {\n \/\/ remember position of link to next state\n referrers.push_back(unescaper.size());\n \/\/ create state\n unescaper.push_back(pair(i->rule, -i->nextState));\n }\n \/\/ put STOP indicator when we have any next state\n if (nextState == 0)\n unescaper.push_back(pair(0, 0));\n \/\/ run through all rules\n vector::const_iterator ireferrers = referrers.begin();\n for (UnescaperStateVector_t::const_iterator i = nextStates.begin();\n i != nextStates.end(); ++i, ++ireferrers) {\n if (!i->nextState) {\n \/\/ remember start of next state\n int pos = unescaper.size();\n \/\/ linearize this state\n i->linearize(unescaper);\n \/\/ assign link to sub state\n unescaper[*ireferrers].second = pos;\n }\n }\n }\n\n};\n\nvoid ContentType_t::compileUnescaper() {\n \/\/ destroy current automaton\n unescaper.clear();\n\n \/\/ start state of automaton\n UnescaperState_t root;\n\n \/\/ run through escape definitions\n for (vector >::const_iterator\n iescapes = escapes.begin();\n iescapes != escapes.end(); ++iescapes) {\n \/\/ start state\n UnescaperState_t *state = &root;\n \/\/ escape sequence\n const string &str = iescapes->second;\n \/\/ run through escape sequence\n for (string::const_iterator istr = str.begin();\n istr != str.end(); ++istr) {\n \/\/ add next state\n state = &state->add(*istr);\n }\n \/\/ assign unescaped character as final rule\n state->nextState = iescapes->first;\n }\n \/\/ linearize automaton into vector\n root.linearize(unescaper);\n}\n\n\/**\n * @short Function which creates content type descriptor\n * @return content type descriptor\n *\/\ntypedef ContentType_t* (*Creator_t)();\n\n\/**\n * @short Entry in table of content type descriptor creating\n * functions.\n *\/\nstruct CreatorEntry_t {\n \/**\n * @short name of content type\n *\/\n const char *name;\n\n \/**\n * @short content type descriptor creating function\n *\/\n Creator_t creator;\n\n \/**\n * @short comment for this content type\n *\/\n const char *comment;\n};\n\n\/** @short Create descriptor of HTML\/XHTML\/XML content type.\n * @return HTML descriptor\n *\/\nContentType_t* htmlCreator() {\n \/\/ create HTML descriptor\n ContentType_t *html = new ContentType_t();\n \/\/ HTML has only block comments\n html->blockComment = pair(\"\");\n \/\/ and has these (necessary) escapes\n html->addEscape('&', \"&\");\n html->addEscape('<', \"<\");\n html->addEscape('>', \">\");\n html->addEscape('\"', \""\");\n \/\/ compile unescaping automaton\n html->compileUnescaper();\n \/\/ return descriptor\n return html;\n}\n\n\/** @short Create descriptor of shell.\n * @return shell descriptor\n *\/\nContentType_t* shellCreator() {\n \/\/ create SHELL descriptor\n ContentType_t *shell = new ContentType_t();\n \/\/ SHELL has only line comment\n shell->lineComment = \"#\";\n \/\/ return descriptor\n return shell;\n}\n\n\/** @short Create descriptor of C language.\n * @return C descriptor\n *\/\nContentType_t* cCreator() {\n \/\/ create C descriptor\n ContentType_t *c = new ContentType_t();\n \/\/ C has only block comments\n c->blockComment = pair(\"\/*\", \"*\/\");\n \/\/ return descriptor\n return c;\n}\n\n\/** @short Create descriptor of quoted string.\n * @return quoted string descriptor\n *\/\nContentType_t* qstringCreator() {\n \/\/ create C descriptor\n ContentType_t *qs = new ContentType_t();\n\n qs->addEscape('\\n', \"\\\\n\");\n qs->addEscape('\\r', \"\\\\r\");\n qs->addEscape('\\a', \"\\\\a\");\n qs->addEscape('\\0', \"\\\\0\");\n qs->addEscape('\\v', \"\\\\v\");\n qs->addEscape('\\'', \"\\\\'\");\n qs->addEscape('\"', \"\\\\\\\"\");\n\n \/\/ compile unescaping automaton\n qs->compileUnescaper();\n\n \/\/ return descriptor\n return qs;\n}\n\nstatic CreatorEntry_t creators[] = {\n { \"text\/html\", htmlCreator,\n \"Hypertext markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"text\/xhtml\", htmlCreator,\n \"X hypertext markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"text\/xml\", htmlCreator,\n \"Extensible markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"application\/x-sh\", shellCreator,\n \"Common for all types of shell.\" },\n { \"text\/csrc\", cCreator,\n \"C\/C++ source code\" },\n { \"quoted-string\", qstringCreator,\n \"Generic quoted string with escapes.\" },\n { 0, 0 }\n};\n\nconst ContentType_t::Descriptor_t* ContentType_t::getDefault() {\n if (!descriptors) {\n descriptors = new map();\n descriptorIndex = new vector();\n }\n\n if (!unknown) {\n string name(\"text\/plain\");\n unknown = new Descriptor_t(new ContentType_t(), 0,\n name, \"Default (text\/plain) type.\");\n descriptors->insert(pair(name, unknown));\n descriptorIndex->push_back(unknown);\n }\n\n return unknown;\n}\n\nnamespace {\n struct ToLower_t {\n int operator () (int c) const {\n return tolower(c);\n }\n };\n}\n\nconst ContentType_t::Descriptor_t*\nContentType_t::findContentType(const string &sname, Error_t &err,\n const Error_t::Position_t &pos, bool failOnError)\n{\n \/\/ make name lower\n string name(sname);\n transform(name.begin(), name.end(), name.begin(), ToLower_t());\n\n \/\/ create all static data\n if (!unknown) getDefault();\n\n if (name.empty()) return unknown;\n\n \/\/ try to find cached content type descriptor\n map::const_iterator\n fdescriptors = descriptors->find(name);\n \/\/ if no content descriptor found\n if (fdescriptors == descriptors->end()) {\n \/\/ run through creator table and try to find appropriate\n \/\/ creator\n for (CreatorEntry_t *icreators = creators; icreators->name;\n ++icreators) {\n \/\/ if creator found\n if (icreators->name == name) {\n \/\/ create content type descriptor\n Descriptor_t *descriptor =\n new Descriptor_t(icreators->creator(),\n descriptorIndex->size(),\n icreators->name, icreators->comment);\n \/\/ remember descriptor in the descriptorIndex\n descriptorIndex->push_back(descriptor);\n\n \/\/ remmeber descriptor in the cache and return it to\n \/\/ the caller\n return descriptors->insert\n (pair(name, descriptor))\n .first->second;\n }\n }\n\n \/\/ log error\n err.logError(Error_t::LL_ERROR, pos, \"Content type '\" + sname +\n \"' not found.\");\n\n \/\/ content type not known; return global desriptor for unknown\n \/\/ types or 0 when asked to faile\n return failOnError ? 0 : unknown;\n }\n\n \/\/ return cached entry\n return fdescriptors->second;\n};\n\nconst ContentType_t::Descriptor_t*\nContentType_t::getContentType(unsigned int index)\n{\n \/\/ check bounds and return desctiptor (or 0 on error)\n if (index >= descriptorIndex->size()) return 0;\n return (*descriptorIndex)[index];\n}\n\nvoid ContentType_t::listSupported(vector > &supported) {\n for (CreatorEntry_t *icreators = creators;\n icreators->name; ++icreators)\n supported.push_back(make_pair(icreators->name,\n (icreators->comment ? icreators->comment\n : string())));\n};\n\nvoid Escaper_t::push(ContentType_t *ct) {\n escapers.push(ct);\n}\n\nvoid Escaper_t::push(unsigned int index, Error_t &err,\n const Error_t::Position_t &pos)\n{\n const ContentType_t::Descriptor_t *descriptor\n = ContentType_t::getContentType(index);\n if (!descriptor) {\n err.logError(Error_t::LL_ERROR, pos,\n \"Cannot pot invalid content type -- using top instead.\");\n escapers.push(escapers.top());\n } else {\n escapers.push(descriptor->contentType);\n }\n}\n\nvoid Escaper_t::pop(Error_t &err, const Error_t::Position_t &pos) {\n if (!escapers.empty()) {\n escapers.pop();\n } else {\n err.logError(Error_t::LL_ERROR, pos,\n \"Cannot pop content type -- only one remains.\");\n }\n}\nadded escaping od \\ to quoted-string escaper\/*\n * Teng -- a general purpose templating engine.\n * Copyright (C) 2004 Seznam.cz, a.s.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Seznam.cz, a.s.\n * Naskove 1, Praha 5, 15000, Czech Republic\n * http:\/\/www.seznam.cz, mailto:teng@firma.seznam.cz\n *\n * $Id: tengcontenttype.cc,v 1.4 2005-09-26 10:08:21 vasek Exp $\n *\n * DESCRIPTION\n * Teng language descriptor -- implementation.\n *\n * AUTHORS\n * Vaclav Blazek \n *\n * HISTORY\n * 2003-09-24 (vasek)\n * Created.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"tengcontenttype.h\"\n\nusing namespace std;\n\nusing namespace Teng;\n\nnamespace {\n map *descriptors = 0;\n vector *descriptorIndex = 0;\n\n ContentType_t::Descriptor_t *unknown = 0;\n}\n\nContentType_t::ContentType_t()\n : lineComment(), blockComment(), escapes(),\n unescaper()\n{\n \/\/ set escape bitmap to all -1 (character not escaped)\n int *end = escapeBitmap + 256;\n int *i = escapeBitmap;\n while (i != end) *i++ = -1;\n \/\/ create empty automaton\n unescaper.push_back(pair(0, 0));\n}\n\nint ContentType_t::addEscape(unsigned char c, const string &escape) {\n \/\/ if escape already present in bitmap make it error\n if (escapeBitmap[c] != -1) return -1;\n \/\/ add escape entry\n escapes.push_back(pair(c, escape));\n \/\/ update entry in escape bitmap\n return escapeBitmap[c] = escapes.size() - 1;\n}\n\nstring ContentType_t::escape(const string &src) const {\n \/\/ output string\n string dest;\n dest.reserve(src.length());\n\n \/\/ run through input string\n for (string::const_iterator isrc = src.begin();\n isrc != src.end(); ++isrc) {\n \/\/ find entry in bitmap\n int pos = escapeBitmap[static_cast(*isrc)];\n \/\/ if position is negative pass source character to output\n if (pos < 0) dest.push_back(*isrc);\n \/\/ else append escape sequence\n else dest.append(escapes[pos].second);\n }\n \/\/ return output\n return dest;\n}\n\nstring ContentType_t::unescape(const string &src) const {\n \/\/ output string\n string dest;\n dest.reserve(src.length());\n\n \/\/ run through input string\n for (string::const_iterator isrc = src.begin();\n isrc != src.end(); ) {\n \/\/ help iterator\n string::const_iterator bsrc = isrc;\n \/\/ index in automaton\n int state = 0;\n \/\/ run through remaining characters\n for (; bsrc != src.end(); ++bsrc) {\n \/\/ move to next state\n state = nextState(*bsrc, state);\n \/\/ we stop here if state is not positive\n if (state <= 0) break;\n }\n\n \/\/ check final state\n if (state < 0) {\n \/\/ state is negative => it's negated character!\n dest.push_back(-state);\n \/\/ move after so far eaten escape sequence\n isrc = bsrc + 1;\n } else {\n \/\/ sequence not matcher pass input verbatim to output\n dest.push_back(*isrc++);\n }\n }\n \/\/ return output\n return dest;\n}\n\nint ContentType_t::nextState(unsigned char c, int state) const {\n \/\/ stop when state outside automaton \n if ((static_cast(state) >= unescaper.size()) ||\n (state < 0)) return 0;\n\n \/\/ iterator to state\n vector >::const_iterator i = unescaper.begin() + state;\n\n \/\/ find rule to move to next state\n for (; i->first > 0; ++i)\n if (i->first == c)\n return i->second;\n \/\/ no rule => stop\n return 0;\n}\n\n\/**\n * @short State in unescaper automaton.\n *\/\nstruct UnescaperState_t {\n \/**\n * @short Vector of next states.\n *\/\n typedef vector UnescaperStateVector_t;\n\n \/**\n * @short Create new state.\n * @param rule matched character\n *\/\n UnescaperState_t(int rule = 0)\n : rule(rule), nextState(0)\n {}\n \n \/**\n * @short Matched character.\n *\/\n int rule;\n\n \/**\n * @short Next state of automaton (positive) or replacement\n * character (negative) or stop state (zero).\n *\/\n int nextState;\n \n \/**\n * @short Next states.\n *\/\n UnescaperStateVector_t nextStates;\n \n \/**\n * @short Add new next state.\n * @param o rule for new state\n * @return added state\n *\/\n UnescaperState_t& add(int o) {\n \/\/ try to find existing state\n for (UnescaperStateVector_t::iterator i = nextStates.begin();\n i != nextStates.end(); ++i) {\n \/\/ rule found => return it\n if (i->rule == o) return *i;\n }\n \/\/ no state found, create it\n nextStates.push_back(UnescaperState_t(o));\n \/\/ return it\n return nextStates.back();\n }\n\n \/**\n * @short Linearize automaton tree.\n *\/\n void linearize(vector > &unescaper) const {\n \/\/ remember link holders\n vector referrers;\n \/\/ run throgh next states and write rule for each\n for (UnescaperStateVector_t::const_iterator i = nextStates.begin();\n i != nextStates.end(); ++i) {\n \/\/ remember position of link to next state\n referrers.push_back(unescaper.size());\n \/\/ create state\n unescaper.push_back(pair(i->rule, -i->nextState));\n }\n \/\/ put STOP indicator when we have any next state\n if (nextState == 0)\n unescaper.push_back(pair(0, 0));\n \/\/ run through all rules\n vector::const_iterator ireferrers = referrers.begin();\n for (UnescaperStateVector_t::const_iterator i = nextStates.begin();\n i != nextStates.end(); ++i, ++ireferrers) {\n if (!i->nextState) {\n \/\/ remember start of next state\n int pos = unescaper.size();\n \/\/ linearize this state\n i->linearize(unescaper);\n \/\/ assign link to sub state\n unescaper[*ireferrers].second = pos;\n }\n }\n }\n\n};\n\nvoid ContentType_t::compileUnescaper() {\n \/\/ destroy current automaton\n unescaper.clear();\n\n \/\/ start state of automaton\n UnescaperState_t root;\n\n \/\/ run through escape definitions\n for (vector >::const_iterator\n iescapes = escapes.begin();\n iescapes != escapes.end(); ++iescapes) {\n \/\/ start state\n UnescaperState_t *state = &root;\n \/\/ escape sequence\n const string &str = iescapes->second;\n \/\/ run through escape sequence\n for (string::const_iterator istr = str.begin();\n istr != str.end(); ++istr) {\n \/\/ add next state\n state = &state->add(*istr);\n }\n \/\/ assign unescaped character as final rule\n state->nextState = iescapes->first;\n }\n \/\/ linearize automaton into vector\n root.linearize(unescaper);\n}\n\n\/**\n * @short Function which creates content type descriptor\n * @return content type descriptor\n *\/\ntypedef ContentType_t* (*Creator_t)();\n\n\/**\n * @short Entry in table of content type descriptor creating\n * functions.\n *\/\nstruct CreatorEntry_t {\n \/**\n * @short name of content type\n *\/\n const char *name;\n\n \/**\n * @short content type descriptor creating function\n *\/\n Creator_t creator;\n\n \/**\n * @short comment for this content type\n *\/\n const char *comment;\n};\n\n\/** @short Create descriptor of HTML\/XHTML\/XML content type.\n * @return HTML descriptor\n *\/\nContentType_t* htmlCreator() {\n \/\/ create HTML descriptor\n ContentType_t *html = new ContentType_t();\n \/\/ HTML has only block comments\n html->blockComment = pair(\"\");\n \/\/ and has these (necessary) escapes\n html->addEscape('&', \"&\");\n html->addEscape('<', \"<\");\n html->addEscape('>', \">\");\n html->addEscape('\"', \""\");\n \/\/ compile unescaping automaton\n html->compileUnescaper();\n \/\/ return descriptor\n return html;\n}\n\n\/** @short Create descriptor of shell.\n * @return shell descriptor\n *\/\nContentType_t* shellCreator() {\n \/\/ create SHELL descriptor\n ContentType_t *shell = new ContentType_t();\n \/\/ SHELL has only line comment\n shell->lineComment = \"#\";\n \/\/ return descriptor\n return shell;\n}\n\n\/** @short Create descriptor of C language.\n * @return C descriptor\n *\/\nContentType_t* cCreator() {\n \/\/ create C descriptor\n ContentType_t *c = new ContentType_t();\n \/\/ C has only block comments\n c->blockComment = pair(\"\/*\", \"*\/\");\n \/\/ return descriptor\n return c;\n}\n\n\/** @short Create descriptor of quoted string.\n * @return quoted string descriptor\n *\/\nContentType_t* qstringCreator() {\n \/\/ create quoted-string descriptor\n ContentType_t *qs = new ContentType_t();\n\n qs->addEscape('\\\\', \"\\\\\\\\\");\n qs->addEscape('\\n', \"\\\\n\");\n qs->addEscape('\\r', \"\\\\r\");\n qs->addEscape('\\a', \"\\\\a\");\n qs->addEscape('\\0', \"\\\\0\");\n qs->addEscape('\\v', \"\\\\v\");\n qs->addEscape('\\'', \"\\\\'\");\n qs->addEscape('\"', \"\\\\\\\"\");\n\n \/\/ compile unescaping automaton\n qs->compileUnescaper();\n\n \/\/ return descriptor\n return qs;\n}\n\nstatic CreatorEntry_t creators[] = {\n { \"text\/html\", htmlCreator,\n \"Hypertext markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"text\/xhtml\", htmlCreator,\n \"X hypertext markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"text\/xml\", htmlCreator,\n \"Extensible markup language. Same processor as for\"\n \" 'text\/xhtml' and 'text\/xml'\" },\n { \"application\/x-sh\", shellCreator,\n \"Common for all types of shell.\" },\n { \"text\/csrc\", cCreator,\n \"C\/C++ source code\" },\n { \"quoted-string\", qstringCreator,\n \"Generic quoted string with escapes.\" },\n { 0, 0 }\n};\n\nconst ContentType_t::Descriptor_t* ContentType_t::getDefault() {\n if (!descriptors) {\n descriptors = new map();\n descriptorIndex = new vector();\n }\n\n if (!unknown) {\n string name(\"text\/plain\");\n unknown = new Descriptor_t(new ContentType_t(), 0,\n name, \"Default (text\/plain) type.\");\n descriptors->insert(pair(name, unknown));\n descriptorIndex->push_back(unknown);\n }\n\n return unknown;\n}\n\nnamespace {\n struct ToLower_t {\n int operator () (int c) const {\n return tolower(c);\n }\n };\n}\n\nconst ContentType_t::Descriptor_t*\nContentType_t::findContentType(const string &sname, Error_t &err,\n const Error_t::Position_t &pos, bool failOnError)\n{\n \/\/ make name lower\n string name(sname);\n transform(name.begin(), name.end(), name.begin(), ToLower_t());\n\n \/\/ create all static data\n if (!unknown) getDefault();\n\n if (name.empty()) return unknown;\n\n \/\/ try to find cached content type descriptor\n map::const_iterator\n fdescriptors = descriptors->find(name);\n \/\/ if no content descriptor found\n if (fdescriptors == descriptors->end()) {\n \/\/ run through creator table and try to find appropriate\n \/\/ creator\n for (CreatorEntry_t *icreators = creators; icreators->name;\n ++icreators) {\n \/\/ if creator found\n if (icreators->name == name) {\n \/\/ create content type descriptor\n Descriptor_t *descriptor =\n new Descriptor_t(icreators->creator(),\n descriptorIndex->size(),\n icreators->name, icreators->comment);\n \/\/ remember descriptor in the descriptorIndex\n descriptorIndex->push_back(descriptor);\n\n \/\/ remmeber descriptor in the cache and return it to\n \/\/ the caller\n return descriptors->insert\n (pair(name, descriptor))\n .first->second;\n }\n }\n\n \/\/ log error\n err.logError(Error_t::LL_ERROR, pos, \"Content type '\" + sname +\n \"' not found.\");\n\n \/\/ content type not known; return global desriptor for unknown\n \/\/ types or 0 when asked to faile\n return failOnError ? 0 : unknown;\n }\n\n \/\/ return cached entry\n return fdescriptors->second;\n};\n\nconst ContentType_t::Descriptor_t*\nContentType_t::getContentType(unsigned int index)\n{\n \/\/ check bounds and return desctiptor (or 0 on error)\n if (index >= descriptorIndex->size()) return 0;\n return (*descriptorIndex)[index];\n}\n\nvoid ContentType_t::listSupported(vector > &supported) {\n for (CreatorEntry_t *icreators = creators;\n icreators->name; ++icreators)\n supported.push_back(make_pair(icreators->name,\n (icreators->comment ? icreators->comment\n : string())));\n};\n\nvoid Escaper_t::push(ContentType_t *ct) {\n escapers.push(ct);\n}\n\nvoid Escaper_t::push(unsigned int index, Error_t &err,\n const Error_t::Position_t &pos)\n{\n const ContentType_t::Descriptor_t *descriptor\n = ContentType_t::getContentType(index);\n if (!descriptor) {\n err.logError(Error_t::LL_ERROR, pos,\n \"Cannot pot invalid content type -- using top instead.\");\n escapers.push(escapers.top());\n } else {\n escapers.push(descriptor->contentType);\n }\n}\n\nvoid Escaper_t::pop(Error_t &err, const Error_t::Position_t &pos) {\n if (!escapers.empty()) {\n escapers.pop();\n } else {\n err.logError(Error_t::LL_ERROR, pos,\n \"Cannot pop content type -- only one remains.\");\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#include \"btree\/operations.hpp\"\n\n#include \"btree\/internal_node.hpp\"\n#include \"btree\/leaf_node.hpp\"\n#include \"btree\/node.hpp\"\n#include \"btree\/slice.hpp\"\n#include \"buffer_cache\/alt\/alt.hpp\"\n#include \"concurrency\/promise.hpp\"\n#include \"rdb_protocol\/profile.hpp\"\n\n\/\/ TODO: consider B#\/B* trees to improve space efficiency\n\n\/* Passing in a pass_back_superblock parameter will cause this function to\n * return the superblock after it's no longer needed (rather than releasing\n * it). Notice the superblock is not guaranteed to be returned until the\n * keyvalue_location_t that's passed in (keyvalue_location_out) is destroyed.\n * This is because it may need to use the superblock for some of its methods.\n * *\/\n\/\/ KSI: It seems like really we should pass the superblock_t via rvalue reference.\n\/\/ Is that possible? (promise_t makes it hard.)\ntemplate \nvoid find_keyvalue_location_for_write(\n superblock_t *superblock, const btree_key_t *key,\n keyvalue_location_t *keyvalue_location_out,\n btree_stats_t *stats,\n profile::trace_t *trace,\n promise_t *pass_back_superblock = NULL) {\n value_sizer_t sizer(superblock->cache()->max_block_size());\n\n keyvalue_location_out->superblock = superblock;\n keyvalue_location_out->pass_back_superblock = pass_back_superblock;\n\n ensure_stat_block(superblock);\n keyvalue_location_out->stat_block = keyvalue_location_out->superblock->get_stat_block_id();\n\n keyvalue_location_out->stats = stats;\n\n \/\/ KSI: Make sure we do the logic smart here -- don't needlessly hold both\n \/\/ buffers. (This finds the keyvalue for _write_ so that probably won't really\n \/\/ happen.)\n buf_lock_t last_buf;\n buf_lock_t buf;\n {\n \/\/ KSI: We can't acquire the block for write here -- we could, but it would\n \/\/ worsen the performance of the program -- sometimes we only end up using\n \/\/ this block for read. So the profiling information is not very good.\n profile::starter_t starter(\"Acquiring block for write.\\n\", trace);\n buf = get_root(&sizer, superblock);\n }\n\n \/\/ Walk down the tree to the leaf.\n for (;;) {\n {\n buf_read_t read(&buf);\n if (!node::is_internal(static_cast(read.get_data_read()))) {\n break;\n }\n }\n \/\/ Check if the node is overfull and proactively split it if it is (since this is an internal node).\n {\n profile::starter_t starter(\"Perhaps split node.\", trace);\n check_and_handle_split(&sizer, &buf, &last_buf, superblock, key, static_cast(NULL));\n }\n\n \/\/ Check if the node is underfull, and merge\/level if it is.\n {\n profile::starter_t starter(\"Perhaps merge nodes.\", trace);\n check_and_handle_underfull(&sizer, &buf, &last_buf, superblock, key);\n }\n\n \/\/ Release the superblock, if we've gone past the root (and haven't\n \/\/ already released it). If we're still at the root or at one of\n \/\/ its direct children, we might still want to replace the root, so\n \/\/ we can't release the superblock yet.\n if (!last_buf.empty() && keyvalue_location_out->superblock) {\n if (pass_back_superblock != NULL) {\n pass_back_superblock->pulse(superblock);\n keyvalue_location_out->superblock = NULL;\n } else {\n keyvalue_location_out->superblock->release();\n keyvalue_location_out->superblock = NULL;\n }\n }\n\n \/\/ Release the old previous node (unless we're at the root), and set\n \/\/ the next previous node (which is the current node).\n last_buf.reset_buf_lock();\n\n \/\/ Look up and acquire the next node.\n block_id_t node_id;\n {\n buf_read_t read(&buf);\n auto node = static_cast(read.get_data_read());\n node_id = internal_node::lookup(node, key);\n }\n rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID);\n\n {\n profile::starter_t starter(\"Acquiring block for write.\\n\", trace);\n buf_lock_t tmp(&buf, node_id, access_t::write);\n last_buf = std::move(buf);\n buf = std::move(tmp);\n }\n }\n\n {\n scoped_malloc_t tmp(sizer.max_possible_size());\n\n \/\/ We've gone down the tree and gotten to a leaf. Now look up the key.\n buf_read_t read(&buf);\n auto node = static_cast(read.get_data_read());\n bool key_found = leaf::lookup(&sizer, node, key, tmp.get());\n\n if (key_found) {\n keyvalue_location_out->there_originally_was_value = true;\n keyvalue_location_out->value = std::move(tmp);\n }\n }\n\n keyvalue_location_out->last_buf.swap(last_buf);\n keyvalue_location_out->buf.swap(buf);\n}\n\ntemplate \nvoid find_keyvalue_location_for_read(\n superblock_t *superblock, const btree_key_t *key,\n keyvalue_location_t *keyvalue_location_out,\n btree_stats_t *stats, profile::trace_t *trace) {\n stats->pm_keys_read.record();\n value_sizer_t sizer(superblock->cache()->max_block_size());\n\n const block_id_t root_id = superblock->get_root_block_id();\n rassert(root_id != SUPERBLOCK_ID);\n\n if (root_id == NULL_BLOCK_ID) {\n \/\/ There is no root, so the tree is empty.\n superblock->release();\n return;\n }\n\n buf_lock_t buf;\n {\n profile::starter_t starter(\"Acquire a block for read.\", trace);\n buf_lock_t tmp(superblock->expose_buf(), root_id, access_t::read);\n superblock->release();\n buf = std::move(tmp);\n }\n\n#ifndef NDEBUG\n {\n buf_read_t read(&buf);\n node::validate(&sizer, static_cast(read.get_data_read()));\n }\n#endif \/\/ NDEBUG\n\n for (;;) {\n {\n buf_read_t read(&buf);\n if (!node::is_internal(static_cast(read.get_data_read()))) {\n break;\n }\n }\n block_id_t node_id;\n {\n buf_read_t read(&buf);\n const internal_node_t *node\n = static_cast(read.get_data_read());\n node_id = internal_node::lookup(node, key);\n }\n rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID);\n\n {\n profile::starter_t starter(\"Acquire a block for read.\", trace);\n buf_lock_t tmp(&buf, node_id, access_t::read);\n buf.reset_buf_lock();\n buf = std::move(tmp);\n }\n\n#ifndef NDEBUG\n {\n buf_read_t read(&buf);\n node::validate(&sizer, static_cast(read.get_data_read()));\n }\n#endif \/\/ NDEBUG\n }\n\n \/\/ Got down to the leaf, now probe it.\n scoped_malloc_t value(sizer.max_possible_size());\n bool value_found;\n {\n buf_read_t read(&buf);\n const leaf_node_t *leaf\n = static_cast(read.get_data_read());\n value_found = leaf::lookup(&sizer, leaf, key, value.get());\n }\n if (value_found) {\n keyvalue_location_out->buf = std::move(buf);\n keyvalue_location_out->there_originally_was_value = true;\n keyvalue_location_out->value = std::move(value);\n }\n}\n\nenum class expired_t { NO, YES };\n\ntemplate \nvoid apply_keyvalue_change(keyvalue_location_t *kv_loc,\n const btree_key_t *key, repli_timestamp_t tstamp, expired_t expired,\n key_modification_callback_t *km_callback) {\n\n value_sizer_t sizer(kv_loc->buf.cache()->get_block_size());\n\n key_modification_proof_t km_proof\n = km_callback->value_modification(kv_loc, key);\n\n \/* how much this keyvalue change affects the total population of the btree\n * (should be -1, 0 or 1) *\/\n int population_change;\n\n if (kv_loc->value.has()) {\n \/\/ We have a value to insert.\n\n \/\/ Split the node if necessary, to make sure that we have room\n \/\/ for the value. Not necessary when deleting, because the\n \/\/ node won't grow.\n\n check_and_handle_split(&sizer, &kv_loc->buf, &kv_loc->last_buf,\n kv_loc->superblock, key, kv_loc->value.get());\n\n {\n#ifndef NDEBUG\n buf_read_t read(&kv_loc->buf);\n auto leaf_node = static_cast(read.get_data_read());\n rassert(!leaf::is_full(&sizer, leaf_node, key, kv_loc->value.get()));\n#endif\n }\n\n if (kv_loc->there_originally_was_value) {\n population_change = 0;\n } else {\n population_change = 1;\n }\n\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::insert(&sizer,\n leaf_node,\n key,\n kv_loc->value.get(),\n tstamp,\n km_proof);\n }\n\n kv_loc->stats->pm_keys_set.record();\n } else {\n \/\/ Delete the value if it's there.\n if (kv_loc->there_originally_was_value) {\n if (expired == expired_t::NO) {\n rassert(tstamp != repli_timestamp_t::invalid, \"Deletes need a valid timestamp now.\");\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::remove(&sizer,\n leaf_node,\n key,\n tstamp,\n km_proof);\n }\n population_change = -1;\n kv_loc->stats->pm_keys_set.record();\n } else {\n \/\/ TODO: Oh god oh god get rid of \"expired\".\n \/\/ Expirations do an erase, not a delete.\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::erase_presence(&sizer,\n leaf_node,\n key,\n km_proof);\n }\n population_change = 0;\n kv_loc->stats->pm_keys_expired.record();\n }\n } else {\n population_change = 0;\n }\n }\n\n \/\/ Check to see if the leaf is underfull (following a change in\n \/\/ size or a deletion, and merge\/level if it is.\n check_and_handle_underfull(&sizer, &kv_loc->buf, &kv_loc->last_buf,\n kv_loc->superblock, key);\n\n \/\/ Modify the stats block. The stats block is detached from the rest of the\n \/\/ btree, we don't keep a consistent view of it, so we pass the txn as its\n \/\/ parent.\n buf_lock_t stat_block(buf_parent_t(kv_loc->buf.txn()),\n kv_loc->stat_block, access_t::write);\n buf_write_t stat_block_write(&stat_block);\n auto stat_block_buf\n = static_cast(stat_block_write.get_data_write());\n stat_block_buf->population += population_change;\n}\nReduced buf_read_t construction a bit.\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#include \"btree\/operations.hpp\"\n\n#include \"btree\/internal_node.hpp\"\n#include \"btree\/leaf_node.hpp\"\n#include \"btree\/node.hpp\"\n#include \"btree\/slice.hpp\"\n#include \"buffer_cache\/alt\/alt.hpp\"\n#include \"concurrency\/promise.hpp\"\n#include \"rdb_protocol\/profile.hpp\"\n\n\/\/ TODO: consider B#\/B* trees to improve space efficiency\n\n\/* Passing in a pass_back_superblock parameter will cause this function to\n * return the superblock after it's no longer needed (rather than releasing\n * it). Notice the superblock is not guaranteed to be returned until the\n * keyvalue_location_t that's passed in (keyvalue_location_out) is destroyed.\n * This is because it may need to use the superblock for some of its methods.\n * *\/\n\/\/ KSI: It seems like really we should pass the superblock_t via rvalue reference.\n\/\/ Is that possible? (promise_t makes it hard.)\ntemplate \nvoid find_keyvalue_location_for_write(\n superblock_t *superblock, const btree_key_t *key,\n keyvalue_location_t *keyvalue_location_out,\n btree_stats_t *stats,\n profile::trace_t *trace,\n promise_t *pass_back_superblock = NULL) {\n value_sizer_t sizer(superblock->cache()->max_block_size());\n\n keyvalue_location_out->superblock = superblock;\n keyvalue_location_out->pass_back_superblock = pass_back_superblock;\n\n ensure_stat_block(superblock);\n keyvalue_location_out->stat_block = keyvalue_location_out->superblock->get_stat_block_id();\n\n keyvalue_location_out->stats = stats;\n\n \/\/ KSI: Make sure we do the logic smart here -- don't needlessly hold both\n \/\/ buffers. (This finds the keyvalue for _write_ so that probably won't really\n \/\/ happen.)\n buf_lock_t last_buf;\n buf_lock_t buf;\n {\n \/\/ KSI: We can't acquire the block for write here -- we could, but it would\n \/\/ worsen the performance of the program -- sometimes we only end up using\n \/\/ this block for read. So the profiling information is not very good.\n profile::starter_t starter(\"Acquiring block for write.\\n\", trace);\n buf = get_root(&sizer, superblock);\n }\n\n \/\/ Walk down the tree to the leaf.\n for (;;) {\n {\n buf_read_t read(&buf);\n if (!node::is_internal(static_cast(read.get_data_read()))) {\n break;\n }\n }\n \/\/ Check if the node is overfull and proactively split it if it is (since this is an internal node).\n {\n profile::starter_t starter(\"Perhaps split node.\", trace);\n check_and_handle_split(&sizer, &buf, &last_buf, superblock, key, static_cast(NULL));\n }\n\n \/\/ Check if the node is underfull, and merge\/level if it is.\n {\n profile::starter_t starter(\"Perhaps merge nodes.\", trace);\n check_and_handle_underfull(&sizer, &buf, &last_buf, superblock, key);\n }\n\n \/\/ Release the superblock, if we've gone past the root (and haven't\n \/\/ already released it). If we're still at the root or at one of\n \/\/ its direct children, we might still want to replace the root, so\n \/\/ we can't release the superblock yet.\n if (!last_buf.empty() && keyvalue_location_out->superblock) {\n if (pass_back_superblock != NULL) {\n pass_back_superblock->pulse(superblock);\n keyvalue_location_out->superblock = NULL;\n } else {\n keyvalue_location_out->superblock->release();\n keyvalue_location_out->superblock = NULL;\n }\n }\n\n \/\/ Release the old previous node (unless we're at the root), and set\n \/\/ the next previous node (which is the current node).\n last_buf.reset_buf_lock();\n\n \/\/ Look up and acquire the next node.\n block_id_t node_id;\n {\n buf_read_t read(&buf);\n auto node = static_cast(read.get_data_read());\n node_id = internal_node::lookup(node, key);\n }\n rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID);\n\n {\n profile::starter_t starter(\"Acquiring block for write.\\n\", trace);\n buf_lock_t tmp(&buf, node_id, access_t::write);\n last_buf = std::move(buf);\n buf = std::move(tmp);\n }\n }\n\n {\n scoped_malloc_t tmp(sizer.max_possible_size());\n\n \/\/ We've gone down the tree and gotten to a leaf. Now look up the key.\n buf_read_t read(&buf);\n auto node = static_cast(read.get_data_read());\n bool key_found = leaf::lookup(&sizer, node, key, tmp.get());\n\n if (key_found) {\n keyvalue_location_out->there_originally_was_value = true;\n keyvalue_location_out->value = std::move(tmp);\n }\n }\n\n keyvalue_location_out->last_buf.swap(last_buf);\n keyvalue_location_out->buf.swap(buf);\n}\n\ntemplate \nvoid find_keyvalue_location_for_read(\n superblock_t *superblock, const btree_key_t *key,\n keyvalue_location_t *keyvalue_location_out,\n btree_stats_t *stats, profile::trace_t *trace) {\n stats->pm_keys_read.record();\n value_sizer_t sizer(superblock->cache()->max_block_size());\n\n const block_id_t root_id = superblock->get_root_block_id();\n rassert(root_id != SUPERBLOCK_ID);\n\n if (root_id == NULL_BLOCK_ID) {\n \/\/ There is no root, so the tree is empty.\n superblock->release();\n return;\n }\n\n buf_lock_t buf;\n {\n profile::starter_t starter(\"Acquire a block for read.\", trace);\n buf_lock_t tmp(superblock->expose_buf(), root_id, access_t::read);\n superblock->release();\n buf = std::move(tmp);\n }\n\n#ifndef NDEBUG\n {\n buf_read_t read(&buf);\n node::validate(&sizer, static_cast(read.get_data_read()));\n }\n#endif \/\/ NDEBUG\n\n for (;;) {\n block_id_t node_id;\n {\n buf_read_t read(&buf);\n const void *data = read.get_data_read();\n if (!node::is_internal(static_cast(data))) {\n break;\n }\n\n node_id = internal_node::lookup(static_cast(data),\n key);\n }\n rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID);\n\n {\n profile::starter_t starter(\"Acquire a block for read.\", trace);\n buf_lock_t tmp(&buf, node_id, access_t::read);\n buf.reset_buf_lock();\n buf = std::move(tmp);\n }\n\n#ifndef NDEBUG\n {\n buf_read_t read(&buf);\n node::validate(&sizer, static_cast(read.get_data_read()));\n }\n#endif \/\/ NDEBUG\n }\n\n \/\/ Got down to the leaf, now probe it.\n scoped_malloc_t value(sizer.max_possible_size());\n bool value_found;\n {\n buf_read_t read(&buf);\n const leaf_node_t *leaf\n = static_cast(read.get_data_read());\n value_found = leaf::lookup(&sizer, leaf, key, value.get());\n }\n if (value_found) {\n keyvalue_location_out->buf = std::move(buf);\n keyvalue_location_out->there_originally_was_value = true;\n keyvalue_location_out->value = std::move(value);\n }\n}\n\nenum class expired_t { NO, YES };\n\ntemplate \nvoid apply_keyvalue_change(keyvalue_location_t *kv_loc,\n const btree_key_t *key, repli_timestamp_t tstamp, expired_t expired,\n key_modification_callback_t *km_callback) {\n\n value_sizer_t sizer(kv_loc->buf.cache()->get_block_size());\n\n key_modification_proof_t km_proof\n = km_callback->value_modification(kv_loc, key);\n\n \/* how much this keyvalue change affects the total population of the btree\n * (should be -1, 0 or 1) *\/\n int population_change;\n\n if (kv_loc->value.has()) {\n \/\/ We have a value to insert.\n\n \/\/ Split the node if necessary, to make sure that we have room\n \/\/ for the value. Not necessary when deleting, because the\n \/\/ node won't grow.\n\n check_and_handle_split(&sizer, &kv_loc->buf, &kv_loc->last_buf,\n kv_loc->superblock, key, kv_loc->value.get());\n\n {\n#ifndef NDEBUG\n buf_read_t read(&kv_loc->buf);\n auto leaf_node = static_cast(read.get_data_read());\n rassert(!leaf::is_full(&sizer, leaf_node, key, kv_loc->value.get()));\n#endif\n }\n\n if (kv_loc->there_originally_was_value) {\n population_change = 0;\n } else {\n population_change = 1;\n }\n\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::insert(&sizer,\n leaf_node,\n key,\n kv_loc->value.get(),\n tstamp,\n km_proof);\n }\n\n kv_loc->stats->pm_keys_set.record();\n } else {\n \/\/ Delete the value if it's there.\n if (kv_loc->there_originally_was_value) {\n if (expired == expired_t::NO) {\n rassert(tstamp != repli_timestamp_t::invalid, \"Deletes need a valid timestamp now.\");\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::remove(&sizer,\n leaf_node,\n key,\n tstamp,\n km_proof);\n }\n population_change = -1;\n kv_loc->stats->pm_keys_set.record();\n } else {\n \/\/ TODO: Oh god oh god get rid of \"expired\".\n \/\/ Expirations do an erase, not a delete.\n {\n buf_write_t write(&kv_loc->buf);\n auto leaf_node = static_cast(write.get_data_write());\n leaf::erase_presence(&sizer,\n leaf_node,\n key,\n km_proof);\n }\n population_change = 0;\n kv_loc->stats->pm_keys_expired.record();\n }\n } else {\n population_change = 0;\n }\n }\n\n \/\/ Check to see if the leaf is underfull (following a change in\n \/\/ size or a deletion, and merge\/level if it is.\n check_and_handle_underfull(&sizer, &kv_loc->buf, &kv_loc->last_buf,\n kv_loc->superblock, key);\n\n \/\/ Modify the stats block. The stats block is detached from the rest of the\n \/\/ btree, we don't keep a consistent view of it, so we pass the txn as its\n \/\/ parent.\n buf_lock_t stat_block(buf_parent_t(kv_loc->buf.txn()),\n kv_loc->stat_block, access_t::write);\n buf_write_t stat_block_write(&stat_block);\n auto stat_block_buf\n = static_cast(stat_block_write.get_data_write());\n stat_block_buf->population += population_change;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n\/* Test calculation of next difficulty target with no constraints applying *\/\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n int64_t nLastRetargetTime = 1261130161; \/\/ Block #30240\n CBlockIndex pindexLast;\n pindexLast.nHeight = 32255;\n pindexLast.nTime = 1262152739; \/\/ Block #32255\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1d00d86a);\n}\n\n\/* Test the constraint on the upper bound for next work *\/\nBOOST_AUTO_TEST_CASE(get_next_work_pow_limit)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n int64_t nLastRetargetTime = 1231006505; \/\/ Block #0\n CBlockIndex pindexLast;\n pindexLast.nHeight = 2015;\n pindexLast.nTime = 1233061996; \/\/ Block #2015\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1d00ffff);\n}\n\n\/* Test the constraint on the lower bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n int64_t nLastRetargetTime = 1279008237; \/\/ Block #66528\n CBlockIndex pindexLast;\n pindexLast.nHeight = 68543;\n pindexLast.nTime = 1279297671; \/\/ Block #68543\n pindexLast.nBits = 0x1c05a3f4;\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1c0168fd);\n}\n\n\/* Test the constraint on the upper bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n int64_t nLastRetargetTime = 1263163443; \/\/ NOTE: Not an actual block time\n CBlockIndex pindexLast;\n pindexLast.nHeight = 46367;\n pindexLast.nTime = 1269211443; \/\/ Block #46367\n pindexLast.nBits = 0x1c387f6f;\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1d00e1fd);\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n std::vector blocks(10000);\n for (int i = 0; i < 10000; i++) {\n blocks[i].pprev = i ? &blocks[i - 1] : nullptr;\n blocks[i].nHeight = i;\n blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;\n blocks[i].nBits = 0x207fffff; \/* target 0x7fffff000... *\/\n blocks[i].nChainTrust = i ? blocks[i - 1].nChainTrust + GetBlockTrust(blocks[i - 1]) : arith_uint256(0);\n }\n\n for (int j = 0; j < 1000; j++) {\n CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];\n CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];\n CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];\n\n int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());\n BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\npow test for v9 fork added\/\/ Copyright (c) 2015-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n\/* Test calculation of next difficulty target with no constraints applying *\/\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n\n CBlockIndex pindexThirdLast;\n pindexThirdLast.nHeight = 2;\n pindexThirdLast.nTime = 1345400368;\n pindexThirdLast.nBits = 0x1c00ffff;\n\n CBlockIndex pindexSecondLast;\n pindexSecondLast.nHeight = 3;\n pindexSecondLast.pprev = &pindexThirdLast;\n pindexSecondLast.nTime = 1345400724;\n pindexSecondLast.nBits = 0x1c00ff7f;\n\n CBlockIndex pindexLast;\n pindexLast.nHeight = 4;\n pindexLast.pprev = &pindexSecondLast;\n pindexLast.nTime = 1345400851;\n pindexLast.nBits = 0x1c00ff4a;\n\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1c00fee3);\n}\n\n\/* Test the target before v9 *\/\nBOOST_AUTO_TEST_CASE(get_next_work_beforev9)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n\n CBlockIndex pindexThirdLast;\n pindexThirdLast.nHeight = 2;\n pindexThirdLast.nTime = 1581334360;\n pindexThirdLast.nBits = 0x1c00ffff;\n\n CBlockIndex pindexSecondLast;\n pindexSecondLast.nHeight = 3;\n pindexSecondLast.pprev = &pindexThirdLast;\n pindexSecondLast.nTime = 1581334380;\n pindexSecondLast.nBits = 0x1c00ff7f;\n\n CBlockIndex pindexLast;\n pindexLast.nHeight = 4;\n pindexLast.pprev = &pindexSecondLast;\n pindexLast.nTime = 1581334400;\n pindexLast.nBits = 0x1c00ff4a;\n\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1c00fecc);\n}\n\n\n\/* Test the target correct after v9 *\/\nBOOST_AUTO_TEST_CASE(get_next_work_afterv9)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n\n CBlockIndex pindexThirdLast;\n pindexThirdLast.nHeight = 2;\n pindexThirdLast.nTime = 1588334400;\n pindexThirdLast.nBits = 0x1c00ffff;\n\n CBlockIndex pindexSecondLast;\n pindexSecondLast.nHeight = 3;\n pindexSecondLast.pprev = &pindexThirdLast;\n pindexSecondLast.nTime = 1588334420;\n pindexSecondLast.nBits = 0x1c00ff7f;\n\n CBlockIndex pindexLast;\n pindexLast.nHeight = 4;\n pindexLast.pprev = &pindexSecondLast;\n pindexLast.nTime = 1588334440;\n pindexLast.nBits = 0x1c00ff4a;\n\n BOOST_CHECK_EQUAL(GetNextTargetRequired(&pindexLast, false, chainParams->GetConsensus()), 0x1c00f94c);\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);\n std::vector blocks(10000);\n for (int i = 0; i < 10000; i++) {\n blocks[i].pprev = i ? &blocks[i - 1] : nullptr;\n blocks[i].nHeight = i;\n blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;\n blocks[i].nBits = 0x207fffff; \/* target 0x7fffff000... *\/\n blocks[i].nChainTrust = i ? blocks[i - 1].nChainTrust + GetBlockTrust(blocks[i - 1]) : arith_uint256(0);\n }\n\n for (int j = 0; j < 1000; j++) {\n CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];\n CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];\n CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];\n\n int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());\n BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include \"test\/test_bitcoin.h\"\n\n#include \n#include \n\n#include \"univalue\/univalue.h\"\n\nusing namespace std;\n\nUniValue\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n UniValue result(UniValue::VARR);\n result.push_back(nRequired);\n UniValue addresses(UniValue::VARR);\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nUniValue CallRPC(string args)\n{\n vector vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n UniValue params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n UniValue result = (*method)(params, false);\n return result;\n }\n catch (const UniValue& objError) {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n UniValue r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n UniValue r;\n \/\/ input is a 1-of-2 multisig (so is output):\n string prevout =\n \"[{\\\"txid\\\":\\\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\\\",\"\n \"\\\"redeemScript\\\":\\\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\\\":11}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\\\"\";\n string privkey2 = \"\\\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK(ValueFromAmount(0LL).write() == \"0.00000000\");\n BOOST_CHECK(ValueFromAmount(1LL).write() == \"0.00000001\");\n BOOST_CHECK(ValueFromAmount(17622195LL).write() == \"0.17622195\");\n BOOST_CHECK(ValueFromAmount(50000000LL).write() == \"0.50000000\");\n BOOST_CHECK(ValueFromAmount(89898989LL).write() == \"0.89898989\");\n BOOST_CHECK(ValueFromAmount(100000000LL).write() == \"1.00000000\");\n BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == \"20999999.99999990\");\n BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == \"20999999.99999999\");\n}\n\nstatic UniValue ValueFromString(const std::string &str)\n{\n UniValue value;\n BOOST_CHECK(value.setNumStr(str));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(json_parse_errors)\n{\n Value value;\n \/\/ Valid\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0\"), value), true);\n \/\/ Valid, with trailing whitespace\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0 \"), value), true);\n \/\/ Invalid, initial garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"[1.0\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"a1.0\"), value), false);\n \/\/ Invalid, trailing garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0sds\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0]\"), value), false);\n \/\/ BTC addresses should fail parsing\n BOOST_CHECK_EQUAL(read_string(std::string(\"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL\"), value), false);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nfix univalue json parse tests\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include \"test\/test_bitcoin.h\"\n\n#include \n#include \n\n#include \"univalue\/univalue.h\"\n\nusing namespace std;\n\nUniValue\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n UniValue result(UniValue::VARR);\n result.push_back(nRequired);\n UniValue addresses(UniValue::VARR);\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nUniValue CallRPC(string args)\n{\n vector vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n UniValue params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n UniValue result = (*method)(params, false);\n return result;\n }\n catch (const UniValue& objError) {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n UniValue r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n UniValue r;\n \/\/ input is a 1-of-2 multisig (so is output):\n string prevout =\n \"[{\\\"txid\\\":\\\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\\\",\"\n \"\\\"redeemScript\\\":\\\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\\\":11}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\\\"\";\n string privkey2 = \"\\\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK(ValueFromAmount(0LL).write() == \"0.00000000\");\n BOOST_CHECK(ValueFromAmount(1LL).write() == \"0.00000001\");\n BOOST_CHECK(ValueFromAmount(17622195LL).write() == \"0.17622195\");\n BOOST_CHECK(ValueFromAmount(50000000LL).write() == \"0.50000000\");\n BOOST_CHECK(ValueFromAmount(89898989LL).write() == \"0.89898989\");\n BOOST_CHECK(ValueFromAmount(100000000LL).write() == \"1.00000000\");\n BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == \"20999999.99999990\");\n BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == \"20999999.99999999\");\n}\n\nstatic UniValue ValueFromString(const std::string &str)\n{\n UniValue value;\n BOOST_CHECK(value.setNumStr(str));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(json_parse_errors)\n{\n UniValue value;\n \/\/ Valid\n BOOST_CHECK_EQUAL(value.read(std::string(\"1.0\")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"[1.0]\")), true);\n \/\/ Valid, with trailing whitespace\n BOOST_CHECK_EQUAL(value.read(std::string(\"1.0 \")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"[1.0 ] \")), true);\n \/\/ Invalid, initial garbage\n BOOST_CHECK_EQUAL(value.read(std::string(\"[1.0\")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"[a1.0]\")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"[\\\"a1.0\\\"]\")), true);\n \/\/ Invalid, trailing garbage\n BOOST_CHECK_EQUAL(value.read(std::string(\"1.0sds\")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"1.0]\")), false);\n \/\/ BTC addresses should fail parsing\n BOOST_CHECK_EQUAL(value.read(std::string(\"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W\")), false);\n BOOST_CHECK_EQUAL(value.read(std::string(\"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL\")), false);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace json_spirit;\n\nArray\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n Array result;\n result.push_back(nRequired);\n Array addresses;\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nValue CallRPC(string args)\n{\n vector vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n Array params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n Value result = (*method)(params, false);\n return result;\n }\n catch (Object& objError)\n {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(rpc_tests)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n Value r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n Value r;\n \/\/ input is a 1-of-2 multisig (so is output):\n \n string prevout =\n \"[{\\\"txid\\\":\\\"fa0e4bbd829d23695accaacc63e9fbeeaa44c0bd60a15fd730597a35f83bed54\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914ae20ad2a36715ceb9a4d108855f43739d57bf5ff87\\\",\"\n \"\\\"redeemScript\\\":\\\"522102aa2b9ccf32a31e9dc02dfd609492db92cd6bbf60ac051dddd83bc2ef23835235210204dfd2dd68a82c091ee17e4cbf0b4aade7f4af16ac36bfc86ab059fbbd965d7152ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"A8JyPAauw5YtNaBshKgVjPGyAqt7xv17Ad\\\":18}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"QVLhi74xEKV5Y3JEyMcst7GSGBccgJmuawgjQxGHxjgjXqG6AaR9\\\"\";\n string privkey2 = \"\\\"QWQbSTCKxQb1e7KHuMv88udFTu88tvh1A71h44CC1SLa9hVVGEBT\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK(write_string(ValueFromAmount(0LL), false) == \"0.00000000\");\n BOOST_CHECK(write_string(ValueFromAmount(1LL), false) == \"0.00000001\");\n BOOST_CHECK(write_string(ValueFromAmount(17622195LL), false) == \"0.17622195\");\n BOOST_CHECK(write_string(ValueFromAmount(50000000LL), false) == \"0.50000000\");\n BOOST_CHECK(write_string(ValueFromAmount(89898989LL), false) == \"0.89898989\");\n BOOST_CHECK(write_string(ValueFromAmount(100000000LL), false) == \"1.00000000\");\n BOOST_CHECK(write_string(ValueFromAmount(2099999999999990LL), false) == \"20999999.99999990\");\n BOOST_CHECK(write_string(ValueFromAmount(2099999999999999LL), false) == \"20999999.99999999\");\n}\n\nstatic Value ValueFromString(const std::string &str)\n{\n Value value;\n BOOST_CHECK(read_string(str, value));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK(AmountFromValue(ValueFromString(\"0.00000001\")) == 1LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"0.17622195\")) == 17622195LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"0.5\")) == 50000000LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"0.50000000\")) == 50000000LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"0.89898989\")) == 89898989LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"1.00000000\")) == 100000000LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"20999999.9999999\")) == 2099999999999990LL);\n BOOST_CHECK(AmountFromValue(ValueFromString(\"20999999.99999999\")) == 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nrpc_tests: use BOOST_CHECK_EQUAL\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace json_spirit;\n\nArray\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n Array result;\n result.push_back(nRequired);\n Array addresses;\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nValue CallRPC(string args)\n{\n vector vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n Array params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n Value result = (*method)(params, false);\n return result;\n }\n catch (Object& objError)\n {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(rpc_tests)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n Value r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n Value r;\n \/\/ input is a 1-of-2 multisig (so is output):\n \n string prevout =\n \"[{\\\"txid\\\":\\\"fa0e4bbd829d23695accaacc63e9fbeeaa44c0bd60a15fd730597a35f83bed54\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914ae20ad2a36715ceb9a4d108855f43739d57bf5ff87\\\",\"\n \"\\\"redeemScript\\\":\\\"522102aa2b9ccf32a31e9dc02dfd609492db92cd6bbf60ac051dddd83bc2ef23835235210204dfd2dd68a82c091ee17e4cbf0b4aade7f4af16ac36bfc86ab059fbbd965d7152ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"A8JyPAauw5YtNaBshKgVjPGyAqt7xv17Ad\\\":18}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"QVLhi74xEKV5Y3JEyMcst7GSGBccgJmuawgjQxGHxjgjXqG6AaR9\\\"\";\n string privkey2 = \"\\\"QWQbSTCKxQb1e7KHuMv88udFTu88tvh1A71h44CC1SLa9hVVGEBT\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(0LL), false), \"0.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(1LL), false), \"0.00000001\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(17622195LL), false), \"0.17622195\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(50000000LL), false), \"0.50000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(89898989LL), false), \"0.89898989\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(100000000LL), false), \"1.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999990LL), false), \"20999999.99999990\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999999LL), false), \"20999999.99999999\");\n}\n\nstatic Value ValueFromString(const std::string &str)\n{\n Value value;\n BOOST_CHECK(read_string(str, value));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \"vast\/configuration.h\"\n#include \"vast\/file_system.h\"\n#include \"vast\/logger.h\"\n#include \"vast\/detail\/type_manager.h\"\n#include \"vast\/util\/color.h\"\n\nnamespace vast {\n\nstd::string configuration::banner() const\n{\n std::stringstream ss;\n auto colorize = ! check(\"log.no-colors\");\n if (colorize)\n ss << util::color::red;\n\n ss << \" _ _____ __________\\n\"\n \" | | \/ \/ _ | \/ __\/_ __\/\\n\"\n \" | |\/ \/ __ |_\\\\ \\\\ \/ \/\\n\"\n \" |___\/_\/ |_\/___\/ \/_\/ \";\n\n if (colorize)\n ss << util::color::yellow;\n\n ss << VAST_VERSION;\n\n if (colorize)\n ss << util::color::reset;\n\n return ss.str();\n}\n\nvoid configuration::initialize()\n{\n auto& general = create_block(\"general options\");\n\/\/ TODO: not yet supported.\n\/\/ general.add('c', \"config\", \"configuration file\");\n general.add('h', \"help\", \"display this help\");\n general.add('d', \"directory\", \"VAST directory\").init(\"vast\");\n general.add('z', \"advanced\", \"show advanced options\");\n general.add(\"version\", \"print the version of VAST\");\n\n auto min = 0;\n auto max = VAST_LOG_LEVEL;\n auto range = '[' + std::to_string(min) + '-' + std::to_string(max) + ']';\n\n auto& log = create_block(\"logger options\", \"log\");\n log.add('v', \"console-verbosity\", \"console verbosity \" + range)\n .init(std::min(3, max));\n log.add('V', \"file-verbosity\", \"log file verbosity \" + range)\n .init(std::min(4, max));\n log.add(\"no-colors\", \"don't use colors for console output\");\n log.add(\"function-names\", \"log function names\");\n\n auto& advanced = create_block(\"advanced options\");\n advanced.add('P', \"profiler\", \"spawn the profiler \");\n advanced.add(\"profile-interval\", \"profiling granularity in seconds\").init(1);\n#ifdef VAST_USE_PERFTOOLS_CPU_PROFILER\n advanced.add(\"perftools-cpu\", \"enable gperftools CPU profiling\");\n#endif\n#ifdef VAST_USE_PERFTOOLS_HEAP_PROFILER\n advanced.add(\"perftools-heap\", \"enable gperftools heap profiling\");\n#endif\n advanced.visible(false);\n\n auto& act = create_block(\"actor options\");\n act.add('C', \"core\", \"spawn all core actors\");\n act.add(\/* 'R', *\/ \"receiver\", \"spawn the receiver\");\n act.add(\/* 'A', *\/ \"archive\", \"spawn the archive\");\n act.add(\/* 'X', *\/ \"index\", \"spawn the index\");\n act.add(\/* 'T', *\/ \"tracker\", \"spawn the tracker\");\n act.add(\/* 'S', *\/ \"search\", \"spawn the search\");\n act.add('E', \"exporter\", \"spawn the exporter\").single();\n act.add('I', \"importer\", \"spawn the importer\").single();\n#ifdef VAST_HAVE_EDITLINE\n act.add('Q', \"console\", \"spawn the query console\");\n#endif\n\n auto& imp = create_block(\"import options\", \"import\");\n imp.add(\"batch-size\", \"number of events to ingest in one run\").init(5000);\n imp.add('r', \"read\", \"path to input file\/directory\").single();\n imp.add('i', \"interface\", \"name of interface to read packets from\").single();\n imp.add(\"pcap-cutoff\", \"forego intra-flow packets after this many bytes\").single();\n imp.add(\"pcap-maxflows\", \"number of concurrent flows to track\").init(100000);\n imp.visible(false);\n\n auto& exp = create_block(\"export options\", \"export\");\n exp.add('l', \"limit\", \"maximum number of results\").init(0);\n exp.add('q', \"query\", \"the query string\").single();\n exp.add('w', \"write\", \"path to output file\/directory\").init(\"-\");\n imp.add(\"pcap-flush\", \"flush to disk after this many packets\").init(10000);\n exp.visible(false);\n\n auto& recv = create_block(\"receiver options\", \"receiver\");\n recv.add(\"host\", \"hostname\/address of the receiver\").init(\"127.0.0.1\");\n recv.add(\"port\", \"TCP port of the receiver\").init(42000);\n recv.visible(false);\n\n auto& arch = create_block(\"archive options\", \"archive\");\n arch.add(\"max-segment-size\", \"maximum segment size in MB\").init(128);\n arch.add(\"max-segments\", \"maximum segments cached in memory\").init(10);\n arch.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n arch.add(\"port\", \"TCP port of the archive\").init(42003);\n arch.visible(false);\n\n auto& idx = create_block(\"index options\", \"index\");\n idx.add('p', \"partition\", \"name of the partition to append to\").single();\n idx.add(\"batch-size\", \"number of events to index in one run\").init(1000);\n idx.add(\"rebuild\", \"rebuild indexes from archive\");\n idx.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n idx.add(\"port\", \"TCP port of the index\").init(42004);\n idx.visible(false);\n\n auto& track = create_block(\"ID tracker options\", \"tracker\");\n track.add(\"host\", \"hostname\/address of the tracker\").init(\"127.0.0.1\");\n track.add(\"port\", \"TCP port of the ID tracker\").init(42002);\n track.visible(false);\n\n auto& srch = create_block(\"search options\", \"search\");\n srch.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n srch.add(\"port\", \"TCP port of the search\").init(42001);\n srch.visible(false);\n\n add_dependency(\"profile-interval\", \"profiler\");\n#ifdef VAST_USE_PERFTOOLS_CPU_PROFILER\n add_dependency(\"perftools-cpu\", \"profiler\");\n#endif\n#ifdef VAST_USE_PERFTOOLS_HEAP_PROFILER\n add_dependency(\"perftools-heap\", \"profiler\");\n#endif\n\n#ifdef VAST_HAVE_EDITLINE\n add_conflict(\"console\", \"core\");\n add_conflict(\"console\", \"tracker\");\n add_conflict(\"console\", \"archive\");\n add_conflict(\"console\", \"index\");\n add_conflict(\"console\", \"importer\");\n add_conflict(\"console\", \"exporter\");\n add_conflict(\"console\", \"search\");\n add_conflict(\"console\", \"receiver\");\n#endif\n\n add_dependency(\"import.format\", \"importer\");\n add_dependency(\"import.read\", \"importer\");\n add_dependency(\"import.interface\", \"importer\");\n add_dependency(\"import.submit\", \"importer\");\n add_dependency(\"import.pcap-cutoff\", \"importer\");\n add_dependency(\"import.pcap-maxflows\", \"importer\");\n add_conflict(\"import.read\", \"import.interface\");\n\n add_dependency(\"export.limit\", \"exporter\");\n add_dependency(\"export.format\", \"exporter\");\n add_dependency(\"export.query\", \"exporter\");\n add_dependency(\"export.write\", \"exporter\");\n add_dependency(\"export.pcap-flush\", \"exporter\");\n add_conflict(\"importer\", \"exporter\");\n add_conflict(\"receiver\", \"exporter\");\n add_conflict(\"tracker\", \"exporter\");\n\n add_dependencies(\"index.partition\", {\"index\", \"core\"});\n add_conflict(\"index.rebuild\", \"index.partition\");\n\n}\n\n} \/\/ namespace vast\nIncrease max concurrent flows to 1M.#include \"vast\/configuration.h\"\n#include \"vast\/file_system.h\"\n#include \"vast\/logger.h\"\n#include \"vast\/detail\/type_manager.h\"\n#include \"vast\/util\/color.h\"\n\nnamespace vast {\n\nstd::string configuration::banner() const\n{\n std::stringstream ss;\n auto colorize = ! check(\"log.no-colors\");\n if (colorize)\n ss << util::color::red;\n\n ss << \" _ _____ __________\\n\"\n \" | | \/ \/ _ | \/ __\/_ __\/\\n\"\n \" | |\/ \/ __ |_\\\\ \\\\ \/ \/\\n\"\n \" |___\/_\/ |_\/___\/ \/_\/ \";\n\n if (colorize)\n ss << util::color::yellow;\n\n ss << VAST_VERSION;\n\n if (colorize)\n ss << util::color::reset;\n\n return ss.str();\n}\n\nvoid configuration::initialize()\n{\n auto& general = create_block(\"general options\");\n\/\/ TODO: not yet supported.\n\/\/ general.add('c', \"config\", \"configuration file\");\n general.add('h', \"help\", \"display this help\");\n general.add('d', \"directory\", \"VAST directory\").init(\"vast\");\n general.add('z', \"advanced\", \"show advanced options\");\n general.add(\"version\", \"print the version of VAST\");\n\n auto min = 0;\n auto max = VAST_LOG_LEVEL;\n auto range = '[' + std::to_string(min) + '-' + std::to_string(max) + ']';\n\n auto& log = create_block(\"logger options\", \"log\");\n log.add('v', \"console-verbosity\", \"console verbosity \" + range)\n .init(std::min(3, max));\n log.add('V', \"file-verbosity\", \"log file verbosity \" + range)\n .init(std::min(4, max));\n log.add(\"no-colors\", \"don't use colors for console output\");\n log.add(\"function-names\", \"log function names\");\n\n auto& advanced = create_block(\"advanced options\");\n advanced.add('P', \"profiler\", \"spawn the profiler \");\n advanced.add(\"profile-interval\", \"profiling granularity in seconds\").init(1);\n#ifdef VAST_USE_PERFTOOLS_CPU_PROFILER\n advanced.add(\"perftools-cpu\", \"enable gperftools CPU profiling\");\n#endif\n#ifdef VAST_USE_PERFTOOLS_HEAP_PROFILER\n advanced.add(\"perftools-heap\", \"enable gperftools heap profiling\");\n#endif\n advanced.visible(false);\n\n auto& act = create_block(\"actor options\");\n act.add('C', \"core\", \"spawn all core actors\");\n act.add(\/* 'R', *\/ \"receiver\", \"spawn the receiver\");\n act.add(\/* 'A', *\/ \"archive\", \"spawn the archive\");\n act.add(\/* 'X', *\/ \"index\", \"spawn the index\");\n act.add(\/* 'T', *\/ \"tracker\", \"spawn the tracker\");\n act.add(\/* 'S', *\/ \"search\", \"spawn the search\");\n act.add('E', \"exporter\", \"spawn the exporter\").single();\n act.add('I', \"importer\", \"spawn the importer\").single();\n#ifdef VAST_HAVE_EDITLINE\n act.add('Q', \"console\", \"spawn the query console\");\n#endif\n\n auto& imp = create_block(\"import options\", \"import\");\n imp.add(\"batch-size\", \"number of events to ingest in one run\").init(5000);\n imp.add('r', \"read\", \"path to input file\/directory\").single();\n imp.add('i', \"interface\", \"name of interface to read packets from\").single();\n imp.add(\"pcap-cutoff\", \"forego intra-flow packets after this many bytes\").single();\n imp.add(\"pcap-maxflows\", \"number of concurrent flows to track\").init(1000000);\n imp.visible(false);\n\n auto& exp = create_block(\"export options\", \"export\");\n exp.add('l', \"limit\", \"maximum number of results\").init(0);\n exp.add('q', \"query\", \"the query string\").single();\n exp.add('w', \"write\", \"path to output file\/directory\").init(\"-\");\n imp.add(\"pcap-flush\", \"flush to disk after this many packets\").init(10000);\n exp.visible(false);\n\n auto& recv = create_block(\"receiver options\", \"receiver\");\n recv.add(\"host\", \"hostname\/address of the receiver\").init(\"127.0.0.1\");\n recv.add(\"port\", \"TCP port of the receiver\").init(42000);\n recv.visible(false);\n\n auto& arch = create_block(\"archive options\", \"archive\");\n arch.add(\"max-segment-size\", \"maximum segment size in MB\").init(128);\n arch.add(\"max-segments\", \"maximum segments cached in memory\").init(10);\n arch.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n arch.add(\"port\", \"TCP port of the archive\").init(42003);\n arch.visible(false);\n\n auto& idx = create_block(\"index options\", \"index\");\n idx.add('p', \"partition\", \"name of the partition to append to\").single();\n idx.add(\"batch-size\", \"number of events to index in one run\").init(1000);\n idx.add(\"rebuild\", \"rebuild indexes from archive\");\n idx.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n idx.add(\"port\", \"TCP port of the index\").init(42004);\n idx.visible(false);\n\n auto& track = create_block(\"ID tracker options\", \"tracker\");\n track.add(\"host\", \"hostname\/address of the tracker\").init(\"127.0.0.1\");\n track.add(\"port\", \"TCP port of the ID tracker\").init(42002);\n track.visible(false);\n\n auto& srch = create_block(\"search options\", \"search\");\n srch.add(\"host\", \"hostname\/address of the archive\").init(\"127.0.0.1\");\n srch.add(\"port\", \"TCP port of the search\").init(42001);\n srch.visible(false);\n\n add_dependency(\"profile-interval\", \"profiler\");\n#ifdef VAST_USE_PERFTOOLS_CPU_PROFILER\n add_dependency(\"perftools-cpu\", \"profiler\");\n#endif\n#ifdef VAST_USE_PERFTOOLS_HEAP_PROFILER\n add_dependency(\"perftools-heap\", \"profiler\");\n#endif\n\n#ifdef VAST_HAVE_EDITLINE\n add_conflict(\"console\", \"core\");\n add_conflict(\"console\", \"tracker\");\n add_conflict(\"console\", \"archive\");\n add_conflict(\"console\", \"index\");\n add_conflict(\"console\", \"importer\");\n add_conflict(\"console\", \"exporter\");\n add_conflict(\"console\", \"search\");\n add_conflict(\"console\", \"receiver\");\n#endif\n\n add_dependency(\"import.format\", \"importer\");\n add_dependency(\"import.read\", \"importer\");\n add_dependency(\"import.interface\", \"importer\");\n add_dependency(\"import.submit\", \"importer\");\n add_dependency(\"import.pcap-cutoff\", \"importer\");\n add_dependency(\"import.pcap-maxflows\", \"importer\");\n add_conflict(\"import.read\", \"import.interface\");\n\n add_dependency(\"export.limit\", \"exporter\");\n add_dependency(\"export.format\", \"exporter\");\n add_dependency(\"export.query\", \"exporter\");\n add_dependency(\"export.write\", \"exporter\");\n add_dependency(\"export.pcap-flush\", \"exporter\");\n add_conflict(\"importer\", \"exporter\");\n add_conflict(\"receiver\", \"exporter\");\n add_conflict(\"tracker\", \"exporter\");\n\n add_dependencies(\"index.partition\", {\"index\", \"core\"});\n add_conflict(\"index.rebuild\", \"index.partition\");\n\n}\n\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"#include \n#include \"ScheduleActualizer.h\"\n#include \"Extensions\/ScheduleActualizationAlgorithm.h\"\n\nnamespace Scheduler\n{\n\n ScheduleActualizer::ScheduleActualizer(Schedule *schedule):\n schedule(schedule),\n algorithms_factory(nullptr),\n\tis_actualizing(false)\n {\n }\n\n\tScheduleActualizer::ScheduleActualizer(Schedule * schedule, const ScheduleActualizer & rhs):\n\t\tschedule(schedule),\n\t\talgorithms_factory(rhs.algorithms_factory)\n\t{\n\t\tfor (ScheduleActualizationAlgorithm* algorithm : rhs.algorithms)\n\t\t{\n\t\t\talgorithms.push_back(algorithm->clone(schedule, algorithms_factory));\n\t\t}\n\t}\n\n void ScheduleActualizer::onOperationAdded(const Stop *stop, const Operation *operation) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationAdded(stop, operation);\n }\n\n void ScheduleActualizer::onOperationRemoved(const Stop *stop) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationRemoved(stop);\n }\n\n void ScheduleActualizer::onStopAdded(const Run *run, const Stop *stop, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopAdded(run, stop, index);\n }\n\n void ScheduleActualizer::onStopRemoved(const Run *run, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopRemoved(run, index);\n }\n\n\tvoid ScheduleActualizer::onStopReplaced(const Run * run, const Stop * new_stop, size_t index)\n\t{\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopReplaced(run, new_stop, index);\n\t}\n\n void ScheduleActualizer::onRunVehicleChanged(const Run *run, const Vehicle *vehicle) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunVehicleChanged(run, vehicle);\n }\n\n void ScheduleActualizer::onRunAdded(const Run *run, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunAdded(run, index);\n }\n\n void ScheduleActualizer::onRunRemoved() {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunRemoved();\n }\n\n void ScheduleActualizer::actualize() {\n\t\tif(is_actualizing) return;\n\t\tis_actualizing = true;\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->actualize();\n\t\tis_actualizing = false;\n }\n\n ScheduleActualizer::~ScheduleActualizer() {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithms_factory->destroyObject(algorithm);\n }\n\n void ScheduleActualizer::onStopNextRouteChanged(const Stop *stop) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopNextRouteChanged(stop);\n }\n\n void ScheduleActualizer::setScheduleActualizationAlgorithmsFactory(\n Factory *factory) {\n this->algorithms_factory = factory;\n }\n}[#65] Fixed copy constructor of ScheduleActualizer#include \n#include \"ScheduleActualizer.h\"\n#include \"Extensions\/ScheduleActualizationAlgorithm.h\"\n\nnamespace Scheduler\n{\n\n ScheduleActualizer::ScheduleActualizer(Schedule *schedule):\n schedule(schedule),\n algorithms_factory(nullptr),\n\tis_actualizing(false)\n {\n }\n\n\tScheduleActualizer::ScheduleActualizer(Schedule * schedule, const ScheduleActualizer & rhs):\n\t\tschedule(schedule),\n\t\talgorithms_factory(rhs.algorithms_factory),\n\t\tis_actualizing(false)\n\t{\n\t\tfor (ScheduleActualizationAlgorithm* algorithm : rhs.algorithms)\n\t\t{\n\t\t\talgorithms.push_back(algorithm->clone(schedule, algorithms_factory));\n\t\t}\n\t}\n\n void ScheduleActualizer::onOperationAdded(const Stop *stop, const Operation *operation) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationAdded(stop, operation);\n }\n\n void ScheduleActualizer::onOperationRemoved(const Stop *stop) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationRemoved(stop);\n }\n\n void ScheduleActualizer::onStopAdded(const Run *run, const Stop *stop, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopAdded(run, stop, index);\n }\n\n void ScheduleActualizer::onStopRemoved(const Run *run, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopRemoved(run, index);\n }\n\n\tvoid ScheduleActualizer::onStopReplaced(const Run * run, const Stop * new_stop, size_t index)\n\t{\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopReplaced(run, new_stop, index);\n\t}\n\n void ScheduleActualizer::onRunVehicleChanged(const Run *run, const Vehicle *vehicle) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunVehicleChanged(run, vehicle);\n }\n\n void ScheduleActualizer::onRunAdded(const Run *run, size_t index) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunAdded(run, index);\n }\n\n void ScheduleActualizer::onRunRemoved() {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunRemoved();\n }\n\n void ScheduleActualizer::actualize() {\n\t\tif(is_actualizing) return;\n\t\tis_actualizing = true;\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->actualize();\n\t\tis_actualizing = false;\n }\n\n ScheduleActualizer::~ScheduleActualizer() {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithms_factory->destroyObject(algorithm);\n }\n\n void ScheduleActualizer::onStopNextRouteChanged(const Stop *stop) {\n for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopNextRouteChanged(stop);\n }\n\n void ScheduleActualizer::setScheduleActualizationAlgorithmsFactory(\n Factory *factory) {\n this->algorithms_factory = factory;\n }\n}<|endoftext|>"} {"text":"\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2019, Cauldron Development LLC\n Copyright (c) 2003-2017, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with the C! library. If not, see\n .\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Base64.h\"\n\n#include \n\n#include \n\n\nusing namespace std;\nusing namespace cb;\n\n\nconst char *Base64::encodeTable =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nconst signed char Base64::decodeTable[256] = {\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,\n -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n};\n\n\nstring Base64::encode(const string &s) const {\n return encode(s.c_str(), s.length());\n}\n\n\nstring Base64::encode(const char *_s, unsigned length) const {\n const uint8_t *s = (uint8_t *)_s;\n const uint8_t *end = s + length;\n string result;\n unsigned size = length \/ 3 * 4 + 4; \/\/ Not exact\n if (width) size += (size \/ width) * 2;\n result.reserve(size);\n\n unsigned col = 0;\n int padding = 0;\n uint8_t a, b, c;\n while (s != end) {\n a = *s++;\n if (s == end) {c = b = 0; padding = 2;}\n else {\n b = *s++;\n if (s == end) {c = 0; padding = 1;}\n else c = *s++;\n }\n\n result += encode(63 & (a >> 2));\n result += encode(63 & (a << 4 | b >> 4));\n if (pad && padding == 2) result += pad;\n else result += encode(63 & (b << 2 | c >> 6));\n if (pad && padding) result += pad;\n else result += encode(63 & c);\n\n if (s != end && width) {\n col += 4;\n if (col == width) {\n col = 0;\n result += \"\\r\\n\";\n }\n }\n }\n\n return result;\n}\n\n\nstring Base64::decode(const string &s) const {\n string result;\n result.reserve(s.length() \/ 4 * 3 + 1);\n\n string::const_iterator it = s.begin();\n while (it != s.end() && isspace(*it)) it++;\n\n while (it != s.end()) {\n char w = decode(next(it, s.end()));\n char x = it == s.end() ? -2 : decode(next(it, s.end()));\n char y = it == s.end() ? -2 : decode(next(it, s.end()));\n char z = it == s.end() ? -2 : decode(next(it, s.end()));\n\n if (w == -2 || x == -2 || w == -1 || x == -1 || y == -1 || z == -1)\n THROW(\"Invalid Base64 data at \" << (it - s.begin()));\n\n result += (char)(w << 2 | x >> 4);\n if (y != -2) {\n result += (char)(x << 4 | y >> 2);\n if (z != -2) result += (char)(y << 6 | z);\n }\n }\n\n return result;\n}\n\n\nchar Base64::next(string::const_iterator &it,\n string::const_iterator end) {\n char c = *it++;\n while (it != end && isspace(*it)) it++;\n return c;\n}\n\n\nchar Base64::encode(int x) const {\n if (x == 62) return a;\n if (x == 63) return b;\n return encodeTable[x];\n}\n\n\nint Base64::decode(char x) const {\n if (x == a) return 62;\n if (x == b) return 63;\n if (x == pad) return -2;\n return decodeTable[(int)x];\n}\nFixed Base64 w\/ no padding\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2019, Cauldron Development LLC\n Copyright (c) 2003-2017, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with the C! library. If not, see\n .\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Base64.h\"\n\n#include \n\n#include \n\n\nusing namespace std;\nusing namespace cb;\n\n\nconst char *Base64::encodeTable =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nconst signed char Base64::decodeTable[256] = {\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,\n -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n};\n\n\nstring Base64::encode(const string &s) const {\n return encode(s.c_str(), s.length());\n}\n\n\nstring Base64::encode(const char *_s, unsigned length) const {\n const uint8_t *s = (uint8_t *)_s;\n const uint8_t *end = s + length;\n string result;\n unsigned size = length \/ 3 * 4 + 4; \/\/ Not exact\n if (width) size += (size \/ width) * 2;\n result.reserve(size);\n\n unsigned col = 0;\n int padding = 0;\n uint8_t a, b, c;\n while (s != end) {\n a = *s++;\n if (s == end) {c = b = 0; padding = 2;}\n else {\n b = *s++;\n if (s == end) {c = 0; padding = 1;}\n else c = *s++;\n }\n\n result += encode(63 & (a >> 2));\n result += encode(63 & (a << 4 | b >> 4));\n if (padding == 2) {if (pad) result += pad;}\n else result += encode(63 & (b << 2 | c >> 6));\n if (padding) {if (pad) result += pad;}\n else result += encode(63 & c);\n\n if (s != end && width) {\n col += 4;\n if (col == width) {\n col = 0;\n result += \"\\r\\n\";\n }\n }\n }\n\n return result;\n}\n\n\nstring Base64::decode(const string &s) const {\n string result;\n result.reserve(s.length() \/ 4 * 3 + 1);\n\n string::const_iterator it = s.begin();\n while (it != s.end() && isspace(*it)) it++;\n\n while (it != s.end()) {\n char w = decode(next(it, s.end()));\n char x = it == s.end() ? -2 : decode(next(it, s.end()));\n char y = it == s.end() ? -2 : decode(next(it, s.end()));\n char z = it == s.end() ? -2 : decode(next(it, s.end()));\n\n if (w == -2 || x == -2 || w == -1 || x == -1 || y == -1 || z == -1)\n THROW(\"Invalid Base64 data at \" << (it - s.begin()));\n\n result += (char)(w << 2 | x >> 4);\n if (y != -2) {\n result += (char)(x << 4 | y >> 2);\n if (z != -2) result += (char)(y << 6 | z);\n }\n }\n\n return result;\n}\n\n\nchar Base64::next(string::const_iterator &it,\n string::const_iterator end) {\n char c = *it++;\n while (it != end && isspace(*it)) it++;\n return c;\n}\n\n\nchar Base64::encode(int x) const {\n if (x == 62) return a;\n if (x == 63) return b;\n return encodeTable[x];\n}\n\n\nint Base64::decode(char x) const {\n if (x == a) return 62;\n if (x == b) return 63;\n if (x == pad) return -2;\n return decodeTable[(int)x];\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2019, Cauldron Development LLC\n Copyright (c) 2003-2017, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with the C! library. If not, see\n .\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Base64.h\"\n\n#include \n\n#include \n\n\nusing namespace std;\nusing namespace cb;\n\n\nnamespace {\n char next(string::const_iterator &it, string::const_iterator end) {\n char c = *it++;\n while (it != end && isspace(*it)) it++;\n return c;\n }\n}\n\n\nconst char *Base64::encodeTable =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nconst signed char Base64::decodeTable[256] = {\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,\n -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n};\n\n\nstring Base64::encode(const string &s) const {\n return encode(s.c_str(), s.length());\n}\n\n\nstring Base64::encode(const char *_s, unsigned length) const {\n const uint8_t *s = (uint8_t *)_s;\n const uint8_t *end = s + length;\n\n struct Result : public string {\n unsigned col = 0;\n unsigned width;\n\n Result(unsigned length, unsigned width) : width(width) {\n unsigned size = length \/ 3 * 4 + 4; \/\/ Not exact\n if (width) size += (size \/ width) * 2;\n reserve(size);\n }\n\n void append(char c) {\n if (width) {\n if (col == width) {\n col = 0;\n string::append(\"\\r\\n\");\n\n } else col++;\n }\n\n string::append(1, c);\n }\n };\n\n Result result(length, width);\n int padding = 0;\n uint8_t a, b, c;\n\n while (s != end) {\n a = *s++;\n if (s == end) {c = b = 0; padding = 2;}\n else {\n b = *s++;\n if (s == end) {c = 0; padding = 1;}\n else c = *s++;\n }\n\n result.append(encode(63 & (a >> 2)));\n result.append(encode(63 & (a << 4 | b >> 4)));\n if (padding == 2) {if (pad) result.append(pad);}\n else result.append(encode(63 & (b << 2 | c >> 6)));\n if (padding) {if (pad) result.append(pad);}\n else result.append(encode(63 & c));\n }\n\n return result;\n}\n\n\nstring Base64::decode(const string &s) const {\n string result;\n result.reserve(s.length() \/ 4 * 3 + 1);\n\n string::const_iterator it = s.begin();\n while (it != s.end() && isspace(*it)) it++;\n\n while (it != s.end()) {\n char w = decode(next(it, s.end()));\n char x = it == s.end() ? -2 : decode(next(it, s.end()));\n char y = it == s.end() ? -2 : decode(next(it, s.end()));\n char z = it == s.end() ? -2 : decode(next(it, s.end()));\n\n if (w == -1 || w == -2 || x == -1 || x == -2 || y == -1 || z == -1)\n THROW(\"Invalid Base64 data at \" << (it - s.begin()));\n\n result += (char)(w << 2 | x >> 4);\n if (y != -2) {\n result += (char)(x << 4 | y >> 2);\n if (z != -2) result += (char)(y << 6 | z);\n }\n }\n\n return result;\n}\n\n\nstring Base64::decode(const char *s, unsigned length) const {\n return decode(string(s, length));\n}\n\n\nchar Base64::encode(int x) const {\n if (x == 62) return a;\n if (x == 63) return b;\n return encodeTable[x];\n}\n\n\nint Base64::decode(char x) const {\n if (x == a) return 62;\n if (x == b) return 63;\n if (x == pad) return -2;\n return decodeTable[(int)x];\n}\nMove result\/******************************************************************************\\\n\n This file is part of the C! library. A.K.A the cbang library.\n\n Copyright (c) 2003-2019, Cauldron Development LLC\n Copyright (c) 2003-2017, Stanford University\n All rights reserved.\n\n The C! library is free software: you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation, either version 2.1 of\n the License, or (at your option) any later version.\n\n The C! library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with the C! library. If not, see\n .\n\n In addition, BSD licensing may be granted on a case by case basis\n by written permission from at least one of the copyright holders.\n You may request written permission by emailing the authors.\n\n For information regarding this software email:\n Joseph Coffland\n joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Base64.h\"\n\n#include \n\n#include \n#include \/\/ std::move()\n\n\nusing namespace std;\nusing namespace cb;\n\n\nnamespace {\n char next(string::const_iterator &it, string::const_iterator end) {\n char c = *it++;\n while (it != end && isspace(*it)) it++;\n return c;\n }\n}\n\n\nconst char *Base64::encodeTable =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nconst signed char Base64::decodeTable[256] = {\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,\n -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n};\n\n\nstring Base64::encode(const string &s) const {\n return encode(s.c_str(), s.length());\n}\n\n\nstring Base64::encode(const char *_s, unsigned length) const {\n const uint8_t *s = (uint8_t *)_s;\n const uint8_t *end = s + length;\n\n struct Result : public string {\n unsigned col = 0;\n unsigned width;\n\n Result(unsigned length, unsigned width) : width(width) {\n unsigned size = length \/ 3 * 4 + 4; \/\/ Not exact\n if (width) size += (size \/ width) * 2;\n reserve(size);\n }\n\n void append(char c) {\n if (width) {\n if (col == width) {\n col = 0;\n string::append(\"\\r\\n\");\n\n } else col++;\n }\n\n string::append(1, c);\n }\n };\n\n Result result(length, width);\n int padding = 0;\n uint8_t a, b, c;\n\n while (s != end) {\n a = *s++;\n if (s == end) {c = b = 0; padding = 2;}\n else {\n b = *s++;\n if (s == end) {c = 0; padding = 1;}\n else c = *s++;\n }\n\n result.append(encode(63 & (a >> 2)));\n result.append(encode(63 & (a << 4 | b >> 4)));\n if (padding == 2) {if (pad) result.append(pad);}\n else result.append(encode(63 & (b << 2 | c >> 6)));\n if (padding) {if (pad) result.append(pad);}\n else result.append(encode(63 & c));\n }\n\n return move(result);\n}\n\n\nstring Base64::decode(const string &s) const {\n string result;\n result.reserve(s.length() \/ 4 * 3 + 1);\n\n string::const_iterator it = s.begin();\n while (it != s.end() && isspace(*it)) it++;\n\n while (it != s.end()) {\n char w = decode(next(it, s.end()));\n char x = it == s.end() ? -2 : decode(next(it, s.end()));\n char y = it == s.end() ? -2 : decode(next(it, s.end()));\n char z = it == s.end() ? -2 : decode(next(it, s.end()));\n\n if (w == -1 || w == -2 || x == -1 || x == -2 || y == -1 || z == -1)\n THROW(\"Invalid Base64 data at \" << (it - s.begin()));\n\n result += (char)(w << 2 | x >> 4);\n if (y != -2) {\n result += (char)(x << 4 | y >> 2);\n if (z != -2) result += (char)(y << 6 | z);\n }\n }\n\n return result;\n}\n\n\nstring Base64::decode(const char *s, unsigned length) const {\n return decode(string(s, length));\n}\n\n\nchar Base64::encode(int x) const {\n if (x == 62) return a;\n if (x == 63) return b;\n return encodeTable[x];\n}\n\n\nint Base64::decode(char x) const {\n if (x == a) return 62;\n if (x == b) return 63;\n if (x == pad) return -2;\n return decodeTable[(int)x];\n}\n<|endoftext|>"} {"text":"\/\/ main.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Utilities.h\"\n\n\/\/ Functions to load in a single image or all images\nMat loadImage(char* location, char* file);\nMat* loadImages(int numberOfImages, char* location, char** files);\n\n\/\/ A function which temporarily resizes images before showing them\nvoid showImage(char* name, Mat image);\n\n\/\/ \"Sign\" functions - used to detect bus stop signs\nMat findSign(Mat image);\nMat binaryImage(Mat image);\nMat backProjection(Mat image, Mat yellow);\nMat getHue(Mat image);\nMat templateMatching(Mat image, Mat templateImage);\n\n\/\/ \"Number\" function - used to detect the stop number from the sign\nint digitRecognition(Mat image);\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tcout << \"Using OpenCV \" << CV_VERSION << endl;\n\tchar* testLocation = \"Media\/Test Images\/\";\t\/\/ Location of bus stop sign images\n\t\n\t\/\/ Bus stop sign images\n\tchar* testFiles[] = {\n\t\t\"2809 a.jpg\",\n\t\t\"2809 b.jpg\",\n\t\t\"2830 a.jpg\",\n\t\t\"2830 b.jpg\",\n\t\t\"2838 a.jpg\",\n\t\t\"2838 b.jpg\",\n\t\t\"2838 c.jpg\",\n\t\t\"2838 d.jpg\",\n\t\t\"2839 a.jpg\",\n\t\t\"2839 b.jpg\",\n\t\t\"2839 c.jpg\",\n\t\t\"2839 d.jpg\"\n\t};\n\n\tchar* templateLocation = \"Media\/Templates\/\";\t\/\/ Location of sample stop sign images\n\n\t\/\/ Sample stop sign images\n\tchar* templateFiles[] = {\n\t\t\"stop.png\",\n\t\t\"stop&no.png\",\n\t\t\"stop2.png\",\n\t\t\"stop&no2.png\",\n\t\t\"yellow.png\"\n\t};\n\n\tMat sign = loadImage(testLocation, testFiles[6]);\n\tMat templateSign = loadImage(templateLocation, templateFiles[2]);\n\tMat yellow = loadImage(templateLocation, templateFiles[4]);\n\n\tshowImage(\"Bus Stop Sign\", sign);\n\tMat hsvSign = findSign(sign);\n\tMat binary = binaryImage(sign);\n\tMat backProjSign = backProjection(sign, yellow);\n\t\/\/Mat templateMatch = templateMatching(sign, templateSign);\n\tMat templateMatch = templateMatching(sign, yellow);\n\n\tshowImage(\"HSV\", hsvSign);\n\tshowImage(\"Binary\", binary);\n\tshowImage(\"Back Projection\", backProjSign);\n\tshowImage(\"Template Matching\", templateMatch);\n\twaitKey(0);\n\n\tint stopNumber = digitRecognition(backProjSign);\n\n\t\/*int numberOfTestImages = sizeof(testFiles) \/ sizeof(testFiles[0]);\n\tMat* busStops = loadImages(numberOfTestImages, testLocation, testFiles);\n\tint numberOfTemplateImages = sizeof(templateFiles) \/ sizeof(templateFiles[0]);\n\tMat* templates = loadImages(numberOfTemplateImages, templateLocation, templateFiles);\n\n\tfor (int i = 0; i < numberOfTestImages; i++) {\n\t\tcout << \"Processing image \" << (i + 1) << endl;\n\t\tshowImage(\"Sign\", busStops[i]);\n\t\tMat hsvSign = findSign(busStops[i]);\n\t\tMat binary = binaryImage(busStops[i]);\n\t\tMat backProjSign = backProjection(busStops[i], templates[4]);\n\t\tMat templateMatch;\n\t\tif (i == 0 || i == 1) {\n\t\t\t\/\/ templates[0] or templates[1]\n\t\t\ttemplateMatch = templateMatching(busStops[i], templates[0]);\n\n\t\t}\n\t\telse {\n\t\t\t\/\/ templates[2] or templates[3]\n\t\t\ttemplateMatch = templateMatching(busStops[i], templates[2]);\n\n\t\t}\n\n\t\tshowImage(\"HSV\", hsvSign);\n\t\tshowImage(\"Binary\", binary);\n\t\tshowImage(\"Back Projection\", backProjSign);\n\t\tshowImage(\"Template Matching\", templateMatch);\n\t\t\n\t\twaitKey(0);\n\t}*\/\n\n\treturn 0;\n}\n\nMat loadImage(char* location, char* file) {\n\tstring filename(location);\n\tfilename.append(file);\n\tMat image = imread(filename, 1);\n\n\treturn image;\n}\n\nMat* loadImages(int numberOfImages, char* location, char** files) {\n\tMat* images = new Mat[numberOfImages];\n\tfor (int i = 0; i < numberOfImages; i++) {\n\t\tstring filename(location);\n\t\tfilename.append(files[i]);\n\t\tcout << \"Loading image \" << (i + 1) << \": \" << filename << endl;\n\t\timages[i] = imread(filename, 1);\n\t}\n\treturn images;\n}\n\nvoid showImage(char* name, Mat image) {\n\tresize(image, image, Size(image.cols \/ 4, image.rows \/ 4));\n\timshow(name, image);\n\n\treturn;\n}\n\nMat findSign(Mat image) {\n\tMat hsv;\n\tcvtColor(image, hsv, CV_BGR2HSV);\n\tinRange(hsv, Scalar(15, 135, 140), Scalar(30, 255, 255), hsv);\n\n\treturn hsv;\n}\n\nMat binaryImage(Mat image) {\n\tMat greyImage, binaryResult;\n\tcvtColor(image, greyImage, CV_BGR2GRAY);\n\tthreshold(greyImage, binaryResult, 200, 255, THRESH_BINARY);\n\n\treturn binaryResult;\n}\n\nMat backProjection(Mat image, Mat yellow) {\n\tMat imageHue = getHue(image);\n\tMat yellowHue = getHue(yellow);\n\n\tMat hist;\n\tint histSize = 180;\n\tfloat hue_range[] = { 0, 180 };\n\tconst float* ranges = { hue_range };\n\n\tcalcHist(&yellowHue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false);\n\tnormalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat());\n\n\tMat backProject;\n\tcalcBackProject(&imageHue, 1, 0, hist, backProject, &ranges, 1, true);\n\n\treturn backProject;\n}\n\nMat getHue(Mat image) {\n\tMat hsv, hue;\n\tcvtColor(image, hsv, CV_BGR2HSV);\n\n\thue.create(hsv.size(), hsv.depth());\n\tint ch[] = { 0, 0 };\n\tmixChannels(&hsv, 1, &hue, 1, ch, 1);\n\n\treturn hue;\n}\n\nMat templateMatching(Mat image, Mat templateImage) {\n\tMat result;\n\n\tMat imageDisplay;\n\timage.copyTo(imageDisplay);\n\n\tint rows = image.rows - templateImage.rows + 1;\n\tint cols = image.cols - templateImage.cols + 1;\n\n\tresult.create(rows, cols, CV_32FC1);\n\n\tmatchTemplate(image, templateImage, result, CV_TM_SQDIFF);\n\tnormalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());\n\n\tdouble minVal, maxVal;\n\tPoint minLoc, maxLoc, matchLoc;\n\n\tminMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());\n\n\tmatchLoc = minLoc;\n\n\trectangle(imageDisplay, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0);\n\trectangle(result, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0);\n\n\t\/*showImage(\"Image\", imageDisplay);\n\tshowImage(\"Result\", result);\n\twaitKey(0);*\/\n\n\t\/\/return result;\n\treturn imageDisplay;\n}\n\nint digitRecognition(Mat image) {\n\t\/\/ TODO: recognise numbers from sign\n\t\/\/ Statistical Pattern Recognition\n\t\/\/ Scene Text Recognition - OCRTesseract\n\t\/\/ Template Matching\n\t\/\/ Chamfer Matching\n\t\/\/ Haar Classifiers\n\n\treturn 0;\n}renamed variable\/\/ main.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Utilities.h\"\n\n\/\/ Functions to load in a single image or all images\nMat loadImage(char* location, char* file);\nMat* loadImages(int numberOfImages, char* location, char** files);\n\n\/\/ A function which temporarily resizes images before showing them\nvoid showImage(char* name, Mat image);\n\n\/\/ \"Sign\" functions - used to detect bus stop signs\nMat findSign(Mat image);\nMat binaryImage(Mat image);\nMat backProjection(Mat image, Mat yellow);\nMat getHue(Mat image);\nMat templateMatching(Mat image, Mat templateImage);\n\n\/\/ \"Number\" function - used to detect the stop number from the sign\nint digitRecognition(Mat image);\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tcout << \"Using OpenCV \" << CV_VERSION << endl;\n\tchar* testLocation = \"Media\/Test Images\/\";\t\/\/ Location of bus stop sign images\n\t\n\t\/\/ Bus stop sign images\n\tchar* testFiles[] = {\n\t\t\"2809 a.jpg\",\n\t\t\"2809 b.jpg\",\n\t\t\"2830 a.jpg\",\n\t\t\"2830 b.jpg\",\n\t\t\"2838 a.jpg\",\n\t\t\"2838 b.jpg\",\n\t\t\"2838 c.jpg\",\n\t\t\"2838 d.jpg\",\n\t\t\"2839 a.jpg\",\n\t\t\"2839 b.jpg\",\n\t\t\"2839 c.jpg\",\n\t\t\"2839 d.jpg\"\n\t};\n\n\tchar* templateLocation = \"Media\/Templates\/\";\t\/\/ Location of sample stop sign images\n\n\t\/\/ Sample stop sign images\n\tchar* templateFiles[] = {\n\t\t\"stop.png\",\n\t\t\"stop&no.png\",\n\t\t\"stop2.png\",\n\t\t\"stop&no2.png\",\n\t\t\"yellow.png\"\n\t};\n\n\tMat sign = loadImage(testLocation, testFiles[6]);\n\tMat templateSign = loadImage(templateLocation, templateFiles[2]);\n\tMat yellow = loadImage(templateLocation, templateFiles[4]);\n\n\tshowImage(\"Bus Stop Sign\", sign);\n\tMat hsvSign = findSign(sign);\n\tMat binary = binaryImage(sign);\n\tMat backProjSign = backProjection(sign, yellow);\n\t\/\/Mat templateMatch = templateMatching(sign, templateSign);\n\tMat templateMatch = templateMatching(sign, yellow);\n\n\tshowImage(\"HSV\", hsvSign);\n\tshowImage(\"Binary\", binary);\n\tshowImage(\"Back Projection\", backProjSign);\n\tshowImage(\"Template Matching\", templateMatch);\n\twaitKey(0);\n\n\tint stopNumber = digitRecognition(backProjSign);\n\n\t\/*int numberOfTestImages = sizeof(testFiles) \/ sizeof(testFiles[0]);\n\tMat* busStops = loadImages(numberOfTestImages, testLocation, testFiles);\n\tint numberOfTemplateImages = sizeof(templateFiles) \/ sizeof(templateFiles[0]);\n\tMat* templates = loadImages(numberOfTemplateImages, templateLocation, templateFiles);\n\n\tfor (int i = 0; i < numberOfTestImages; i++) {\n\t\tcout << \"Processing image \" << (i + 1) << endl;\n\t\tshowImage(\"Sign\", busStops[i]);\n\t\tMat hsvSign = findSign(busStops[i]);\n\t\tMat binary = binaryImage(busStops[i]);\n\t\tMat backProjSign = backProjection(busStops[i], templates[4]);\n\t\tMat templateMatch;\n\t\tif (i == 0 || i == 1) {\n\t\t\t\/\/ templates[0] or templates[1]\n\t\t\ttemplateMatch = templateMatching(busStops[i], templates[0]);\n\n\t\t}\n\t\telse {\n\t\t\t\/\/ templates[2] or templates[3]\n\t\t\ttemplateMatch = templateMatching(busStops[i], templates[2]);\n\n\t\t}\n\n\t\tshowImage(\"HSV\", hsvSign);\n\t\tshowImage(\"Binary\", binary);\n\t\tshowImage(\"Back Projection\", backProjSign);\n\t\tshowImage(\"Template Matching\", templateMatch);\n\t\t\n\t\twaitKey(0);\n\t}*\/\n\n\treturn 0;\n}\n\nMat loadImage(char* location, char* file) {\n\tstring filename(location);\n\tfilename.append(file);\n\tMat image = imread(filename, 1);\n\n\treturn image;\n}\n\nMat* loadImages(int numberOfImages, char* location, char** files) {\n\tMat* images = new Mat[numberOfImages];\n\tfor (int i = 0; i < numberOfImages; i++) {\n\t\tstring filename(location);\n\t\tfilename.append(files[i]);\n\t\tcout << \"Loading image \" << (i + 1) << \": \" << filename << endl;\n\t\timages[i] = imread(filename, 1);\n\t}\n\treturn images;\n}\n\nvoid showImage(char* name, Mat image) {\n\tresize(image, image, Size(image.cols \/ 4, image.rows \/ 4));\n\timshow(name, image);\n\n\treturn;\n}\n\nMat findSign(Mat image) {\n\tMat hsv;\n\tcvtColor(image, hsv, CV_BGR2HSV);\n\tinRange(hsv, Scalar(15, 135, 140), Scalar(30, 255, 255), hsv);\n\n\treturn hsv;\n}\n\nMat binaryImage(Mat image) {\n\tMat greyImage, binaryResult;\n\tcvtColor(image, greyImage, CV_BGR2GRAY);\n\tthreshold(greyImage, binaryResult, 200, 255, THRESH_BINARY);\n\n\treturn binaryResult;\n}\n\nMat backProjection(Mat image, Mat yellow) {\n\tMat imageHue = getHue(image);\n\tMat yellowHue = getHue(yellow);\n\n\tMat hist;\n\tint histSize = 180;\n\tfloat hueRange[] = { 0, 180 };\n\tconst float* ranges = { hueRange };\n\n\tcalcHist(&yellowHue, 1, 0, Mat(), hist, 1, &histSize, &ranges, true, false);\n\tnormalize(hist, hist, 0, 255, NORM_MINMAX, -1, Mat());\n\n\tMat backProject;\n\tcalcBackProject(&imageHue, 1, 0, hist, backProject, &ranges, 1, true);\n\n\treturn backProject;\n}\n\nMat getHue(Mat image) {\n\tMat hsv, hue;\n\tcvtColor(image, hsv, CV_BGR2HSV);\n\n\thue.create(hsv.size(), hsv.depth());\n\tint ch[] = { 0, 0 };\n\tmixChannels(&hsv, 1, &hue, 1, ch, 1);\n\n\treturn hue;\n}\n\nMat templateMatching(Mat image, Mat templateImage) {\n\tMat result;\n\n\tMat imageDisplay;\n\timage.copyTo(imageDisplay);\n\n\tint rows = image.rows - templateImage.rows + 1;\n\tint cols = image.cols - templateImage.cols + 1;\n\n\tresult.create(rows, cols, CV_32FC1);\n\n\tmatchTemplate(image, templateImage, result, CV_TM_SQDIFF);\n\tnormalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());\n\n\tdouble minVal, maxVal;\n\tPoint minLoc, maxLoc, matchLoc;\n\n\tminMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());\n\n\tmatchLoc = minLoc;\n\n\trectangle(imageDisplay, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0);\n\trectangle(result, matchLoc, Point(matchLoc.x + templateImage.cols, matchLoc.y + templateImage.rows), Scalar::all(0), 2, 8, 0);\n\n\t\/*showImage(\"Image\", imageDisplay);\n\tshowImage(\"Result\", result);\n\twaitKey(0);*\/\n\n\t\/\/return result;\n\treturn imageDisplay;\n}\n\nint digitRecognition(Mat image) {\n\t\/\/ TODO: recognise numbers from sign\n\t\/\/ Statistical Pattern Recognition\n\t\/\/ Scene Text Recognition - OCRTesseract\n\t\/\/ Template Matching\n\t\/\/ Chamfer Matching\n\t\/\/ Haar Classifiers\n\n\treturn 0;\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \nusing namespace std;\n\n\/*\nStrongly Connected Components of a Undirected Graph.\n-v & w are SCC if there's a path from v to w and from w to v.\n\nKosaraju Algorithm (DOUBLE PASS DFS, linear time E+V):\ninverse graph G -> R\ndfs to obtain reversed post order of R\ndfs G in the order given by reverse post order of R and mark in an array (array[nodeid]=SCC_id) the SCC id as we visit each node\n\n\n*\/\n\n#define MAX 13\n\ntypedef vector vi;\ntypedef vector vvi;\n\nint visited[MAX]={0};\nint visited2[MAX]={0};\nint SCCids[MAX]={0};\nstack postOrder;\n\nvvi graphG,graphR; \/\/original and reversed graph\n\nvoid dfs(int node){\n\tvisited[node]=true;\n\tvi newVec = graphR[node];\t\n\tvi::iterator it;\n\tfor(it=newVec.begin();it!=newVec.end();it++){\n\t\tint son=*it;\n\t\tif(visited[son]==false){\n\t\t\tdfs(son);\n\t\t}\n\t}\n\tpostOrder.push(node);\n}\n\nvoid dfs_mark(int node, int SCCid){ \/\/mark with SCC id\n\tvisited2[node]=true;\n\tSCCids[node]=SCCid;\n\tvi newVec = graphG[node];\t\n\tvi::iterator it;\n\tfor(it=newVec.begin();it!=newVec.end();it++){\n\t\tint son=*it;\n\t\tif(visited2[son]==false){\n\t\t\tdfs_mark(son,SCCid);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tifstream fin (\"graph1.txt\");\n\t\n\tfor(int i=0;i>node1>>node2){\n\t\t\/\/cout<TARJAN for SCC#include \n#include \n#include \n#include \nusing namespace std;\n\n\/*\nStrongly Connected Components of a Undirected Graph.\n-v & w are SCC if there's a path from v to w and from w to v.\n\nKosaraju Algorithm (DOUBLE PASS DFS, linear time E+V):\ninverse graph G -> R\ndfs to obtain reversed post order of R\ndfs G in the order given by reverse post order of R and mark in an array (array[nodeid]=SCC_id) the SCC id as we visit each node\n\n\n*\/\n\n#define MAX 13\n\ntypedef vector vi;\ntypedef vector vvi;\n\nint visited[MAX]={0};\nint visited2[MAX]={0};\nint SCCids[MAX]={0};\nstack postOrder;\n\nvvi graphG,graphR; \/\/original and reversed graph\n\nvoid dfs(int node){\n\tvisited[node]=true;\n\tvi newVec = graphR[node];\t\n\tvi::iterator it;\n\tfor(it=newVec.begin();it!=newVec.end();it++){\n\t\tint son=*it;\n\t\tif(visited[son]==false){\n\t\t\tdfs(son);\n\t\t}\n\t}\n\tpostOrder.push(node);\n}\n\nvoid dfs_mark(int node, int SCCid){ \/\/mark with SCC id\n\tvisited2[node]=true;\n\tSCCids[node]=SCCid;\n\tvi newVec = graphG[node];\t\n\tvi::iterator it;\n\tfor(it=newVec.begin();it!=newVec.end();it++){\n\t\tint son=*it;\n\t\tif(visited2[son]==false){\n\t\t\tdfs_mark(son,SCCid);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tifstream fin (\"graph2.txt\"); \/\/graph1.txt\n\t\n\tfor(int i=0;i>node1>>node2){\n\t\t\/\/cout<"} {"text":"\/*=========================================================================\n\n Program: ParaView\n Module: testRegistry.cxx\n\n Copyright (c) Kitware, Inc.\n All rights reserved.\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n\n#include KWSYS_HEADER(Registry.hxx)\n#include KWSYS_HEADER(ios\/iostream)\n#include \n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"Registry.hxx.in\"\n# include \"kwsys_ios_iostream.h.in\"\n#endif\n\n#define IFT(x,res) if ( !x ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error in: \" << #x << kwsys_ios::endl; \\\n }\n#define IFNT(x,res) if ( x ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error in: \" << #x << kwsys_ios::endl; \\\n }\n\n#define CHE(x,y,res) if ( x && y && strcmp(x,y) ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error, \" << x << \" != \" << y << kwsys_ios::endl; \\\n }\n\nint testRegistry(int, char*[])\n{\n int res = 0;\n \n kwsys::Registry reg;\n reg.SetTopLevel(\"TestRegistry\");\n \n IFT(reg.SetValue(\"TestSubkey\", \"TestKey1\", \"Test Value 1\"), res);\n IFT(reg.SetValue(\"TestSubkey1\", \"TestKey2\", \"Test Value 2\"), res);\n IFT(reg.SetValue(\"TestSubkey\", \"TestKey3\", \"Test Value 3\"), res);\n IFT(reg.SetValue(\"TestSubkey2\", \"TestKey4\", \"Test Value 4\"), res);\n\n const char *buffer;\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey1\", &buffer), res);\n CHE(buffer, \"Test Value 1\", res);\n IFT(reg.ReadValue(\"TestSubkey1\", \"TestKey2\", &buffer), res);\n CHE(buffer, \"Test Value 2\", res);\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey3\", &buffer), res);\n CHE(buffer, \"Test Value 3\", res);\n IFT(reg.ReadValue(\"TestSubkey2\", \"TestKey4\", &buffer), res);\n CHE(buffer, \"Test Value 4\", res);\n \n IFT(reg.SetValue(\"TestSubkey\", \"TestKey1\", \"New Test Value 1\"), res);\n IFT(reg.SetValue(\"TestSubkey1\", \"TestKey2\", \"New Test Value 2\"), res);\n IFT(reg.SetValue(\"TestSubkey\", \"TestKey3\", \"New Test Value 3\"), res);\n IFT(reg.SetValue(\"TestSubkey2\", \"TestKey4\", \"New Test Value 4\"), res);\n\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey1\", &buffer), res);\n CHE(buffer, \"New Test Value 1\", res);\n IFT(reg.ReadValue(\"TestSubkey1\", \"TestKey2\", &buffer), res);\n CHE(buffer, \"New Test Value 2\", res);\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey3\", &buffer), res);\n CHE(buffer, \"New Test Value 3\", res);\n IFT(reg.ReadValue(\"TestSubkey2\", \"TestKey4\", &buffer), res);\n CHE(buffer, \"New Test Value 4\", res);\n\n IFT( reg.DeleteValue(\"TestSubkey\", \"TestKey1\"), res);\n IFNT(reg.ReadValue( \"TestSubkey\", \"TestKey1\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey1\", \"TestKey2\"), res);\n IFNT(reg.ReadValue( \"TestSubkey1\", \"TestKey2\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey\", \"TestKey3\"), res);\n IFNT(reg.ReadValue( \"TestSubkey\", \"TestKey3\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey2\", \"TestKey4\"), res);\n IFNT(reg.ReadValue( \"TestSubkey2\", \"TestKey5\", &buffer), res); \n\n const char* longStringWithNewLines = \"Value with embedded CR and LF characters CR='\\015' LF='\\012' CRLF='\\015\\012'\";\n IFT(reg.SetValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", longStringWithNewLines), res);\n IFT(reg.ReadValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", &buffer), res);\n CHE(buffer, longStringWithNewLines, res);\n IFT(reg.DeleteValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\"), res);\n IFNT(reg.ReadValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", &buffer), res);\n\n IFT(reg.SetValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", \"Some value\"), res);\n IFT(reg.ReadValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", &buffer), res);\n CHE(buffer, \"Some value\", res);\n IFT(reg.DeleteValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\"), res);\n IFNT(reg.ReadValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", &buffer), res);\n\n if ( res )\n {\n kwsys_ios::cout << \"Test failed\" << kwsys_ios::endl;\n }\n else\n {\n kwsys_ios::cout << \"Test passed\" << kwsys_ios::endl;\n }\n return res;\n}\nCOMP: remove warning on new HPUX compiler\/*=========================================================================\n\n Program: ParaView\n Module: testRegistry.cxx\n\n Copyright (c) Kitware, Inc.\n All rights reserved.\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n\n#include KWSYS_HEADER(Registry.hxx)\n#include KWSYS_HEADER(ios\/iostream)\n#include \n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"Registry.hxx.in\"\n# include \"kwsys_ios_iostream.h.in\"\n#endif\n\n#define IFT(x,res) if ( !x ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error in: \" << #x << kwsys_ios::endl; \\\n }\n#define IFNT(x,res) if ( x ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error in: \" << #x << kwsys_ios::endl; \\\n }\n\n#define CHE(x,y,res) if ( x && strcmp(x,y) ) \\\n { \\\n res = 1; \\\n kwsys_ios::cout << \"Error, \" << x << \" != \" << y << kwsys_ios::endl; \\\n }\n\nint testRegistry(int, char*[])\n{\n int res = 0;\n \n kwsys::Registry reg;\n reg.SetTopLevel(\"TestRegistry\");\n \n IFT(reg.SetValue(\"TestSubkey\", \"TestKey1\", \"Test Value 1\"), res);\n IFT(reg.SetValue(\"TestSubkey1\", \"TestKey2\", \"Test Value 2\"), res);\n IFT(reg.SetValue(\"TestSubkey\", \"TestKey3\", \"Test Value 3\"), res);\n IFT(reg.SetValue(\"TestSubkey2\", \"TestKey4\", \"Test Value 4\"), res);\n\n const char *buffer;\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey1\", &buffer), res);\n CHE(buffer, \"Test Value 1\", res);\n IFT(reg.ReadValue(\"TestSubkey1\", \"TestKey2\", &buffer), res);\n CHE(buffer, \"Test Value 2\", res);\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey3\", &buffer), res);\n CHE(buffer, \"Test Value 3\", res);\n IFT(reg.ReadValue(\"TestSubkey2\", \"TestKey4\", &buffer), res);\n CHE(buffer, \"Test Value 4\", res);\n \n IFT(reg.SetValue(\"TestSubkey\", \"TestKey1\", \"New Test Value 1\"), res);\n IFT(reg.SetValue(\"TestSubkey1\", \"TestKey2\", \"New Test Value 2\"), res);\n IFT(reg.SetValue(\"TestSubkey\", \"TestKey3\", \"New Test Value 3\"), res);\n IFT(reg.SetValue(\"TestSubkey2\", \"TestKey4\", \"New Test Value 4\"), res);\n\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey1\", &buffer), res);\n CHE(buffer, \"New Test Value 1\", res);\n IFT(reg.ReadValue(\"TestSubkey1\", \"TestKey2\", &buffer), res);\n CHE(buffer, \"New Test Value 2\", res);\n IFT(reg.ReadValue(\"TestSubkey\", \"TestKey3\", &buffer), res);\n CHE(buffer, \"New Test Value 3\", res);\n IFT(reg.ReadValue(\"TestSubkey2\", \"TestKey4\", &buffer), res);\n CHE(buffer, \"New Test Value 4\", res);\n\n IFT( reg.DeleteValue(\"TestSubkey\", \"TestKey1\"), res);\n IFNT(reg.ReadValue( \"TestSubkey\", \"TestKey1\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey1\", \"TestKey2\"), res);\n IFNT(reg.ReadValue( \"TestSubkey1\", \"TestKey2\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey\", \"TestKey3\"), res);\n IFNT(reg.ReadValue( \"TestSubkey\", \"TestKey3\", &buffer), res);\n IFT( reg.DeleteValue(\"TestSubkey2\", \"TestKey4\"), res);\n IFNT(reg.ReadValue( \"TestSubkey2\", \"TestKey5\", &buffer), res); \n\n const char* longStringWithNewLines = \"Value with embedded CR and LF characters CR='\\015' LF='\\012' CRLF='\\015\\012'\";\n IFT(reg.SetValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", longStringWithNewLines), res);\n IFT(reg.ReadValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", &buffer), res);\n CHE(buffer, longStringWithNewLines, res);\n IFT(reg.DeleteValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\"), res);\n IFNT(reg.ReadValue(\"TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName\", \"TestKey1\", &buffer), res);\n\n IFT(reg.SetValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", \"Some value\"), res);\n IFT(reg.ReadValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", &buffer), res);\n CHE(buffer, \"Some value\", res);\n IFT(reg.DeleteValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\"), res);\n IFNT(reg.ReadValue(\"TestSubkeyWith = EqualSignChar\", \"TestKey = 1\", &buffer), res);\n\n if ( res )\n {\n kwsys_ios::cout << \"Test failed\" << kwsys_ios::endl;\n }\n else\n {\n kwsys_ios::cout << \"Test passed\" << kwsys_ios::endl;\n }\n return res;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2010, The Cinder Project, All rights reserved.\n\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/Clipboard.h\"\n#include \"cinder\/Unicode.h\"\n#include \"cinder\/Log.h\"\n#if defined( CINDER_MAC )\n\t#include \"cinder\/cocoa\/CinderCocoa.h\"\n\t#import \n\t#import \n\t#import \n#elif defined( CINDER_COCOA_TOUCH )\t\n\t#include \"cinder\/cocoa\/CinderCocoa.h\"\n\t#include \"cinder\/cocoa\/CinderCocoaTouch.h\"\n\t#import \t\n#elif defined( CINDER_MSW )\n\t#include \n\t#define max(a, b) (((a) > (b)) ? (a) : (b))\n\t#define min(a, b) (((a) < (b)) ? (a) : (b))\n\t#include \n\t#undef min\n\t#undef max\n\t#include \"cinder\/msw\/CinderMsw.h\"\n\t#include \"cinder\/msw\/CinderMswGdiPlus.h\"\n\t#include \"cinder\/Utilities.h\"\n\t#include \"cinder\/ip\/Fill.h\"\n\t#include \"cinder\/ip\/Blend.h\"\n\t#include \n#endif\n\nnamespace cinder {\n\n#if defined( CINDER_MSW )\nbool clipboardContainsFormat( const std::set &formats )\n{\n\tbool result = false;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn false;\n\tint numFormats = ::CountClipboardFormats();\n\tfor( int f = 0; f < numFormats; ++f ) {\n\t\tif( formats.find( ::EnumClipboardFormats( f ) ) != formats.end() ) {\n\t\t\tresult = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t::CloseClipboard();\n\treturn result;\n}\n\n#endif\n\nbool Clipboard::hasString()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSString class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\treturn [pasteboard canReadObjectForClasses:classArray options:options];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\treturn [pasteboard containsPasteboardTypes:UIPasteboardTypeListString];\t\n#elif defined( CINDER_MSW )\n\tstd::set textFormats;\n\ttextFormats.insert( CF_TEXT ); textFormats.insert( CF_UNICODETEXT ); textFormats.insert( CF_OEMTEXT );\n\treturn clipboardContainsFormat( textFormats );\n#endif\n}\n\nbool Clipboard::hasImage()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSImage class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\treturn [pasteboard canReadObjectForClasses:classArray options:options];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\treturn [pasteboard containsPasteboardTypes:UIPasteboardTypeListImage];\t\t\n#elif defined( CINDER_MSW )\n\tstd::set imageFormats;\n\timageFormats.insert( CF_BITMAP ); imageFormats.insert( CF_DIB ); imageFormats.insert( CF_DIBV5 );\n\treturn clipboardContainsFormat( imageFormats);\n#endif\n}\n\t\nstd::string\tClipboard::getString()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSString class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\tif( [pasteboard canReadObjectForClasses:classArray options:options] ) {\n\t\tNSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];\n NSString *text = [objectsToPaste firstObject];\n\t\tif( ! text )\n\t\t\treturn std::string();\n\t\telse\n\t\t\treturn cocoa::convertNsString( text );\n\t}\n\telse {\n\t\treturn std::string();\n\t}\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\tNSString *str = pasteboard.string;\n\tif( str )\n\t\treturn cocoa::convertNsString( str );\n\telse\n\t\treturn std::string();\n#elif defined( CINDER_MSW )\n\tstd::string result;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn result;\n\tHANDLE dataH = ::GetClipboardData( CF_UNICODETEXT );\n\tif( dataH ) {\n\t\twchar_t *pstr = reinterpret_cast( ::GlobalLock( dataH ) );\n\t\tif( pstr ) {\n\t\t\tstd::wstring wstr( pstr );\n\t\t\tresult = toUtf8( (char16_t*)wstr.c_str() );\n\t\t\t::GlobalUnlock( dataH );\n\t\t}\n\t}\n\t::CloseClipboard();\n\treturn result;\n#endif\n}\n\nImageSourceRef Clipboard::getImage()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithPasteboard:pasteboard];\n\tif( rep )\n\t\treturn cocoa::ImageSourceCgImage::createRef( [rep CGImage] );\n\telse\n\t\treturn ImageSourceRef();\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\tUIImage *image = pasteboard.image;\n\tif( image )\n\t\treturn ImageSourceRef( *cocoa::convertUiImage( image ) );\n\telse\n\t\treturn ImageSourceRef();\n#elif defined( CINDER_MSW )\n\tImageSourceRef result;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn ImageSourceRef();\n\tHANDLE dataH = ::GetClipboardData( CF_DIBV5 );\n\tif( dataH ) {\n\t\tuint8_t *data = reinterpret_cast( ::GlobalLock( dataH ) );\n\t\t\/\/ CF_DIBV5 is composed of a BITMAPV5HEADER + bitmap data\n\t\tGdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromBITMAPINFO( reinterpret_cast( data ), data + sizeof(BITMAPV5HEADER) );\n\t\tif( bmp ) {\n\t\t\tresult = ImageSourceRef( msw::convertGdiplusBitmap( *bmp ) );\n\t\t\tdelete bmp;\n\t\t}\n\t\t::GlobalUnlock( dataH );\n\t}\n\t::CloseClipboard();\n\treturn result;\n#endif\n}\n\nvoid Clipboard::setString( const std::string &str )\n{\n#if defined( CINDER_MAC )\n\t[[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner:nil];\n\t[[NSPasteboard generalPasteboard] setString:[NSString stringWithUTF8String:str.c_str()] forType: NSStringPboardType];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard];\n\tpasteboard.string = [NSString stringWithUTF8String:str.c_str()];\n#elif defined( CINDER_MSW )\n\tif( ! ::OpenClipboard( NULL ) ) {\n\t\tCI_LOG_E( \"Failed to open clipboard\" );\n\t\treturn;\n\t}\n\t::EmptyClipboard();\n\tstd::u16string wstr = toUtf16( str );\n\tHANDLE hglbCopy = ::GlobalAlloc( GMEM_MOVEABLE, sizeof(uint16_t) * (wstr.length()+1) );\n\t\/\/ Lock the handle and copy the text to the buffer. \n\tvoid *lptstrCopy = ::GlobalLock( hglbCopy ); \n\tmemcpy( lptstrCopy, &wstr[0], sizeof(uint16_t) * (wstr.length()+1) ); \n\t::GlobalUnlock( hglbCopy );\n\t::SetClipboardData( CF_UNICODETEXT, hglbCopy ); \n\t::CloseClipboard();\n#endif\n}\n\nvoid Clipboard::setImage( ImageSourceRef imageSource, ImageTarget::Options options )\n{\n#if defined( CINDER_MAC )\n\tcocoa::ImageTargetCgImageRef target = cocoa::ImageTargetCgImage::createRef( imageSource, options );\n\timageSource->load( target );\n\ttarget->finalize();\n\t\n\tNSBitmapImageRep *imageRep = [[[NSBitmapImageRep alloc] initWithCGImage:target->getCgImage()] autorelease];\n\tNSImage *image = [[NSImage alloc] initWithSize:[imageRep size]];\n\t[image addRepresentation: imageRep];\n\t[[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSTIFFPboardType] owner:nil];\n\t[[NSPasteboard generalPasteboard] setData:[image TIFFRepresentation] forType:NSTIFFPboardType];\t\n\t[image release];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard];\n\tcocoa::SafeUiImage uiImage = cocoa::createUiImage( imageSource );\n\tpasteboard.image = (UIImage*)uiImage;\n#elif defined( CINDER_MSW )\n\tif( ! ::OpenClipboard( NULL ) ) {\n\t\tCI_LOG_E( \"Failed to open clipboard\" );\n\t\treturn;\n\t}\n\t::EmptyClipboard();\n\tint32_t rowBytes = (( imageSource->getWidth() * 32 + 31 ) \/ 32 ) * 4;\n\tsize_t dataSize = sizeof(BITMAPV5HEADER) + imageSource->getHeight() * rowBytes; \n\tHANDLE hglbCopy = ::GlobalAlloc( GMEM_MOVEABLE, dataSize );\n\tuint8_t *destData = reinterpret_cast( ::GlobalLock( hglbCopy ) ); \n\t\n\t\/\/ we create 'tempSurface' convert 'imageSource' into a Surface8u\n\t\/\/ then alpha blend 'tempSurface' into 'destSurface'.\n\t\/\/ Unfortunately alpha on Win32 Clipboard just seems to be a total mess, so we're punting and forcing it to be opaque on black.\n\tSurfaceChannelOrder sco = SurfaceChannelOrder::BGRA;\n\tconst Surface8u tempSurface( imageSource );\n\tSurface8u destSurface( destData + sizeof(BITMAPV5HEADER), imageSource->getWidth(), imageSource->getHeight(), rowBytes, sco );\n\tip::fill( &destSurface, ColorA8u( 0, 0, 0, 255 ) );\n\tip::blend( &destSurface, tempSurface );\n\n\t\/\/ set the BITMAPV5HEADER based on 'destSurface'\n\tBITMAPV5HEADER bi = {0};\n\tbi.bV5Size = sizeof(BITMAPV5HEADER);\n\tbi.bV5Width = destSurface.getWidth();\n\tbi.bV5Height = -destSurface.getHeight();\n\tbi.bV5Planes = 1;\n\tbi.bV5BitCount = 32;\n\tbi.bV5Compression = BI_RGB;\n\tbi.bV5SizeImage = destSurface.getHeight() * rowBytes;\n\tbi.bV5XPelsPerMeter = 0;\n\tbi.bV5YPelsPerMeter = 0;\n\tbi.bV5ClrUsed = 0;\n\tbi.bV5ClrImportant = 0;\n\tbi.bV5BlueMask = 0x000000ff;\n\tbi.bV5GreenMask = 0x0000ff00;\n\tbi.bV5RedMask = 0x00ff0000;\n\tbi.bV5AlphaMask = 0xff000000;\n\tbi.bV5CSType = LCS_sRGB;\n\tbi.bV5Intent = LCS_GM_IMAGES;\n\t*(reinterpret_cast(destData)) = bi;\n\n\t::GlobalUnlock( hglbCopy );\n\t::SetClipboardData( CF_DIBV5, hglbCopy ); \n\t::CloseClipboard();\t\n#endif\n}\n\n} \/\/ namespace cinderadd a cast to avoid a warning\/*\n Copyright (c) 2010, The Cinder Project, All rights reserved.\n\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/Clipboard.h\"\n#include \"cinder\/Unicode.h\"\n#include \"cinder\/Log.h\"\n#if defined( CINDER_MAC )\n\t#include \"cinder\/cocoa\/CinderCocoa.h\"\n\t#import \n\t#import \n\t#import \n#elif defined( CINDER_COCOA_TOUCH )\t\n\t#include \"cinder\/cocoa\/CinderCocoa.h\"\n\t#include \"cinder\/cocoa\/CinderCocoaTouch.h\"\n\t#import \t\n#elif defined( CINDER_MSW )\n\t#include \n\t#define max(a, b) (((a) > (b)) ? (a) : (b))\n\t#define min(a, b) (((a) < (b)) ? (a) : (b))\n\t#include \n\t#undef min\n\t#undef max\n\t#include \"cinder\/msw\/CinderMsw.h\"\n\t#include \"cinder\/msw\/CinderMswGdiPlus.h\"\n\t#include \"cinder\/Utilities.h\"\n\t#include \"cinder\/ip\/Fill.h\"\n\t#include \"cinder\/ip\/Blend.h\"\n\t#include \n#endif\n\nnamespace cinder {\n\n#if defined( CINDER_MSW )\nbool clipboardContainsFormat( const std::set &formats )\n{\n\tbool result = false;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn false;\n\tint numFormats = ::CountClipboardFormats();\n\tfor( int f = 0; f < numFormats; ++f ) {\n\t\tif( formats.find( ::EnumClipboardFormats( f ) ) != formats.end() ) {\n\t\t\tresult = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t::CloseClipboard();\n\treturn result;\n}\n\n#endif\n\nbool Clipboard::hasString()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSString class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\treturn [pasteboard canReadObjectForClasses:classArray options:options];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\treturn [pasteboard containsPasteboardTypes:UIPasteboardTypeListString];\t\n#elif defined( CINDER_MSW )\n\tstd::set textFormats;\n\ttextFormats.insert( CF_TEXT ); textFormats.insert( CF_UNICODETEXT ); textFormats.insert( CF_OEMTEXT );\n\treturn clipboardContainsFormat( textFormats );\n#endif\n}\n\nbool Clipboard::hasImage()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSImage class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\treturn [pasteboard canReadObjectForClasses:classArray options:options];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\treturn [pasteboard containsPasteboardTypes:UIPasteboardTypeListImage];\t\t\n#elif defined( CINDER_MSW )\n\tstd::set imageFormats;\n\timageFormats.insert( CF_BITMAP ); imageFormats.insert( CF_DIB ); imageFormats.insert( CF_DIBV5 );\n\treturn clipboardContainsFormat( imageFormats);\n#endif\n}\n\t\nstd::string\tClipboard::getString()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSArray *classArray = [NSArray arrayWithObject:[NSString class]];\n NSDictionary *options = [NSDictionary dictionary];\n \n\tif( [pasteboard canReadObjectForClasses:classArray options:options] ) {\n\t\tNSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];\n NSString *text = [objectsToPaste firstObject];\n\t\tif( ! text )\n\t\t\treturn std::string();\n\t\telse\n\t\t\treturn cocoa::convertNsString( text );\n\t}\n\telse {\n\t\treturn std::string();\n\t}\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\tNSString *str = pasteboard.string;\n\tif( str )\n\t\treturn cocoa::convertNsString( str );\n\telse\n\t\treturn std::string();\n#elif defined( CINDER_MSW )\n\tstd::string result;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn result;\n\tHANDLE dataH = ::GetClipboardData( CF_UNICODETEXT );\n\tif( dataH ) {\n\t\twchar_t *pstr = reinterpret_cast( ::GlobalLock( dataH ) );\n\t\tif( pstr ) {\n\t\t\tstd::wstring wstr( pstr );\n\t\t\tresult = toUtf8( (char16_t*)wstr.c_str() );\n\t\t\t::GlobalUnlock( dataH );\n\t\t}\n\t}\n\t::CloseClipboard();\n\treturn result;\n#endif\n}\n\nImageSourceRef Clipboard::getImage()\n{\n#if defined( CINDER_MAC )\n\tNSPasteboard *pasteboard = [NSPasteboard generalPasteboard];\n NSBitmapImageRep *rep = (NSBitmapImageRep*)[NSBitmapImageRep imageRepWithPasteboard:pasteboard];\n\tif( rep )\n\t\treturn cocoa::ImageSourceCgImage::createRef( [rep CGImage] );\n\telse\n\t\treturn ImageSourceRef();\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; \n\tUIImage *image = pasteboard.image;\n\tif( image )\n\t\treturn ImageSourceRef( *cocoa::convertUiImage( image ) );\n\telse\n\t\treturn ImageSourceRef();\n#elif defined( CINDER_MSW )\n\tImageSourceRef result;\n\tif( ! ::OpenClipboard( NULL ) )\n\t\treturn ImageSourceRef();\n\tHANDLE dataH = ::GetClipboardData( CF_DIBV5 );\n\tif( dataH ) {\n\t\tuint8_t *data = reinterpret_cast( ::GlobalLock( dataH ) );\n\t\t\/\/ CF_DIBV5 is composed of a BITMAPV5HEADER + bitmap data\n\t\tGdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromBITMAPINFO( reinterpret_cast( data ), data + sizeof(BITMAPV5HEADER) );\n\t\tif( bmp ) {\n\t\t\tresult = ImageSourceRef( msw::convertGdiplusBitmap( *bmp ) );\n\t\t\tdelete bmp;\n\t\t}\n\t\t::GlobalUnlock( dataH );\n\t}\n\t::CloseClipboard();\n\treturn result;\n#endif\n}\n\nvoid Clipboard::setString( const std::string &str )\n{\n#if defined( CINDER_MAC )\n\t[[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner:nil];\n\t[[NSPasteboard generalPasteboard] setString:[NSString stringWithUTF8String:str.c_str()] forType: NSStringPboardType];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard];\n\tpasteboard.string = [NSString stringWithUTF8String:str.c_str()];\n#elif defined( CINDER_MSW )\n\tif( ! ::OpenClipboard( NULL ) ) {\n\t\tCI_LOG_E( \"Failed to open clipboard\" );\n\t\treturn;\n\t}\n\t::EmptyClipboard();\n\tstd::u16string wstr = toUtf16( str );\n\tHANDLE hglbCopy = ::GlobalAlloc( GMEM_MOVEABLE, sizeof(uint16_t) * (wstr.length()+1) );\n\t\/\/ Lock the handle and copy the text to the buffer. \n\tvoid *lptstrCopy = ::GlobalLock( hglbCopy ); \n\tmemcpy( lptstrCopy, &wstr[0], sizeof(uint16_t) * (wstr.length()+1) ); \n\t::GlobalUnlock( hglbCopy );\n\t::SetClipboardData( CF_UNICODETEXT, hglbCopy ); \n\t::CloseClipboard();\n#endif\n}\n\nvoid Clipboard::setImage( ImageSourceRef imageSource, ImageTarget::Options options )\n{\n#if defined( CINDER_MAC )\n\tcocoa::ImageTargetCgImageRef target = cocoa::ImageTargetCgImage::createRef( imageSource, options );\n\timageSource->load( target );\n\ttarget->finalize();\n\t\n\tNSBitmapImageRep *imageRep = [[[NSBitmapImageRep alloc] initWithCGImage:target->getCgImage()] autorelease];\n\tNSImage *image = [[NSImage alloc] initWithSize:[imageRep size]];\n\t[image addRepresentation: imageRep];\n\t[[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSTIFFPboardType] owner:nil];\n\t[[NSPasteboard generalPasteboard] setData:[image TIFFRepresentation] forType:NSTIFFPboardType];\t\n\t[image release];\n#elif defined( CINDER_COCOA_TOUCH )\n\tUIPasteboard *pasteboard = [UIPasteboard generalPasteboard];\n\tcocoa::SafeUiImage uiImage = cocoa::createUiImage( imageSource );\n\tpasteboard.image = (UIImage*)uiImage;\n#elif defined( CINDER_MSW )\n\tif( ! ::OpenClipboard( NULL ) ) {\n\t\tCI_LOG_E( \"Failed to open clipboard\" );\n\t\treturn;\n\t}\n\t::EmptyClipboard();\n\tint32_t rowBytes = (( imageSource->getWidth() * 32 + 31 ) \/ 32 ) * 4;\n\tsize_t dataSize = sizeof(BITMAPV5HEADER) + imageSource->getHeight() * rowBytes; \n\tHANDLE hglbCopy = ::GlobalAlloc( GMEM_MOVEABLE, dataSize );\n\tuint8_t *destData = reinterpret_cast( ::GlobalLock( hglbCopy ) ); \n\t\n\t\/\/ we create 'tempSurface' convert 'imageSource' into a Surface8u\n\t\/\/ then alpha blend 'tempSurface' into 'destSurface'.\n\t\/\/ Unfortunately alpha on Win32 Clipboard just seems to be a total mess, so we're punting and forcing it to be opaque on black.\n\tSurfaceChannelOrder sco = SurfaceChannelOrder::BGRA;\n\tconst Surface8u tempSurface( imageSource );\n\tSurface8u destSurface( destData + sizeof(BITMAPV5HEADER), imageSource->getWidth(), imageSource->getHeight(), rowBytes, sco );\n\tip::fill( &destSurface, ColorA8u( 0, 0, 0, 255 ) );\n\tip::blend( &destSurface, tempSurface );\n\n\t\/\/ set the BITMAPV5HEADER based on 'destSurface'\n\tBITMAPV5HEADER bi = {0};\n\tbi.bV5Size = sizeof(BITMAPV5HEADER);\n\tbi.bV5Width = destSurface.getWidth();\n\tbi.bV5Height = -destSurface.getHeight();\n\tbi.bV5Planes = 1;\n\tbi.bV5BitCount = 32;\n\tbi.bV5Compression = BI_RGB;\n\tbi.bV5SizeImage = destSurface.getHeight() * rowBytes;\n\tbi.bV5XPelsPerMeter = 0;\n\tbi.bV5YPelsPerMeter = 0;\n\tbi.bV5ClrUsed = 0;\n\tbi.bV5ClrImportant = 0;\n\tbi.bV5BlueMask = 0x000000ff;\n\tbi.bV5GreenMask = 0x0000ff00;\n\tbi.bV5RedMask = 0x00ff0000;\n\tbi.bV5AlphaMask = 0xff000000;\n\tbi.bV5CSType = LCS_sRGB;\n\tbi.bV5Intent = LCS_GM_IMAGES;\n\t*(reinterpret_cast(destData)) = bi;\n\n\t::GlobalUnlock( hglbCopy );\n\t::SetClipboardData( CF_DIBV5, hglbCopy ); \n\t::CloseClipboard();\t\n#endif\n}\n\n} \/\/ namespace cinder<|endoftext|>"} {"text":"\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"elements\/logic\/pid.h\"\n\nnamespace spaghetti::elements::logic {\n\nPID::PID()\n : Element{}\n{\n setMinInputs(7);\n setMaxInputs(7);\n setMinOutputs(1);\n setMaxOutputs(1);\n\n addInput(ValueType::eFloat, \"PV\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"SP\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KP\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KI\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KD\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"CV High\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"CV Low\", IOSocket::eCanHoldFloat);\n\n addOutput(ValueType::eFloat, \"CV\", IOSocket::eCanHoldFloat);\n}\n\nvoid PID::update(duration_t const &a_delta)\n{\n m_delta = static_cast(a_delta.count()) \/ 1000.f;\n}\n\nvoid PID::calculate()\n{\n float const PV{ std::get(m_inputs[0].value) };\n float const SP{ std::get(m_inputs[1].value) };\n float const KP{ std::get(m_inputs[2].value) };\n float const KI{ std::get(m_inputs[3].value) };\n float const KD{ std::get(m_inputs[4].value) };\n float const CV_HIGH{ std::get(m_inputs[5].value) };\n float const CV_LOW{ std::get(m_inputs[6].value) };\n\n float const ERROR{ SP - PV };\n\n m_integral += ERROR * m_delta;\n\n float const P{ KP * ERROR };\n float const I{ KI * m_integral };\n float const D{ KD * ((ERROR - m_lastError) \/ m_delta) };\n\n float const CV{ std::clamp(P + I + D, CV_LOW, CV_HIGH) };\n\n m_lastError = ERROR;\n\n m_outputs[0].value = CV;\n}\n\n} \/\/ namespace spaghetti::elements::logic\nFix PID\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"elements\/logic\/pid.h\"\n\nnamespace spaghetti::elements::logic {\n\nPID::PID()\n : Element{}\n{\n setMinInputs(7);\n setMaxInputs(7);\n setMinOutputs(1);\n setMaxOutputs(1);\n\n addInput(ValueType::eFloat, \"PV\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"SP\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KP\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KI\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"KD\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"CV High\", IOSocket::eCanHoldFloat);\n addInput(ValueType::eFloat, \"CV Low\", IOSocket::eCanHoldFloat);\n\n addOutput(ValueType::eFloat, \"CV\", IOSocket::eCanHoldFloat);\n}\n\nvoid PID::update(duration_t const &a_delta)\n{\n m_delta = static_cast(a_delta.count()) \/ 1000.f;\n}\n\nvoid PID::calculate()\n{\n float const PV{ std::get(m_inputs[0].value) };\n float const SP{ std::get(m_inputs[1].value) };\n float const KP{ std::get(m_inputs[2].value) };\n float const KI{ std::get(m_inputs[3].value) };\n float const KD{ std::get(m_inputs[4].value) };\n float const CV_HIGH{ std::get(m_inputs[5].value) };\n float const CV_LOW{ std::get(m_inputs[6].value) };\n\n float const ERROR{ SP - PV };\n\n m_integral += (ERROR * m_delta) \/ KI;\n m_integral = std::clamp(m_integral, CV_LOW, CV_HIGH);\n\n float const P{ KP * ERROR };\n float const I{ m_integral };\n float const D{ KD * ((ERROR - m_lastError) \/ m_delta) };\n\n float const CV{ std::clamp(P + I + D, CV_LOW, CV_HIGH) };\n\n m_lastError = ERROR;\n\n m_outputs[0].value = CV;\n}\n\n} \/\/ namespace spaghetti::elements::logic\n<|endoftext|>"} {"text":"#include \n#include \"qwaylandintegration.h\"\n#include \"qwaylandwindowsurface.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nQWaylandInputDevice::QWaylandInputDevice(struct wl_display *display,\n\t\t\t\t\t uint32_t id)\n : mDisplay(display)\n , mInputDevice(wl_input_device_create(display, id))\n , mPointerFocus(NULL)\n , mKeyboardFocus(NULL)\n , mButtons(0)\n{\n struct xkb_rule_names names;\n\n wl_input_device_add_listener(mInputDevice,\n\t\t\t\t &inputDeviceListener,\n\t\t\t\t this);\n wl_input_device_set_user_data(mInputDevice, this);\n\n names.rules = \"evdev\";\n names.model = \"pc105\";\n names.layout = \"us\";\n names.variant = \"\";\n names.options = \"\";\n\n mXkb = xkb_compile_keymap_from_rules(&names);\n}\n\nvoid QWaylandInputDevice::inputHandleMotion(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time,\n\t\t\t\t\t int32_t x, int32_t y,\n\t\t\t\t\t int32_t surface_x, int32_t surface_y)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mPointerFocus;\n\n inputDevice->mSurfacePos = QPoint(surface_x, surface_y);\n inputDevice->mGlobalPos = QPoint(x, y);\n inputDevice->mTime = time;\n QWindowSystemInterface::handleMouseEvent(window->widget(),\n\t\t\t\t\t time,\n\t\t\t\t\t inputDevice->mSurfacePos,\n\t\t\t\t\t inputDevice->mGlobalPos,\n\t\t\t\t\t inputDevice->mButtons);\n}\n\nvoid QWaylandInputDevice::inputHandleButton(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time, uint32_t button, uint32_t state)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mPointerFocus;\n Qt::MouseButton qt_button;\n\n switch (button) {\n case 272:\n\tqt_button = Qt::LeftButton;\n\tbreak;\n case 273:\n\tqt_button = Qt::RightButton;\n\tbreak;\n case 274:\n\tqt_button = Qt::MiddleButton;\n\tbreak;\n default:\n\treturn;\n }\n\n if (state)\n\tinputDevice->mButtons |= qt_button;\n else\n\tinputDevice->mButtons &= ~qt_button;\n\n inputDevice->mTime = time;\n QWindowSystemInterface::handleMouseEvent(window->widget(),\n\t\t\t\t\t time,\n\t\t\t\t\t inputDevice->mSurfacePos,\n\t\t\t\t\t inputDevice->mGlobalPos,\n\t\t\t\t\t inputDevice->mButtons);\n}\n\nstatic Qt::KeyboardModifiers translateModifiers(int s)\n{\n const uchar qt_alt_mask = XKB_COMMON_MOD1_MASK;\n const uchar qt_meta_mask = XKB_COMMON_MOD4_MASK;\n\n Qt::KeyboardModifiers ret = 0;\n if (s & XKB_COMMON_SHIFT_MASK)\n\tret |= Qt::ShiftModifier;\n if (s & XKB_COMMON_CONTROL_MASK)\n\tret |= Qt::ControlModifier;\n if (s & qt_alt_mask)\n\tret |= Qt::AltModifier;\n if (s & qt_meta_mask)\n\tret |= Qt::MetaModifier;\n\n return ret;\n}\n\nstatic uint32_t translateKey(uint32_t sym, char *string, size_t size)\n{\n string[0] = '\\0';\n\n switch (sym) {\n case XK_Escape:\t\treturn Qt::Key_Escape;\n case XK_Tab:\t\treturn Qt::Key_Tab;\n case XK_ISO_Left_Tab:\treturn Qt::Key_Backtab;\n case XK_BackSpace:\t\treturn Qt::Key_Backspace;\n case XK_Return:\t\treturn Qt::Key_Return;\n case XK_Insert:\t\treturn Qt::Key_Insert;\n case XK_Delete:\t\treturn Qt::Key_Delete;\n case XK_Clear:\t\treturn Qt::Key_Delete;\n case XK_Pause:\t\treturn Qt::Key_Pause;\n case XK_Print:\t\treturn Qt::Key_Print;\n\n case XK_Home:\t\treturn Qt::Key_Home;\n case XK_End:\t\treturn Qt::Key_End;\n case XK_Left:\t\treturn Qt::Key_Left;\n case XK_Up:\t\t\treturn Qt::Key_Up;\n case XK_Right:\t\treturn Qt::Key_Right;\n case XK_Down:\t\treturn Qt::Key_Down;\n case XK_Prior:\t\treturn Qt::Key_PageUp;\n case XK_Next:\t\treturn Qt::Key_PageDown;\n\n case XK_Shift_L:\t\treturn Qt::Key_Shift;\n case XK_Shift_R:\t\treturn Qt::Key_Shift;\n case XK_Shift_Lock:\t\treturn Qt::Key_Shift;\n case XK_Control_L:\t\treturn Qt::Key_Control;\n case XK_Control_R:\t\treturn Qt::Key_Control;\n case XK_Meta_L:\t\treturn Qt::Key_Meta;\n case XK_Meta_R:\t\treturn Qt::Key_Meta;\n case XK_Alt_L:\t\treturn Qt::Key_Alt;\n case XK_Alt_R:\t\treturn Qt::Key_Alt;\n case XK_Caps_Lock:\t\treturn Qt::Key_CapsLock;\n case XK_Num_Lock:\t\treturn Qt::Key_NumLock;\n case XK_Scroll_Lock:\treturn Qt::Key_ScrollLock;\n case XK_Super_L:\t\treturn Qt::Key_Super_L;\n case XK_Super_R:\t\treturn Qt::Key_Super_R;\n case XK_Menu:\t\treturn Qt::Key_Menu;\n\n default:\n\tstring[0] = sym;\n\tstring[1] = '\\0';\n\treturn toupper(sym);\n }\n}\n\nvoid QWaylandInputDevice::inputHandleKey(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time, uint32_t key, uint32_t state)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mKeyboardFocus;\n uint32_t code, sym, level;\n Qt::KeyboardModifiers modifiers;\n QEvent::Type type;\n char s[2];\n\n code = key + inputDevice->mXkb->min_key_code;\n\n level = 0;\n if (inputDevice->mModifiers & Qt::ShiftModifier &&\n\tXkbKeyGroupWidth(inputDevice->mXkb, code, 0) > 1)\n\tlevel = 1;\n\n sym = XkbKeySymEntry(inputDevice->mXkb, code, level, 0);\n\n modifiers = translateModifiers(inputDevice->mXkb->map->modmap[code]);\n\n if (state) {\n\tinputDevice->mModifiers |= modifiers;\n\ttype = QEvent::KeyPress;\n } else {\n\tinputDevice->mModifiers &= ~modifiers;\n\ttype = QEvent::KeyRelease;\n }\n\n sym = translateKey(sym, s, sizeof s);\n\n qWarning(\"keycode %d, sym %d, string %d, modifiers 0x%x\",\n\t code, sym, s[0], (int) inputDevice->mModifiers);\n\n QWindowSystemInterface::handleKeyEvent(window->widget(),\n\t\t\t\t\t time, type, sym,\n\t\t\t\t\t inputDevice->mModifiers,\n\t\t\t\t\t QString::fromLatin1(s));\n}\n\nvoid QWaylandInputDevice::inputHandlePointerFocus(void *data,\n\t\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t\t uint32_t time, struct wl_surface *surface,\n\t\t\t\t\t\t int32_t x, int32_t y, int32_t sx, int32_t sy)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window;\n\n if (inputDevice->mPointerFocus) {\n\twindow = inputDevice->mPointerFocus;\n\tQWindowSystemInterface::handleLeaveEvent(window->widget());\n\tinputDevice->mPointerFocus = NULL;\n }\n\n if (surface) {\n\twindow = (QWaylandWindow *) wl_surface_get_user_data(surface);\n\tQWindowSystemInterface::handleEnterEvent(window->widget());\n\tinputDevice->mPointerFocus = window;\n }\n\n inputDevice->mTime = time;\n}\n\nvoid QWaylandInputDevice::inputHandleKeyboardFocus(void *data,\n\t\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t\t uint32_t time,\n\t\t\t\t\t\t struct wl_surface *surface,\n\t\t\t\t\t\t struct wl_array *keys)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window;\n\n if (inputDevice->mKeyboardFocus) {\n\twindow = inputDevice->mKeyboardFocus;\n\tinputDevice->mKeyboardFocus = NULL;\n }\n\n if (surface) {\n\twindow = (QWaylandWindow *) wl_surface_get_user_data(surface);\n\tinputDevice->mKeyboardFocus = window;\n }\n}\n\nconst struct wl_input_device_listener QWaylandInputDevice::inputDeviceListener = {\n QWaylandInputDevice::inputHandleMotion,\n QWaylandInputDevice::inputHandleButton,\n QWaylandInputDevice::inputHandleKey,\n QWaylandInputDevice::inputHandlePointerFocus,\n QWaylandInputDevice::inputHandleKeyboardFocus,\n};\n\nvoid QWaylandInputDevice::attach(QWaylandBuffer *buffer, int x, int y)\n{\n wl_input_device_attach(mInputDevice, mTime, buffer->mBuffer, x, y);\n}\nWayland: silence unused variable warnings in qwaylandinputdevice.cpp#include \n#include \"qwaylandintegration.h\"\n#include \"qwaylandwindowsurface.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nQWaylandInputDevice::QWaylandInputDevice(struct wl_display *display,\n\t\t\t\t\t uint32_t id)\n : mDisplay(display)\n , mInputDevice(wl_input_device_create(display, id))\n , mPointerFocus(NULL)\n , mKeyboardFocus(NULL)\n , mButtons(0)\n{\n struct xkb_rule_names names;\n\n wl_input_device_add_listener(mInputDevice,\n\t\t\t\t &inputDeviceListener,\n\t\t\t\t this);\n wl_input_device_set_user_data(mInputDevice, this);\n\n names.rules = \"evdev\";\n names.model = \"pc105\";\n names.layout = \"us\";\n names.variant = \"\";\n names.options = \"\";\n\n mXkb = xkb_compile_keymap_from_rules(&names);\n}\n\nvoid QWaylandInputDevice::inputHandleMotion(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time,\n\t\t\t\t\t int32_t x, int32_t y,\n\t\t\t\t\t int32_t surface_x, int32_t surface_y)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mPointerFocus;\n\n inputDevice->mSurfacePos = QPoint(surface_x, surface_y);\n inputDevice->mGlobalPos = QPoint(x, y);\n inputDevice->mTime = time;\n QWindowSystemInterface::handleMouseEvent(window->widget(),\n\t\t\t\t\t time,\n\t\t\t\t\t inputDevice->mSurfacePos,\n\t\t\t\t\t inputDevice->mGlobalPos,\n\t\t\t\t\t inputDevice->mButtons);\n}\n\nvoid QWaylandInputDevice::inputHandleButton(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time, uint32_t button, uint32_t state)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mPointerFocus;\n Qt::MouseButton qt_button;\n\n switch (button) {\n case 272:\n\tqt_button = Qt::LeftButton;\n\tbreak;\n case 273:\n\tqt_button = Qt::RightButton;\n\tbreak;\n case 274:\n\tqt_button = Qt::MiddleButton;\n\tbreak;\n default:\n\treturn;\n }\n\n if (state)\n\tinputDevice->mButtons |= qt_button;\n else\n\tinputDevice->mButtons &= ~qt_button;\n\n inputDevice->mTime = time;\n QWindowSystemInterface::handleMouseEvent(window->widget(),\n\t\t\t\t\t time,\n\t\t\t\t\t inputDevice->mSurfacePos,\n\t\t\t\t\t inputDevice->mGlobalPos,\n\t\t\t\t\t inputDevice->mButtons);\n}\n\nstatic Qt::KeyboardModifiers translateModifiers(int s)\n{\n const uchar qt_alt_mask = XKB_COMMON_MOD1_MASK;\n const uchar qt_meta_mask = XKB_COMMON_MOD4_MASK;\n\n Qt::KeyboardModifiers ret = 0;\n if (s & XKB_COMMON_SHIFT_MASK)\n\tret |= Qt::ShiftModifier;\n if (s & XKB_COMMON_CONTROL_MASK)\n\tret |= Qt::ControlModifier;\n if (s & qt_alt_mask)\n\tret |= Qt::AltModifier;\n if (s & qt_meta_mask)\n\tret |= Qt::MetaModifier;\n\n return ret;\n}\n\nstatic uint32_t translateKey(uint32_t sym, char *string, size_t size)\n{\n Q_UNUSED(size);\n string[0] = '\\0';\n\n switch (sym) {\n case XK_Escape:\t\treturn Qt::Key_Escape;\n case XK_Tab:\t\treturn Qt::Key_Tab;\n case XK_ISO_Left_Tab:\treturn Qt::Key_Backtab;\n case XK_BackSpace:\t\treturn Qt::Key_Backspace;\n case XK_Return:\t\treturn Qt::Key_Return;\n case XK_Insert:\t\treturn Qt::Key_Insert;\n case XK_Delete:\t\treturn Qt::Key_Delete;\n case XK_Clear:\t\treturn Qt::Key_Delete;\n case XK_Pause:\t\treturn Qt::Key_Pause;\n case XK_Print:\t\treturn Qt::Key_Print;\n\n case XK_Home:\t\treturn Qt::Key_Home;\n case XK_End:\t\treturn Qt::Key_End;\n case XK_Left:\t\treturn Qt::Key_Left;\n case XK_Up:\t\t\treturn Qt::Key_Up;\n case XK_Right:\t\treturn Qt::Key_Right;\n case XK_Down:\t\treturn Qt::Key_Down;\n case XK_Prior:\t\treturn Qt::Key_PageUp;\n case XK_Next:\t\treturn Qt::Key_PageDown;\n\n case XK_Shift_L:\t\treturn Qt::Key_Shift;\n case XK_Shift_R:\t\treturn Qt::Key_Shift;\n case XK_Shift_Lock:\t\treturn Qt::Key_Shift;\n case XK_Control_L:\t\treturn Qt::Key_Control;\n case XK_Control_R:\t\treturn Qt::Key_Control;\n case XK_Meta_L:\t\treturn Qt::Key_Meta;\n case XK_Meta_R:\t\treturn Qt::Key_Meta;\n case XK_Alt_L:\t\treturn Qt::Key_Alt;\n case XK_Alt_R:\t\treturn Qt::Key_Alt;\n case XK_Caps_Lock:\t\treturn Qt::Key_CapsLock;\n case XK_Num_Lock:\t\treturn Qt::Key_NumLock;\n case XK_Scroll_Lock:\treturn Qt::Key_ScrollLock;\n case XK_Super_L:\t\treturn Qt::Key_Super_L;\n case XK_Super_R:\t\treturn Qt::Key_Super_R;\n case XK_Menu:\t\treturn Qt::Key_Menu;\n\n default:\n\tstring[0] = sym;\n\tstring[1] = '\\0';\n\treturn toupper(sym);\n }\n}\n\nvoid QWaylandInputDevice::inputHandleKey(void *data,\n\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t uint32_t time, uint32_t key, uint32_t state)\n{\n Q_UNUSED(input_device);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window = inputDevice->mKeyboardFocus;\n uint32_t code, sym, level;\n Qt::KeyboardModifiers modifiers;\n QEvent::Type type;\n char s[2];\n\n code = key + inputDevice->mXkb->min_key_code;\n\n level = 0;\n if (inputDevice->mModifiers & Qt::ShiftModifier &&\n\tXkbKeyGroupWidth(inputDevice->mXkb, code, 0) > 1)\n\tlevel = 1;\n\n sym = XkbKeySymEntry(inputDevice->mXkb, code, level, 0);\n\n modifiers = translateModifiers(inputDevice->mXkb->map->modmap[code]);\n\n if (state) {\n\tinputDevice->mModifiers |= modifiers;\n\ttype = QEvent::KeyPress;\n } else {\n\tinputDevice->mModifiers &= ~modifiers;\n\ttype = QEvent::KeyRelease;\n }\n\n sym = translateKey(sym, s, sizeof s);\n\n qWarning(\"keycode %d, sym %d, string %d, modifiers 0x%x\",\n\t code, sym, s[0], (int) inputDevice->mModifiers);\n\n QWindowSystemInterface::handleKeyEvent(window->widget(),\n\t\t\t\t\t time, type, sym,\n\t\t\t\t\t inputDevice->mModifiers,\n\t\t\t\t\t QString::fromLatin1(s));\n}\n\nvoid QWaylandInputDevice::inputHandlePointerFocus(void *data,\n\t\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t\t uint32_t time, struct wl_surface *surface,\n\t\t\t\t\t\t int32_t x, int32_t y, int32_t sx, int32_t sy)\n{\n Q_UNUSED(input_device);\n Q_UNUSED(x);\n Q_UNUSED(y);\n Q_UNUSED(sx);\n Q_UNUSED(sy);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window;\n\n if (inputDevice->mPointerFocus) {\n\twindow = inputDevice->mPointerFocus;\n\tQWindowSystemInterface::handleLeaveEvent(window->widget());\n\tinputDevice->mPointerFocus = NULL;\n }\n\n if (surface) {\n\twindow = (QWaylandWindow *) wl_surface_get_user_data(surface);\n\tQWindowSystemInterface::handleEnterEvent(window->widget());\n\tinputDevice->mPointerFocus = window;\n }\n\n inputDevice->mTime = time;\n}\n\nvoid QWaylandInputDevice::inputHandleKeyboardFocus(void *data,\n\t\t\t\t\t\t struct wl_input_device *input_device,\n\t\t\t\t\t\t uint32_t time,\n\t\t\t\t\t\t struct wl_surface *surface,\n\t\t\t\t\t\t struct wl_array *keys)\n{\n Q_UNUSED(input_device);\n Q_UNUSED(time);\n Q_UNUSED(keys);\n QWaylandInputDevice *inputDevice = (QWaylandInputDevice *) data;\n QWaylandWindow *window;\n\n if (inputDevice->mKeyboardFocus) {\n\twindow = inputDevice->mKeyboardFocus;\n\tinputDevice->mKeyboardFocus = NULL;\n }\n\n if (surface) {\n\twindow = (QWaylandWindow *) wl_surface_get_user_data(surface);\n\tinputDevice->mKeyboardFocus = window;\n }\n}\n\nconst struct wl_input_device_listener QWaylandInputDevice::inputDeviceListener = {\n QWaylandInputDevice::inputHandleMotion,\n QWaylandInputDevice::inputHandleButton,\n QWaylandInputDevice::inputHandleKey,\n QWaylandInputDevice::inputHandlePointerFocus,\n QWaylandInputDevice::inputHandleKeyboardFocus,\n};\n\nvoid QWaylandInputDevice::attach(QWaylandBuffer *buffer, int x, int y)\n{\n wl_input_device_attach(mInputDevice, mTime, buffer->mBuffer, x, y);\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\nusing world = Hydra::World::World;\nnamespace Barcode {\n\tEditorState::EditorState() : _engine(Hydra::IEngine::getInstance()) {}\n\n\tvoid EditorState::load() {\n\t\t_textureLoader = Hydra::IO::GLTextureLoader::create();\n\t\t_meshLoader = Hydra::IO::GLMeshLoader::create(_engine->getRenderer());\n\n\t\tauto windowSize = _engine->getView()->getSize();\n\t\t_dgp = std::make_unique(_cameraSystem, windowSize);\n\n\t\t{\n\t\t\t_hitboxBatch = RenderBatch(\"assets\/shaders\/hitboxdebug.vert\", \"\", \"assets\/shaders\/hitboxdebug.frag\", _engine->getView());\n\t\t\t_hitboxBatch.batch.clearFlags = ClearFlags::none;\n\t\t}\n\n\t\t{\n\t\t\t_previewBatch = RenderBatch(\"assets\/shaders\/previewWindow.vert\", \"\", \"assets\/shaders\/previewWindow.frag\", glm::ivec2(720, 720));\n\t\t\t_previewBatch.output->addTexture(0, Hydra::Renderer::TextureType::u8RGB).finalize();\n\t\t}\n\t\t_initWorld();\n\n\t\t_importerMenu = new ImporterMenu();\n\t\t_exporterMenu = new ExporterMenu();\n\t\t_componentMenu = new ComponentMenu();\n\t}\n\n\tEditorState::~EditorState() { }\n\n\tvoid EditorState::onMainMenu() {\n\t\tif (ImGui::BeginMenu(\"Editor\")) {\n\t\t\tif (ImGui::MenuItem(\"Import...\")) {\n\t\t\t\t_showImporter = !_showImporter;\n\t\t\t\tif (_showImporter)\n\t\t\t\t\t_importerMenu->refresh(\"\/assets\");\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Export...\"))\t{\n\t\t\t\t_showExporter = !_showExporter;\n\t\t\t\tif (_showExporter)\n\t\t\t\t\t_exporterMenu->refresh(\"\/assets\");\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Pathfinding...\"))\n\t\t\t{\n\t\t\t\t_showPathMapCreator = !_showPathMapCreator;\n\t\t\t\tif (_showPathMapCreator)\n\t\t\t\t{\n\t\t\t\t\t_cc->useOrtho = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Add component...\")){\n\t\t\t\t_showComponentMenu = !_showComponentMenu;\n\t\t\t\tif (_showComponentMenu)\n\t\t\t\t\t_componentMenu->refresh();\n\t\t\t}\n\t\t\tImGui::Separator();\n\t\t\tif (ImGui::MenuItem(\"Clear room\")) {\n\t\t\t\tif (FileTree::getRoomEntity() != nullptr)\n\t\t\t\t\tFileTree::getRoomEntity()->dead = true;\n\n\t\t\t\tauto room = world::newEntity(\"Workspace\", world::root());\n\t\t\t\tauto t = room->addComponent();\n\t\t\t\tauto r = room->addComponent();\n\n\t\t\t}\t\t\n\n\t\t\tImGui::EndMenu();\n\t\t}\n\t}\n\n\tvoid EditorState::runFrame(float delta) {\n\t\tauto windowSize = _engine->getView()->getSize();\n\t\t_physicsSystem.tick(delta);\n\t\t_cameraSystem.tick(delta);\n\t\t_aiSystem.tick(delta);\n\t\t_bulletSystem.tick(delta);\n\t\t_playerSystem.tick(delta);\n\t\t_abilitySystem.tick(delta);\n\t\t_particleSystem.tick(delta);\n\t\t_rendererSystem.tick(delta);\n\t\t_animationSystem.tick(delta);\n\n\t\tconst glm::vec3 cameraPos = _playerTransform->position;\n\n\t\tif (_showPathMapCreator)\n\t\t{\n\t\t\t_cc->getTransformComponent()->position = glm::vec3(0, 40, 0);\n\t\t\t_cc->cameraPitch = 1.571;\n\t\t\t_cc->cameraYaw = 0;\n\t\t\t_cc->movementSpeed = 0;\n\t\t\t_cc->sensitivity = 0;\n\t\t}\n\n\t\tstatic bool enableHitboxDebug = true;\n\t\tImGui::Checkbox(\"Enable Hitbox Debug\", &enableHitboxDebug);\n\t\tImGui::Checkbox(\"Enable Glow\", &MenuState::glowEnabled);\n\t\tImGui::Checkbox(\"Enable SSAO\", &MenuState::ssaoEnabled);\n\t\tImGui::Checkbox(\"Enable Shadow\", &MenuState::shadowEnabled);\n\n\t\tauto viewMatrix = _cc->getViewMatrix();\n\t\tglm::vec3 rightVector = { viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0] };\n\t\tglm::vec3 upVector = { viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1] };\n\t\tglm::vec3 forwardVector = { viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2] };\n\t\t_cameraSystem.setCamInternals(*_cc);\n\t\t_cameraSystem.setCamDef(_playerTransform->position, forwardVector, upVector, rightVector, *_cc);\n\n\t\t_dgp->render(cameraPos, *_cc, *_playerTransform);\n\n\t\tif (enableHitboxDebug) {\n\t\t\tfor (auto& kv : _hitboxBatch.batch.objects)\n\t\t\t\tkv.second.clear();\n\n\t\t\tstd::vector> entities;\n\t\t\tworld::getEntitiesWithComponents(entities);\n\t\t\tfor (auto e : entities) {\n\t\t\t\t\/\/ GOTTA MAKE IT VERSATILE SO IT CAN TAKE CAPSULE AS WELL.\n\t\t\t\tauto drawObj = e->getComponent()->drawObject;\n\t\t\t\tauto rgbc = e->getComponent();\n\t\t\t\tglm::vec3 newScale;\n\t\t\t\tglm::quat rotation;\n\t\t\t\tglm::vec3 translation;\n\t\t\t\tglm::vec3 skew;\n\t\t\t\tglm::vec4 perspective;\n\t\t\t\tglm::decompose(drawObj->modelMatrix, newScale, rotation, translation, skew, perspective);\n\t\t\t\t_hitboxBatch.batch.objects[_hitboxCube.get()].push_back(glm::translate(translation) * glm::mat4_cast(rotation) * glm::scale(rgbc->getHalfExtentScale() * glm::vec3(2)));\n\t\t\t}\n\n\t\t\tworld::getEntitiesWithComponents(entities);\n\t\t\tfor (auto e : entities) {\n\t\t\t\tauto drawObj = e->getComponent()->drawObject;\n\t\t\t\tauto goc = e->getComponent();\n\t\t\t\tglm::vec3 newScale;\n\t\t\t\tglm::quat rotation;\n\t\t\t\tglm::vec3 translation;\n\t\t\t\tglm::vec3 skew;\n\t\t\t\tglm::vec4 perspective;\n\t\t\t\tglm::decompose(drawObj->modelMatrix, newScale, rotation, translation, skew, perspective);\n\t\t\t\t_hitboxBatch.batch.objects[_hitboxCube.get()].push_back(glm::translate(translation) * glm::mat4_cast(goc->quatRotation) * glm::scale(goc->halfExtents * glm::vec3(2)));\n\t\t\t}\n\n\t\t\t_hitboxBatch.pipeline->setValue(0, _cc->getViewMatrix());\n\t\t\t_hitboxBatch.pipeline->setValue(1, _cc->getProjectionMatrix());\n\t\t\t_engine->getRenderer()->renderHitboxes(_hitboxBatch.batch);\n\t\t}\n\n\t\tif (_showImporter)\n\t\t\t_importerMenu->render(_showImporter, &_previewBatch.batch, delta);\n\t\tif (_showExporter)\n\t\t\t_exporterMenu->render(_showExporter);\n\t\tif (_showPathMapCreator)\n\t\t\t_pathingMenu.render(_showPathMapCreator, delta, _engine->getView()->getSize().x, _engine->getView()->getSize().y);\n\t\tif (_showComponentMenu)\n\t\t\t_componentMenu->render(_showComponentMenu, _physicsSystem);\n\t}\n\tvoid EditorState::_initSystem() {\n\t\tconst std::vector systems = { _engine->getDeadSystem(), &_cameraSystem, &_particleSystem, &_abilitySystem, &_aiSystem, &_physicsSystem, &_bulletSystem, &_playerSystem, &_rendererSystem };\n\t\t_engine->getUIRenderer()->registerSystems(systems);\n\t}\n\tvoid EditorState::_initWorld() {\n\t\t_hitboxCube = Hydra::IEngine::getInstance()->getState()->getMeshLoader()->getMesh(\"assets\/objects\/HitBox.mATTIC\");\n\t\t{\n\t\t\tauto floor = world::newEntity(\"Floor\", world::root());\n\t\t\tauto t = floor->addComponent();\n\t\t\tt->position = glm::vec3(0, -7, 0);\n\t\t\tauto rgbc = floor->addComponent();\n\t\t\trgbc->createStaticPlane(glm::vec3(0, 1, 0), 1, Hydra::System::BulletPhysicsSystem::CollisionTypes::COLL_WALL\n\t\t\t\t, 0, 0, 0, 0.6f, 0);\n\t\t\tfloor->addComponent()->loadMesh(\"assets\/objects\/Floor_v2.mATTIC\");\n\t\t}\n\n\t\t{\n\t\t\tauto room = world::newEntity(\"Workspace\", world::root());\n\t\t\tauto t = room->addComponent();\n\t\t\tauto r = room->addComponent();\n\t\t}\n\n\t\t{\n\t\t\tauto compass = world::newEntity(\"Compass\", world::root());\n\t\t\tauto t = compass->addComponent();\n\n\t\t\tauto n = world::newEntity(\"North\", compass);\n\t\t\tauto tn = n->addComponent();\n\t\t\ttn->position = glm::vec3(0,0,17);\n\n\t\t\tauto e = world::newEntity(\"East\", compass);\n\t\t\tauto te = e->addComponent();\n\t\t\tte->position = glm::vec3(17, 0, 0);\n\n\t\t\tauto s = world::newEntity(\"South\", compass);\n\t\t\tauto ts = s->addComponent();\n\t\t\tts->position = glm::vec3(0, 0, -17);\n\n\t\t\tauto w = world::newEntity(\"West\", compass);\n\t\t\tauto tw = w->addComponent();\n\t\t\ttw->position = glm::vec3(-17, 0, 0);\n\t\t}\n\n\t\t{\n\t\t\tauto playerEntity = world::newEntity(\"Player\", world::root());\n\t\t\tauto c = playerEntity->addComponent();\n\t\t\tc->noClip = true;\n\t\t\tc->mouseControl = false;\n\t\t\tauto t = playerEntity->addComponent();\n\t\t\t_playerTransform = t.get();\n\t\t}\n\n\t\t{\n\t\t\tauto lightEntity = world::newEntity(\"Light\", world::root());\n\t\t\tauto l = lightEntity->addComponent();\n\t\t\tauto t = lightEntity->addComponent();\n\t\t\tt->position = glm::vec3(8.0, 0, 3.5);\n\t\t}\n\n\t\t{\n\t\t\tBlueprintLoader::save(\"world.blueprint\", \"World Blueprint\", world::root().get());\n\t\t\tHydra::World::World::reset();\n\t\t\tauto bp = BlueprintLoader::load(\"world.blueprint\");\n\t\t\tbp->spawn(world::root());\n\t\t}\n\n\t\t{\n\t\t\t_cc = static_cast(Hydra::Component::CameraComponent::componentHandler->getActiveComponents()[0].get());\n\t\t\tfor (auto& rb : Hydra::Component::RigidBodyComponent::componentHandler->getActiveComponents()) {\n\t\t\t\t_engine->log(Hydra::LogLevel::normal, \"Enabling bullet for %s\", world::getEntity(rb->entityID)->name.c_str());\n\t\t\t\t_physicsSystem.enable(static_cast(rb.get()));\n\t\t\t}\n\t\t}\n\t}\n}\neditorstate font fix#include \n\n#include \n#include \n#include \n\nusing world = Hydra::World::World;\nnamespace Barcode {\n\tEditorState::EditorState() : _engine(Hydra::IEngine::getInstance()) {}\n\n\tvoid EditorState::load() {\n\t\t_textureLoader = Hydra::IO::GLTextureLoader::create();\n\t\t_meshLoader = Hydra::IO::GLMeshLoader::create(_engine->getRenderer());\n\t\t_textFactory = Hydra::IO::GLTextFactory::create(\"assets\/fonts\/font.png\");\n\t\tauto windowSize = _engine->getView()->getSize();\n\t\t_dgp = std::make_unique(_cameraSystem, windowSize);\n\n\t\t{\n\t\t\t_hitboxBatch = RenderBatch(\"assets\/shaders\/hitboxdebug.vert\", \"\", \"assets\/shaders\/hitboxdebug.frag\", _engine->getView());\n\t\t\t_hitboxBatch.batch.clearFlags = ClearFlags::none;\n\t\t}\n\n\t\t{\n\t\t\t_previewBatch = RenderBatch(\"assets\/shaders\/previewWindow.vert\", \"\", \"assets\/shaders\/previewWindow.frag\", glm::ivec2(720, 720));\n\t\t\t_previewBatch.output->addTexture(0, Hydra::Renderer::TextureType::u8RGB).finalize();\n\t\t}\n\t\t_initWorld();\n\n\t\t_importerMenu = new ImporterMenu();\n\t\t_exporterMenu = new ExporterMenu();\n\t\t_componentMenu = new ComponentMenu();\n\t}\n\n\tEditorState::~EditorState() { }\n\n\tvoid EditorState::onMainMenu() {\n\t\tif (ImGui::BeginMenu(\"Editor\")) {\n\t\t\tif (ImGui::MenuItem(\"Import...\")) {\n\t\t\t\t_showImporter = !_showImporter;\n\t\t\t\tif (_showImporter)\n\t\t\t\t\t_importerMenu->refresh(\"\/assets\");\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Export...\"))\t{\n\t\t\t\t_showExporter = !_showExporter;\n\t\t\t\tif (_showExporter)\n\t\t\t\t\t_exporterMenu->refresh(\"\/assets\");\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Pathfinding...\"))\n\t\t\t{\n\t\t\t\t_showPathMapCreator = !_showPathMapCreator;\n\t\t\t\tif (_showPathMapCreator)\n\t\t\t\t{\n\t\t\t\t\t_cc->useOrtho = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ImGui::MenuItem(\"Add component...\")){\n\t\t\t\t_showComponentMenu = !_showComponentMenu;\n\t\t\t\tif (_showComponentMenu)\n\t\t\t\t\t_componentMenu->refresh();\n\t\t\t}\n\t\t\tImGui::Separator();\n\t\t\tif (ImGui::MenuItem(\"Clear room\")) {\n\t\t\t\tif (FileTree::getRoomEntity() != nullptr)\n\t\t\t\t\tFileTree::getRoomEntity()->dead = true;\n\n\t\t\t\tauto room = world::newEntity(\"Workspace\", world::root());\n\t\t\t\tauto t = room->addComponent();\n\t\t\t\tauto r = room->addComponent();\n\n\t\t\t}\t\t\n\n\t\t\tImGui::EndMenu();\n\t\t}\n\t}\n\n\tvoid EditorState::runFrame(float delta) {\n\t\tauto windowSize = _engine->getView()->getSize();\n\t\t_physicsSystem.tick(delta);\n\t\t_cameraSystem.tick(delta);\n\t\t_aiSystem.tick(delta);\n\t\t_bulletSystem.tick(delta);\n\t\t_playerSystem.tick(delta);\n\t\t_abilitySystem.tick(delta);\n\t\t_particleSystem.tick(delta);\n\t\t_rendererSystem.tick(delta);\n\t\t_animationSystem.tick(delta);\n\n\t\tconst glm::vec3 cameraPos = _playerTransform->position;\n\n\t\tif (_showPathMapCreator)\n\t\t{\n\t\t\t_cc->getTransformComponent()->position = glm::vec3(0, 40, 0);\n\t\t\t_cc->cameraPitch = 1.571;\n\t\t\t_cc->cameraYaw = 0;\n\t\t\t_cc->movementSpeed = 0;\n\t\t\t_cc->sensitivity = 0;\n\t\t}\n\n\t\tstatic bool enableHitboxDebug = true;\n\t\tImGui::Checkbox(\"Enable Hitbox Debug\", &enableHitboxDebug);\n\t\tImGui::Checkbox(\"Enable Glow\", &MenuState::glowEnabled);\n\t\tImGui::Checkbox(\"Enable SSAO\", &MenuState::ssaoEnabled);\n\t\tImGui::Checkbox(\"Enable Shadow\", &MenuState::shadowEnabled);\n\n\t\tauto viewMatrix = _cc->getViewMatrix();\n\t\tglm::vec3 rightVector = { viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0] };\n\t\tglm::vec3 upVector = { viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1] };\n\t\tglm::vec3 forwardVector = { viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2] };\n\t\t_cameraSystem.setCamInternals(*_cc);\n\t\t_cameraSystem.setCamDef(_playerTransform->position, forwardVector, upVector, rightVector, *_cc);\n\n\t\t_dgp->render(cameraPos, *_cc, *_playerTransform);\n\n\t\tif (enableHitboxDebug) {\n\t\t\tfor (auto& kv : _hitboxBatch.batch.objects)\n\t\t\t\tkv.second.clear();\n\n\t\t\tstd::vector> entities;\n\t\t\tworld::getEntitiesWithComponents(entities);\n\t\t\tfor (auto e : entities) {\n\t\t\t\t\/\/ GOTTA MAKE IT VERSATILE SO IT CAN TAKE CAPSULE AS WELL.\n\t\t\t\tauto drawObj = e->getComponent()->drawObject;\n\t\t\t\tauto rgbc = e->getComponent();\n\t\t\t\tglm::vec3 newScale;\n\t\t\t\tglm::quat rotation;\n\t\t\t\tglm::vec3 translation;\n\t\t\t\tglm::vec3 skew;\n\t\t\t\tglm::vec4 perspective;\n\t\t\t\tglm::decompose(drawObj->modelMatrix, newScale, rotation, translation, skew, perspective);\n\t\t\t\t_hitboxBatch.batch.objects[_hitboxCube.get()].push_back(glm::translate(translation) * glm::mat4_cast(rotation) * glm::scale(rgbc->getHalfExtentScale() * glm::vec3(2)));\n\t\t\t}\n\n\t\t\tworld::getEntitiesWithComponents(entities);\n\t\t\tfor (auto e : entities) {\n\t\t\t\tauto drawObj = e->getComponent()->drawObject;\n\t\t\t\tauto goc = e->getComponent();\n\t\t\t\tglm::vec3 newScale;\n\t\t\t\tglm::quat rotation;\n\t\t\t\tglm::vec3 translation;\n\t\t\t\tglm::vec3 skew;\n\t\t\t\tglm::vec4 perspective;\n\t\t\t\tglm::decompose(drawObj->modelMatrix, newScale, rotation, translation, skew, perspective);\n\t\t\t\t_hitboxBatch.batch.objects[_hitboxCube.get()].push_back(glm::translate(translation) * glm::mat4_cast(goc->quatRotation) * glm::scale(goc->halfExtents * glm::vec3(2)));\n\t\t\t}\n\n\t\t\t_hitboxBatch.pipeline->setValue(0, _cc->getViewMatrix());\n\t\t\t_hitboxBatch.pipeline->setValue(1, _cc->getProjectionMatrix());\n\t\t\t_engine->getRenderer()->renderHitboxes(_hitboxBatch.batch);\n\t\t}\n\n\t\tif (_showImporter)\n\t\t\t_importerMenu->render(_showImporter, &_previewBatch.batch, delta);\n\t\tif (_showExporter)\n\t\t\t_exporterMenu->render(_showExporter);\n\t\tif (_showPathMapCreator)\n\t\t\t_pathingMenu.render(_showPathMapCreator, delta, _engine->getView()->getSize().x, _engine->getView()->getSize().y);\n\t\tif (_showComponentMenu)\n\t\t\t_componentMenu->render(_showComponentMenu, _physicsSystem);\n\t}\n\tvoid EditorState::_initSystem() {\n\t\tconst std::vector systems = { _engine->getDeadSystem(), &_cameraSystem, &_particleSystem, &_abilitySystem, &_aiSystem, &_physicsSystem, &_bulletSystem, &_playerSystem, &_rendererSystem };\n\t\t_engine->getUIRenderer()->registerSystems(systems);\n\t}\n\tvoid EditorState::_initWorld() {\n\t\t_hitboxCube = Hydra::IEngine::getInstance()->getState()->getMeshLoader()->getMesh(\"assets\/objects\/HitBox.mATTIC\");\n\t\t{\n\t\t\tauto floor = world::newEntity(\"Floor\", world::root());\n\t\t\tauto t = floor->addComponent();\n\t\t\tt->position = glm::vec3(0, -7, 0);\n\t\t\tauto rgbc = floor->addComponent();\n\t\t\trgbc->createStaticPlane(glm::vec3(0, 1, 0), 1, Hydra::System::BulletPhysicsSystem::CollisionTypes::COLL_WALL\n\t\t\t\t, 0, 0, 0, 0.6f, 0);\n\t\t\tfloor->addComponent()->loadMesh(\"assets\/objects\/Floor_v2.mATTIC\");\n\t\t}\n\n\t\t{\n\t\t\tauto room = world::newEntity(\"Workspace\", world::root());\n\t\t\tauto t = room->addComponent();\n\t\t\tauto r = room->addComponent();\n\t\t}\n\n\t\t{\n\t\t\tauto compass = world::newEntity(\"Compass\", world::root());\n\t\t\tauto t = compass->addComponent();\n\n\t\t\tauto n = world::newEntity(\"North\", compass);\n\t\t\tauto tn = n->addComponent();\n\t\t\ttn->position = glm::vec3(0,0,17);\n\n\t\t\tauto e = world::newEntity(\"East\", compass);\n\t\t\tauto te = e->addComponent();\n\t\t\tte->position = glm::vec3(17, 0, 0);\n\n\t\t\tauto s = world::newEntity(\"South\", compass);\n\t\t\tauto ts = s->addComponent();\n\t\t\tts->position = glm::vec3(0, 0, -17);\n\n\t\t\tauto w = world::newEntity(\"West\", compass);\n\t\t\tauto tw = w->addComponent();\n\t\t\ttw->position = glm::vec3(-17, 0, 0);\n\t\t}\n\n\t\t{\n\t\t\tauto playerEntity = world::newEntity(\"Player\", world::root());\n\t\t\tauto c = playerEntity->addComponent();\n\t\t\tc->noClip = true;\n\t\t\tc->mouseControl = false;\n\t\t\tauto t = playerEntity->addComponent();\n\t\t\t_playerTransform = t.get();\n\t\t}\n\n\t\t{\n\t\t\tauto lightEntity = world::newEntity(\"Light\", world::root());\n\t\t\tauto l = lightEntity->addComponent();\n\t\t\tauto t = lightEntity->addComponent();\n\t\t\tt->position = glm::vec3(8.0, 0, 3.5);\n\t\t}\n\n\t\t{\n\t\t\tBlueprintLoader::save(\"world.blueprint\", \"World Blueprint\", world::root().get());\n\t\t\tHydra::World::World::reset();\n\t\t\tauto bp = BlueprintLoader::load(\"world.blueprint\");\n\t\t\tbp->spawn(world::root());\n\t\t}\n\n\t\t{\n\t\t\t_cc = static_cast(Hydra::Component::CameraComponent::componentHandler->getActiveComponents()[0].get());\n\t\t\tfor (auto& rb : Hydra::Component::RigidBodyComponent::componentHandler->getActiveComponents()) {\n\t\t\t\t_engine->log(Hydra::LogLevel::normal, \"Enabling bullet for %s\", world::getEntity(rb->entityID)->name.c_str());\n\t\t\t\t_physicsSystem.enable(static_cast(rb.get()));\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"base\/trace.hh\"\n#include \"dev\/io_device.hh\"\n#include \"sim\/builder.hh\"\n\n\nPioPort::PioPort(PioDevice *dev, Platform *p)\n : Port(dev->name() + \"-pioport\"), device(dev), platform(p)\n{ }\n\n\nTick\nPioPort::recvAtomic(Packet *pkt)\n{\n return device->recvAtomic(pkt);\n}\n\nvoid\nPioPort::recvFunctional(Packet *pkt)\n{\n device->recvAtomic(pkt);\n}\n\nvoid\nPioPort::getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)\n{\n snoop.clear();\n device->addressRanges(resp);\n}\n\n\nvoid\nPioPort::recvRetry()\n{\n Packet* pkt = transmitList.front();\n if (Port::sendTiming(pkt)) {\n transmitList.pop_front();\n }\n}\n\n\nvoid\nPioPort::SendEvent::process()\n{\n if (port->Port::sendTiming(packet))\n return;\n\n port->transmitList.push_back(packet);\n}\n\n\n\nbool\nPioPort::recvTiming(Packet *pkt)\n{\n device->recvAtomic(pkt);\n \/\/ turn packet around to go back to requester\n pkt->makeTimingResponse();\n sendTiming(pkt, pkt->time - pkt->req->getTime());\n return true;\n}\n\nPioDevice::~PioDevice()\n{\n if (pioPort)\n delete pioPort;\n}\n\nvoid\nPioDevice::init()\n{\n if (!pioPort)\n panic(\"Pio port not connected to anything!\");\n pioPort->sendStatusChange(Port::RangeChange);\n}\n\nvoid\nBasicPioDevice::addressRanges(AddrRangeList &range_list)\n{\n assert(pioSize != 0);\n range_list.clear();\n range_list.push_back(RangeSize(pioAddr, pioSize));\n}\n\n\nDmaPort::DmaPort(DmaDevice *dev, Platform *p)\n : Port(dev->name() + \"-dmaport\"), device(dev), platform(p), pendingCount(0)\n{ }\n\nbool\nDmaPort::recvTiming(Packet *pkt)\n{\n if (pkt->senderState) {\n DmaReqState *state;\n DPRINTF(DMA, \"Received response Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n state = dynamic_cast(pkt->senderState);\n assert(state);\n state->completionEvent->process();\n delete pkt->req;\n delete pkt;\n } else {\n DPRINTF(DMA, \"Received response Packet %#x with no senderState\\n\", pkt);\n delete pkt->req;\n delete pkt;\n }\n\n return true;\n}\n\nDmaDevice::DmaDevice(Params *p)\n : PioDevice(p), dmaPort(NULL)\n{ }\n\nvoid\nDmaPort::recvRetry()\n{\n Packet* pkt = transmitList.front();\n DPRINTF(DMA, \"Retry on Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n if (sendTiming(pkt)) {\n DPRINTF(DMA, \"-- Done\\n\");\n transmitList.pop_front();\n pendingCount--;\n assert(pendingCount >= 0);\n } else {\n DPRINTF(DMA, \"-- Failed, queued\\n\");\n }\n}\n\n\nvoid\nDmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,\n uint8_t *data)\n{\n assert(event);\n\n int prevSize = 0;\n\n for (ChunkGenerator gen(addr, size, peerBlockSize());\n !gen.done(); gen.next()) {\n Request *req = new Request(false);\n req->setPaddr(gen.addr());\n req->setSize(gen.size());\n req->setTime(curTick);\n Packet *pkt = new Packet(req, cmd, Packet::Broadcast);\n\n \/\/ Increment the data pointer on a write\n if (data)\n pkt->dataStatic(data + prevSize) ;\n\n prevSize += gen.size();\n\n \/\/ Set the last bit of the dma as the final packet for this dma\n \/\/ and set it's completion event.\n if (prevSize == size) {\n pkt->senderState = new DmaReqState(event, true);\n }\n assert(pendingCount >= 0);\n pendingCount++;\n sendDma(pkt);\n }\n}\n\n\nvoid\nDmaPort::sendDma(Packet *pkt)\n{\n \/\/ some kind of selction between access methods\n \/\/ more work is going to have to be done to make\n \/\/ switching actually work\n \/* MemState state = device->platform->system->memState;\n\n if (state == Timing) { *\/\n DPRINTF(DMA, \"Attempting to send Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n if (!sendTiming(pkt)) {\n transmitList.push_back(pkt);\n DPRINTF(DMA, \"-- Failed: queued\\n\");\n } else {\n DPRINTF(DMA, \"-- Done\\n\");\n pendingCount--;\n assert(pendingCount >= 0);\n }\n \/* } else if (state == Atomic) {\n sendAtomic(pkt);\n if (pkt->senderState) {\n DmaReqState *state = dynamic_cast(pkt->senderState);\n assert(state);\n state->completionEvent->schedule(curTick + (pkt->time - pkt->req->getTime()) +1);\n }\n pendingCount--;\n assert(pendingCount >= 0);\n delete pkt->req;\n delete pkt;\n\n } else if (state == Functional) {\n sendFunctional(pkt);\n \/\/ Is this correct???\n completionEvent->schedule(pkt->req->responseTime - pkt->req->requestTime);\n completionEvent == NULL;\n } else\n panic(\"Unknown memory command state.\");\n *\/\n}\n\nDmaDevice::~DmaDevice()\n{\n if (dmaPort)\n delete dmaPort;\n}\n\n\nmake io device be a little nicer about scheduling retries on the bus\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"base\/trace.hh\"\n#include \"dev\/io_device.hh\"\n#include \"sim\/builder.hh\"\n\n\nPioPort::PioPort(PioDevice *dev, Platform *p)\n : Port(dev->name() + \"-pioport\"), device(dev), platform(p)\n{ }\n\n\nTick\nPioPort::recvAtomic(Packet *pkt)\n{\n return device->recvAtomic(pkt);\n}\n\nvoid\nPioPort::recvFunctional(Packet *pkt)\n{\n device->recvAtomic(pkt);\n}\n\nvoid\nPioPort::getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)\n{\n snoop.clear();\n device->addressRanges(resp);\n}\n\n\nvoid\nPioPort::recvRetry()\n{\n Packet* pkt = transmitList.front();\n if (Port::sendTiming(pkt)) {\n transmitList.pop_front();\n }\n}\n\n\nvoid\nPioPort::SendEvent::process()\n{\n if (port->Port::sendTiming(packet))\n return;\n\n port->transmitList.push_back(packet);\n}\n\n\n\nbool\nPioPort::recvTiming(Packet *pkt)\n{\n device->recvAtomic(pkt);\n \/\/ turn packet around to go back to requester\n pkt->makeTimingResponse();\n sendTiming(pkt, pkt->time - pkt->req->getTime());\n return true;\n}\n\nPioDevice::~PioDevice()\n{\n if (pioPort)\n delete pioPort;\n}\n\nvoid\nPioDevice::init()\n{\n if (!pioPort)\n panic(\"Pio port not connected to anything!\");\n pioPort->sendStatusChange(Port::RangeChange);\n}\n\nvoid\nBasicPioDevice::addressRanges(AddrRangeList &range_list)\n{\n assert(pioSize != 0);\n range_list.clear();\n range_list.push_back(RangeSize(pioAddr, pioSize));\n}\n\n\nDmaPort::DmaPort(DmaDevice *dev, Platform *p)\n : Port(dev->name() + \"-dmaport\"), device(dev), platform(p), pendingCount(0)\n{ }\n\nbool\nDmaPort::recvTiming(Packet *pkt)\n{\n if (pkt->senderState) {\n DmaReqState *state;\n DPRINTF(DMA, \"Received response Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n state = dynamic_cast(pkt->senderState);\n assert(state);\n state->completionEvent->process();\n delete pkt->req;\n delete pkt;\n } else {\n DPRINTF(DMA, \"Received response Packet %#x with no senderState\\n\", pkt);\n delete pkt->req;\n delete pkt;\n }\n\n return true;\n}\n\nDmaDevice::DmaDevice(Params *p)\n : PioDevice(p), dmaPort(NULL)\n{ }\n\nvoid\nDmaPort::recvRetry()\n{\n Packet* pkt = transmitList.front();\n bool result = true;\n while (result && transmitList.size()) {\n DPRINTF(DMA, \"Retry on Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n result = sendTiming(pkt);\n if (result) {\n DPRINTF(DMA, \"-- Done\\n\");\n transmitList.pop_front();\n pendingCount--;\n assert(pendingCount >= 0);\n } else {\n DPRINTF(DMA, \"-- Failed, queued\\n\");\n }\n }\n}\n\n\nvoid\nDmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,\n uint8_t *data)\n{\n assert(event);\n\n int prevSize = 0;\n\n for (ChunkGenerator gen(addr, size, peerBlockSize());\n !gen.done(); gen.next()) {\n Request *req = new Request(false);\n req->setPaddr(gen.addr());\n req->setSize(gen.size());\n req->setTime(curTick);\n Packet *pkt = new Packet(req, cmd, Packet::Broadcast);\n\n \/\/ Increment the data pointer on a write\n if (data)\n pkt->dataStatic(data + prevSize) ;\n\n prevSize += gen.size();\n\n \/\/ Set the last bit of the dma as the final packet for this dma\n \/\/ and set it's completion event.\n if (prevSize == size) {\n pkt->senderState = new DmaReqState(event, true);\n }\n assert(pendingCount >= 0);\n pendingCount++;\n sendDma(pkt);\n }\n}\n\n\nvoid\nDmaPort::sendDma(Packet *pkt)\n{\n \/\/ some kind of selction between access methods\n \/\/ more work is going to have to be done to make\n \/\/ switching actually work\n \/* MemState state = device->platform->system->memState;\n\n if (state == Timing) { *\/\n DPRINTF(DMA, \"Attempting to send Packet %#x with senderState: %#x\\n\",\n pkt, pkt->senderState);\n if (transmitList.size() || !sendTiming(pkt)) {\n transmitList.push_back(pkt);\n DPRINTF(DMA, \"-- Failed: queued\\n\");\n } else {\n DPRINTF(DMA, \"-- Done\\n\");\n pendingCount--;\n assert(pendingCount >= 0);\n }\n \/* } else if (state == Atomic) {\n sendAtomic(pkt);\n if (pkt->senderState) {\n DmaReqState *state = dynamic_cast(pkt->senderState);\n assert(state);\n state->completionEvent->schedule(curTick + (pkt->time - pkt->req->getTime()) +1);\n }\n pendingCount--;\n assert(pendingCount >= 0);\n delete pkt->req;\n delete pkt;\n\n } else if (state == Functional) {\n sendFunctional(pkt);\n \/\/ Is this correct???\n completionEvent->schedule(pkt->req->responseTime - pkt->req->requestTime);\n completionEvent == NULL;\n } else\n panic(\"Unknown memory command state.\");\n *\/\n}\n\nDmaDevice::~DmaDevice()\n{\n if (dmaPort)\n delete dmaPort;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\/** @file\n * This device implemetns the niagara I\/O bridge chip. It manages incomming\n * interrupts and posts them to the CPU when needed. It holds mask registers and\n * various status registers for CPUs to check what interrupts are pending as\n * well as facilities to send IPIs to other cpus.\n *\/\n\n#include \n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/faults.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/intr_control.hh\"\n#include \"dev\/sparc\/iob.hh\"\n#include \"dev\/platform.hh\"\n#include \"mem\/port.hh\"\n#include \"mem\/packet_access.hh\"\n#include \"sim\/faults.hh\"\n#include \"sim\/system.hh\"\n\nIob::Iob(const Params *p)\n : PioDevice(p), ic(p->platform->intrctrl)\n{\n iobManAddr = ULL(0x9800000000);\n iobManSize = ULL(0x0100000000);\n iobJBusAddr = ULL(0x9F00000000);\n iobJBusSize = ULL(0x0100000000);\n assert (params()->system->threadContexts.size() <= MaxNiagaraProcs);\n\n pioDelay = p->pio_latency;\n\n \/\/ Get the interrupt controller from the platform\n ic = platform->intrctrl;\n\n for (int x = 0; x < NumDeviceIds; ++x) {\n intMan[x].cpu = 0;\n intMan[x].vector = 0;\n intCtl[x].mask = true;\n intCtl[x].pend = false;\n }\n\n}\n\nTick\nIob::read(PacketPtr pkt)\n{\n\n if (pkt->getAddr() >= iobManAddr && pkt->getAddr() < iobManAddr + iobManSize)\n readIob(pkt);\n else if (pkt->getAddr() >= iobJBusAddr && pkt->getAddr() < iobJBusAddr+iobJBusSize)\n readJBus(pkt);\n else\n panic(\"Invalid address reached Iob\\n\");\n\n pkt->makeAtomicResponse();\n return pioDelay;\n}\n\nvoid\nIob::readIob(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobManAddr;\n int index;\n uint64_t data;\n\n if (accessAddr >= IntManAddr && accessAddr < IntManAddr + IntManSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = intMan[index].cpu << 8 | intMan[index].vector << 0;\n pkt->set(data);\n return;\n }\n\n if (accessAddr >= IntCtlAddr && accessAddr < IntCtlAddr + IntCtlSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = intCtl[index].mask ? 1 << 2 : 0 |\n intCtl[index].pend ? 1 << 0 : 0;\n pkt->set(data);\n return;\n }\n\n if (accessAddr == JIntVecAddr) {\n pkt->set(jIntVec);\n return;\n }\n\n panic(\"Read to unknown IOB offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::readJBus(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobJBusAddr;\n int cpuid = pkt->req->contextId();\n int index;\n uint64_t data;\n\n\n\n\n if (accessAddr >= JIntData0Addr && accessAddr < JIntData1Addr) {\n index = (accessAddr - JIntData0Addr) >> 3;\n pkt->set(jBusData0[index]);\n return;\n }\n\n if (accessAddr >= JIntData1Addr && accessAddr < JIntDataA0Addr) {\n index = (accessAddr - JIntData1Addr) >> 3;\n pkt->set(jBusData1[index]);\n return;\n }\n\n if (accessAddr == JIntDataA0Addr) {\n pkt->set(jBusData0[cpuid]);\n return;\n }\n\n if (accessAddr == JIntDataA1Addr) {\n pkt->set(jBusData1[cpuid]);\n return;\n }\n\n if (accessAddr >= JIntBusyAddr && accessAddr < JIntBusyAddr + JIntBusySize) {\n index = (accessAddr - JIntBusyAddr) >> 3;\n data = jIntBusy[index].busy ? 1 << 5 : 0 |\n jIntBusy[index].source;\n pkt->set(data);\n return;\n }\n if (accessAddr == JIntABusyAddr) {\n data = jIntBusy[cpuid].busy ? 1 << 5 : 0 |\n jIntBusy[cpuid].source;\n pkt->set(data);\n return;\n };\n\n panic(\"Read to unknown JBus offset 0x%x\\n\", accessAddr);\n}\n\nTick\nIob::write(PacketPtr pkt)\n{\n if (pkt->getAddr() >= iobManAddr && pkt->getAddr() < iobManAddr + iobManSize)\n writeIob(pkt);\n else if (pkt->getAddr() >= iobJBusAddr && pkt->getAddr() < iobJBusAddr+iobJBusSize)\n writeJBus(pkt);\n else\n panic(\"Invalid address reached Iob\\n\");\n\n\n pkt->makeAtomicResponse();\n return pioDelay;\n}\n\nvoid\nIob::writeIob(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobManAddr;\n int index;\n uint64_t data;\n\n if (accessAddr >= IntManAddr && accessAddr < IntManAddr + IntManSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n intMan[index].cpu = bits(data,12,8);\n intMan[index].vector = bits(data,5,0);\n DPRINTF(Iob, \"Wrote IntMan %d cpu %d, vec %d\\n\", index,\n intMan[index].cpu, intMan[index].vector);\n return;\n }\n\n if (accessAddr >= IntCtlAddr && accessAddr < IntCtlAddr + IntCtlSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n intCtl[index].mask = bits(data,2,2);\n if (bits(data,1,1))\n intCtl[index].pend = false;\n DPRINTF(Iob, \"Wrote IntCtl %d pend %d cleared %d\\n\", index,\n intCtl[index].pend, bits(data,2,2));\n return;\n }\n\n if (accessAddr == JIntVecAddr) {\n jIntVec = bits(pkt->get(), 5,0);\n DPRINTF(Iob, \"Wrote jIntVec %d\\n\", jIntVec);\n return;\n }\n\n if (accessAddr >= IntVecDisAddr && accessAddr < IntVecDisAddr + IntVecDisSize) {\n Type type;\n int cpu_id;\n int vector;\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n type = (Type)bits(data,17,16);\n cpu_id = bits(data, 12,8);\n vector = bits(data,5,0);\n generateIpi(type,cpu_id, vector);\n return;\n }\n\n panic(\"Write to unknown IOB offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::writeJBus(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobJBusAddr;\n int cpuid = pkt->req->contextId();\n int index;\n uint64_t data;\n\n if (accessAddr >= JIntBusyAddr && accessAddr < JIntBusyAddr + JIntBusySize) {\n index = (accessAddr - JIntBusyAddr) >> 3;\n data = pkt->get();\n jIntBusy[index].busy = bits(data,5,5);\n DPRINTF(Iob, \"Wrote jIntBusy index %d busy: %d\\n\", index,\n jIntBusy[index].busy);\n return;\n }\n if (accessAddr == JIntABusyAddr) {\n data = pkt->get();\n jIntBusy[cpuid].busy = bits(data,5,5);\n DPRINTF(Iob, \"Wrote jIntBusy index %d busy: %d\\n\", cpuid,\n jIntBusy[cpuid].busy);\n return;\n };\n\n panic(\"Write to unknown JBus offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::receiveDeviceInterrupt(DeviceId devid)\n{\n assert(devid < NumDeviceIds);\n if (intCtl[devid].mask)\n return;\n intCtl[devid].mask = true;\n intCtl[devid].pend = true;\n DPRINTF(Iob, \"Receiving Device interrupt: %d for cpu %d vec %d\\n\",\n devid, intMan[devid].cpu, intMan[devid].vector);\n ic->post(intMan[devid].cpu, SparcISA::IT_INT_VEC, intMan[devid].vector);\n}\n\n\nvoid\nIob::generateIpi(Type type, int cpu_id, int vector)\n{\n SparcISA::SparcFault *por = new SparcISA::PowerOnReset();\n if (cpu_id >= sys->getNumCPUs())\n return;\n\n switch (type) {\n case 0: \/\/ interrupt\n DPRINTF(Iob, \"Generating interrupt because of I\/O write to cpu: %d vec %d\\n\",\n cpu_id, vector);\n ic->post(cpu_id, SparcISA::IT_INT_VEC, vector);\n break;\n case 1: \/\/ reset\n warn(\"Sending reset to CPU: %d\\n\", cpu_id);\n if (vector != por->trapType())\n panic(\"Don't know how to set non-POR reset to cpu\\n\");\n por->invoke(sys->threadContexts[cpu_id]);\n sys->threadContexts[cpu_id]->activate();\n break;\n case 2: \/\/ idle -- this means stop executing and don't wake on interrupts\n DPRINTF(Iob, \"Idling CPU because of I\/O write cpu: %d\\n\", cpu_id);\n sys->threadContexts[cpu_id]->halt();\n break;\n case 3: \/\/ resume\n DPRINTF(Iob, \"Resuming CPU because of I\/O write cpu: %d\\n\", cpu_id);\n sys->threadContexts[cpu_id]->activate();\n break;\n default:\n panic(\"Invalid type to generate ipi\\n\");\n }\n}\n\nbool\nIob::receiveJBusInterrupt(int cpu_id, int source, uint64_t d0, uint64_t d1)\n{\n \/\/ If we are already dealing with an interrupt for that cpu we can't deal\n \/\/ with another one right now... come back later\n if (jIntBusy[cpu_id].busy)\n return false;\n\n DPRINTF(Iob, \"Receiving jBus interrupt: %d for cpu %d vec %d\\n\",\n source, cpu_id, jIntVec);\n\n jIntBusy[cpu_id].busy = true;\n jIntBusy[cpu_id].source = source;\n jBusData0[cpu_id] = d0;\n jBusData1[cpu_id] = d1;\n\n ic->post(cpu_id, SparcISA::IT_INT_VEC, jIntVec);\n return true;\n}\n\nvoid\nIob::addressRanges(AddrRangeList &range_list)\n{\n range_list.clear();\n range_list.push_back(RangeSize(iobManAddr, iobManSize));\n range_list.push_back(RangeSize(iobJBusAddr, iobJBusSize));\n}\n\n\nvoid\nIob::serialize(std::ostream &os)\n{\n\n SERIALIZE_SCALAR(jIntVec);\n SERIALIZE_ARRAY(jBusData0, MaxNiagaraProcs);\n SERIALIZE_ARRAY(jBusData1, MaxNiagaraProcs);\n for (int x = 0; x < NumDeviceIds; x++) {\n nameOut(os, csprintf(\"%s.Int%d\", name(), x));\n paramOut(os, \"cpu\", intMan[x].cpu);\n paramOut(os, \"vector\", intMan[x].vector);\n paramOut(os, \"mask\", intCtl[x].mask);\n paramOut(os, \"pend\", intCtl[x].pend);\n };\n for (int x = 0; x < MaxNiagaraProcs; x++) {\n nameOut(os, csprintf(\"%s.jIntBusy%d\", name(), x));\n paramOut(os, \"busy\", jIntBusy[x].busy);\n paramOut(os, \"source\", jIntBusy[x].source);\n };\n}\n\nvoid\nIob::unserialize(Checkpoint *cp, const std::string §ion)\n{\n UNSERIALIZE_SCALAR(jIntVec);\n UNSERIALIZE_ARRAY(jBusData0, MaxNiagaraProcs);\n UNSERIALIZE_ARRAY(jBusData1, MaxNiagaraProcs);\n for (int x = 0; x < NumDeviceIds; x++) {\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"cpu\", intMan[x].cpu);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"vector\", intMan[x].vector);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"mask\", intCtl[x].mask);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"pend\", intCtl[x].pend);\n };\n for (int x = 0; x < MaxNiagaraProcs; x++) {\n paramIn(cp, csprintf(\"%s.jIntBusy%d\", name(), x), \"busy\", jIntBusy[x].busy);\n paramIn(cp, csprintf(\"%s.jIntBusy%d\", name(), x), \"source\", jIntBusy[x].source);\n };\n}\n\nIob *\nIobParams::create()\n{\n return new Iob(this);\n}\nFix SPARC_FS compile\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\/** @file\n * This device implemetns the niagara I\/O bridge chip. It manages incomming\n * interrupts and posts them to the CPU when needed. It holds mask registers and\n * various status registers for CPUs to check what interrupts are pending as\n * well as facilities to send IPIs to other cpus.\n *\/\n\n#include \n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/faults.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/intr_control.hh\"\n#include \"dev\/sparc\/iob.hh\"\n#include \"dev\/platform.hh\"\n#include \"mem\/port.hh\"\n#include \"mem\/packet_access.hh\"\n#include \"sim\/faults.hh\"\n#include \"sim\/system.hh\"\n\nIob::Iob(const Params *p)\n : PioDevice(p), ic(p->platform->intrctrl)\n{\n iobManAddr = ULL(0x9800000000);\n iobManSize = ULL(0x0100000000);\n iobJBusAddr = ULL(0x9F00000000);\n iobJBusSize = ULL(0x0100000000);\n assert (params()->system->threadContexts.size() <= MaxNiagaraProcs);\n\n pioDelay = p->pio_latency;\n\n \/\/ Get the interrupt controller from the platform\n ic = platform->intrctrl;\n\n for (int x = 0; x < NumDeviceIds; ++x) {\n intMan[x].cpu = 0;\n intMan[x].vector = 0;\n intCtl[x].mask = true;\n intCtl[x].pend = false;\n }\n\n}\n\nTick\nIob::read(PacketPtr pkt)\n{\n\n if (pkt->getAddr() >= iobManAddr && pkt->getAddr() < iobManAddr + iobManSize)\n readIob(pkt);\n else if (pkt->getAddr() >= iobJBusAddr && pkt->getAddr() < iobJBusAddr+iobJBusSize)\n readJBus(pkt);\n else\n panic(\"Invalid address reached Iob\\n\");\n\n pkt->makeAtomicResponse();\n return pioDelay;\n}\n\nvoid\nIob::readIob(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobManAddr;\n int index;\n uint64_t data;\n\n if (accessAddr >= IntManAddr && accessAddr < IntManAddr + IntManSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = intMan[index].cpu << 8 | intMan[index].vector << 0;\n pkt->set(data);\n return;\n }\n\n if (accessAddr >= IntCtlAddr && accessAddr < IntCtlAddr + IntCtlSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = intCtl[index].mask ? 1 << 2 : 0 |\n intCtl[index].pend ? 1 << 0 : 0;\n pkt->set(data);\n return;\n }\n\n if (accessAddr == JIntVecAddr) {\n pkt->set(jIntVec);\n return;\n }\n\n panic(\"Read to unknown IOB offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::readJBus(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobJBusAddr;\n int cpuid = pkt->req->contextId();\n int index;\n uint64_t data;\n\n\n\n\n if (accessAddr >= JIntData0Addr && accessAddr < JIntData1Addr) {\n index = (accessAddr - JIntData0Addr) >> 3;\n pkt->set(jBusData0[index]);\n return;\n }\n\n if (accessAddr >= JIntData1Addr && accessAddr < JIntDataA0Addr) {\n index = (accessAddr - JIntData1Addr) >> 3;\n pkt->set(jBusData1[index]);\n return;\n }\n\n if (accessAddr == JIntDataA0Addr) {\n pkt->set(jBusData0[cpuid]);\n return;\n }\n\n if (accessAddr == JIntDataA1Addr) {\n pkt->set(jBusData1[cpuid]);\n return;\n }\n\n if (accessAddr >= JIntBusyAddr && accessAddr < JIntBusyAddr + JIntBusySize) {\n index = (accessAddr - JIntBusyAddr) >> 3;\n data = jIntBusy[index].busy ? 1 << 5 : 0 |\n jIntBusy[index].source;\n pkt->set(data);\n return;\n }\n if (accessAddr == JIntABusyAddr) {\n data = jIntBusy[cpuid].busy ? 1 << 5 : 0 |\n jIntBusy[cpuid].source;\n pkt->set(data);\n return;\n };\n\n panic(\"Read to unknown JBus offset 0x%x\\n\", accessAddr);\n}\n\nTick\nIob::write(PacketPtr pkt)\n{\n if (pkt->getAddr() >= iobManAddr && pkt->getAddr() < iobManAddr + iobManSize)\n writeIob(pkt);\n else if (pkt->getAddr() >= iobJBusAddr && pkt->getAddr() < iobJBusAddr+iobJBusSize)\n writeJBus(pkt);\n else\n panic(\"Invalid address reached Iob\\n\");\n\n\n pkt->makeAtomicResponse();\n return pioDelay;\n}\n\nvoid\nIob::writeIob(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobManAddr;\n int index;\n uint64_t data;\n\n if (accessAddr >= IntManAddr && accessAddr < IntManAddr + IntManSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n intMan[index].cpu = bits(data,12,8);\n intMan[index].vector = bits(data,5,0);\n DPRINTF(Iob, \"Wrote IntMan %d cpu %d, vec %d\\n\", index,\n intMan[index].cpu, intMan[index].vector);\n return;\n }\n\n if (accessAddr >= IntCtlAddr && accessAddr < IntCtlAddr + IntCtlSize) {\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n intCtl[index].mask = bits(data,2,2);\n if (bits(data,1,1))\n intCtl[index].pend = false;\n DPRINTF(Iob, \"Wrote IntCtl %d pend %d cleared %d\\n\", index,\n intCtl[index].pend, bits(data,2,2));\n return;\n }\n\n if (accessAddr == JIntVecAddr) {\n jIntVec = bits(pkt->get(), 5,0);\n DPRINTF(Iob, \"Wrote jIntVec %d\\n\", jIntVec);\n return;\n }\n\n if (accessAddr >= IntVecDisAddr && accessAddr < IntVecDisAddr + IntVecDisSize) {\n Type type;\n int cpu_id;\n int vector;\n index = (accessAddr - IntManAddr) >> 3;\n data = pkt->get();\n type = (Type)bits(data,17,16);\n cpu_id = bits(data, 12,8);\n vector = bits(data,5,0);\n generateIpi(type,cpu_id, vector);\n return;\n }\n\n panic(\"Write to unknown IOB offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::writeJBus(PacketPtr pkt)\n{\n Addr accessAddr = pkt->getAddr() - iobJBusAddr;\n int cpuid = pkt->req->contextId();\n int index;\n uint64_t data;\n\n if (accessAddr >= JIntBusyAddr && accessAddr < JIntBusyAddr + JIntBusySize) {\n index = (accessAddr - JIntBusyAddr) >> 3;\n data = pkt->get();\n jIntBusy[index].busy = bits(data,5,5);\n DPRINTF(Iob, \"Wrote jIntBusy index %d busy: %d\\n\", index,\n jIntBusy[index].busy);\n return;\n }\n if (accessAddr == JIntABusyAddr) {\n data = pkt->get();\n jIntBusy[cpuid].busy = bits(data,5,5);\n DPRINTF(Iob, \"Wrote jIntBusy index %d busy: %d\\n\", cpuid,\n jIntBusy[cpuid].busy);\n return;\n };\n\n panic(\"Write to unknown JBus offset 0x%x\\n\", accessAddr);\n}\n\nvoid\nIob::receiveDeviceInterrupt(DeviceId devid)\n{\n assert(devid < NumDeviceIds);\n if (intCtl[devid].mask)\n return;\n intCtl[devid].mask = true;\n intCtl[devid].pend = true;\n DPRINTF(Iob, \"Receiving Device interrupt: %d for cpu %d vec %d\\n\",\n devid, intMan[devid].cpu, intMan[devid].vector);\n ic->post(intMan[devid].cpu, SparcISA::IT_INT_VEC, intMan[devid].vector);\n}\n\n\nvoid\nIob::generateIpi(Type type, int cpu_id, int vector)\n{\n SparcISA::SparcFault *por = new SparcISA::PowerOnReset();\n if (cpu_id >= sys->numContexts())\n return;\n\n switch (type) {\n case 0: \/\/ interrupt\n DPRINTF(Iob, \"Generating interrupt because of I\/O write to cpu: %d vec %d\\n\",\n cpu_id, vector);\n ic->post(cpu_id, SparcISA::IT_INT_VEC, vector);\n break;\n case 1: \/\/ reset\n warn(\"Sending reset to CPU: %d\\n\", cpu_id);\n if (vector != por->trapType())\n panic(\"Don't know how to set non-POR reset to cpu\\n\");\n por->invoke(sys->threadContexts[cpu_id]);\n sys->threadContexts[cpu_id]->activate();\n break;\n case 2: \/\/ idle -- this means stop executing and don't wake on interrupts\n DPRINTF(Iob, \"Idling CPU because of I\/O write cpu: %d\\n\", cpu_id);\n sys->threadContexts[cpu_id]->halt();\n break;\n case 3: \/\/ resume\n DPRINTF(Iob, \"Resuming CPU because of I\/O write cpu: %d\\n\", cpu_id);\n sys->threadContexts[cpu_id]->activate();\n break;\n default:\n panic(\"Invalid type to generate ipi\\n\");\n }\n}\n\nbool\nIob::receiveJBusInterrupt(int cpu_id, int source, uint64_t d0, uint64_t d1)\n{\n \/\/ If we are already dealing with an interrupt for that cpu we can't deal\n \/\/ with another one right now... come back later\n if (jIntBusy[cpu_id].busy)\n return false;\n\n DPRINTF(Iob, \"Receiving jBus interrupt: %d for cpu %d vec %d\\n\",\n source, cpu_id, jIntVec);\n\n jIntBusy[cpu_id].busy = true;\n jIntBusy[cpu_id].source = source;\n jBusData0[cpu_id] = d0;\n jBusData1[cpu_id] = d1;\n\n ic->post(cpu_id, SparcISA::IT_INT_VEC, jIntVec);\n return true;\n}\n\nvoid\nIob::addressRanges(AddrRangeList &range_list)\n{\n range_list.clear();\n range_list.push_back(RangeSize(iobManAddr, iobManSize));\n range_list.push_back(RangeSize(iobJBusAddr, iobJBusSize));\n}\n\n\nvoid\nIob::serialize(std::ostream &os)\n{\n\n SERIALIZE_SCALAR(jIntVec);\n SERIALIZE_ARRAY(jBusData0, MaxNiagaraProcs);\n SERIALIZE_ARRAY(jBusData1, MaxNiagaraProcs);\n for (int x = 0; x < NumDeviceIds; x++) {\n nameOut(os, csprintf(\"%s.Int%d\", name(), x));\n paramOut(os, \"cpu\", intMan[x].cpu);\n paramOut(os, \"vector\", intMan[x].vector);\n paramOut(os, \"mask\", intCtl[x].mask);\n paramOut(os, \"pend\", intCtl[x].pend);\n };\n for (int x = 0; x < MaxNiagaraProcs; x++) {\n nameOut(os, csprintf(\"%s.jIntBusy%d\", name(), x));\n paramOut(os, \"busy\", jIntBusy[x].busy);\n paramOut(os, \"source\", jIntBusy[x].source);\n };\n}\n\nvoid\nIob::unserialize(Checkpoint *cp, const std::string §ion)\n{\n UNSERIALIZE_SCALAR(jIntVec);\n UNSERIALIZE_ARRAY(jBusData0, MaxNiagaraProcs);\n UNSERIALIZE_ARRAY(jBusData1, MaxNiagaraProcs);\n for (int x = 0; x < NumDeviceIds; x++) {\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"cpu\", intMan[x].cpu);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"vector\", intMan[x].vector);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"mask\", intCtl[x].mask);\n paramIn(cp, csprintf(\"%s.Int%d\", name(), x), \"pend\", intCtl[x].pend);\n };\n for (int x = 0; x < MaxNiagaraProcs; x++) {\n paramIn(cp, csprintf(\"%s.jIntBusy%d\", name(), x), \"busy\", jIntBusy[x].busy);\n paramIn(cp, csprintf(\"%s.jIntBusy%d\", name(), x), \"source\", jIntBusy[x].source);\n };\n}\n\nIob *\nIobParams::create()\n{\n return new Iob(this);\n}\n<|endoftext|>"} {"text":"#include \"logging.h\"\r\n#include \"resources.h\"\r\n#include \"textureManager.h\"\r\n\r\nTextureManager textureManager;\r\n\r\nTextureManager::TextureManager()\r\n{\r\n defaultRepeated = false;\r\n defaultSmooth = false;\r\n autoSprite = true;\r\n disabled = false;\r\n}\r\n\r\nTextureManager::~TextureManager()\r\n{\r\n}\r\n\r\nvoid TextureManager::setTexture(sf::Sprite& sprite, const string& name, unsigned int spriteIndex)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n {\r\n sprite.setTexture(data.texture);\r\n sprite.setTextureRect(data.sprites[spriteIndex]);\r\n sprite.setOrigin(float(data.sprites[spriteIndex].width) \/ 2, float(data.sprites[spriteIndex].height) \/ 2);\r\n }else{\r\n sprite.setTexture(data.texture, true);\r\n sprite.setOrigin(data.texture.getSize().x \/ 2, data.texture.getSize().y \/ 2);\r\n }\r\n}\r\n\r\nsf::Texture* TextureManager::getTexture(const string& name, sf::Vector2i subDiv)\r\n{\r\n if (disabled)\r\n return nullptr;\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, subDiv);\r\n return &data.texture;\r\n}\r\n\r\nconst sf::IntRect TextureManager::getSpriteRect(const string& name, unsigned int spriteIndex)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n return data.sprites[spriteIndex];\r\n \r\n return sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(data.texture.getSize()));\r\n}\r\n\r\nvoid TextureManager::setSpriteRect(const string& name, unsigned int spriteIndex, const sf::IntRect rect)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n data.sprites[spriteIndex] = rect;\r\n else\r\n data.sprites.push_back(rect);\r\n}\r\n\r\nvoid TextureManager::loadTexture(const string& name, sf::Vector2i subDiv)\r\n{\r\n TextureData& data = textureMap[name];\r\n \r\n sf::Image tmpImage;\r\n P stream = getResourceStream(name);\r\n if (!stream) stream = getResourceStream(name + \".png\");\r\n if (!stream || !tmpImage.loadFromStream(**stream))\r\n {\r\n LOG(WARNING) << \"Failed to load texture: \" << name;\r\n sf::Image image;\r\n image.create(8, 8, sf::Color(255, 0, 255, 128));\r\n data.texture.loadFromImage(image);\r\n return;\r\n }\r\n \r\n if (subDiv.x > 0 || subDiv.y > 0)\r\n {\r\n subDiv.x = std::max(subDiv.x, 1);\r\n subDiv.y = std::max(subDiv.y, 1);\r\n int w = tmpImage.getSize().x \/ subDiv.x;\r\n int h = tmpImage.getSize().y \/ subDiv.y;\r\n for(int y=0; y 1 && y1-y > 1 && x1Update textureManager.cpp (#103)#include \"logging.h\"\r\n#include \"resources.h\"\r\n#include \"textureManager.h\"\r\n\r\nTextureManager textureManager;\r\n\r\nTextureManager::TextureManager()\r\n{\r\n defaultRepeated = false;\r\n defaultSmooth = false;\r\n autoSprite = true;\r\n disabled = false;\r\n}\r\n\r\nTextureManager::~TextureManager()\r\n{\r\n}\r\n\r\nvoid TextureManager::setTexture(sf::Sprite& sprite, const string& name, unsigned int spriteIndex)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n {\r\n sprite.setTexture(data.texture);\r\n sprite.setTextureRect(data.sprites[spriteIndex]);\r\n sprite.setOrigin(float(data.sprites[spriteIndex].width) \/ 2, float(data.sprites[spriteIndex].height) \/ 2);\r\n }else{\r\n sprite.setTexture(data.texture, true);\r\n sprite.setOrigin(data.texture.getSize().x \/ 2.f, data.texture.getSize().y \/ 2.f);\r\n }\r\n}\r\n\r\nsf::Texture* TextureManager::getTexture(const string& name, sf::Vector2i subDiv)\r\n{\r\n if (disabled)\r\n return nullptr;\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, subDiv);\r\n return &data.texture;\r\n}\r\n\r\nconst sf::IntRect TextureManager::getSpriteRect(const string& name, unsigned int spriteIndex)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n return data.sprites[spriteIndex];\r\n \r\n return sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(data.texture.getSize()));\r\n}\r\n\r\nvoid TextureManager::setSpriteRect(const string& name, unsigned int spriteIndex, const sf::IntRect rect)\r\n{\r\n TextureData& data = textureMap[name];\r\n if (data.texture.getSize().x < 1)\r\n loadTexture(name, sf::Vector2i(0, 0));\r\n \r\n if (spriteIndex < data.sprites.size())\r\n data.sprites[spriteIndex] = rect;\r\n else\r\n data.sprites.push_back(rect);\r\n}\r\n\r\nvoid TextureManager::loadTexture(const string& name, sf::Vector2i subDiv)\r\n{\r\n TextureData& data = textureMap[name];\r\n \r\n sf::Image tmpImage;\r\n P stream = getResourceStream(name);\r\n if (!stream) stream = getResourceStream(name + \".png\");\r\n if (!stream || !tmpImage.loadFromStream(**stream))\r\n {\r\n LOG(WARNING) << \"Failed to load texture: \" << name;\r\n sf::Image image;\r\n image.create(8, 8, sf::Color(255, 0, 255, 128));\r\n data.texture.loadFromImage(image);\r\n return;\r\n }\r\n \r\n if (subDiv.x > 0 || subDiv.y > 0)\r\n {\r\n subDiv.x = std::max(subDiv.x, 1);\r\n subDiv.y = std::max(subDiv.y, 1);\r\n int w = tmpImage.getSize().x \/ subDiv.x;\r\n int h = tmpImage.getSize().y \/ subDiv.y;\r\n for(int y=0; y 1 && y1-y > 1 && x1"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \"bastype2.hxx\"\n#include \"basdoc.hxx\"\n\n#include \"localizationmgr.hxx\"\n#include \"managelang.hxx\"\n#include \"dlgresid.hrc\"\n#include \n\n#include \n#include \n#include \n\nnamespace basctl\n{\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\n\nSFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );\n\nLibBoxControl::LibBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\n\n\nLibBoxControl::~LibBoxControl()\n{\n}\n\n\n\nvoid LibBoxControl::StateChanged( sal_uInt16, SfxItemState eState, const SfxPoolItem* pState )\n{\n LibBox* pBox = (LibBox*)GetToolBox().GetItemWindow(GetId());\n\n DBG_ASSERT( pBox, \"Box not found\" );\n if ( !pBox )\n return;\n\n if ( eState != SFX_ITEM_AVAILABLE )\n pBox->Disable();\n else\n {\n pBox->Enable();\n pBox->Update(dynamic_cast(pState));\n }\n}\n\n\n\nWindow* LibBoxControl::CreateItemWindow( Window *pParent )\n{\n return new LibBox( pParent, m_xFrame );\n}\n\n\n\/\/= DocListenerBox\n\n\nDocListenerBox::DocListenerBox( Window* pParent )\n :ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) )\n ,m_aNotifier( *this )\n{\n}\n\nDocListenerBox::~DocListenerBox()\n{\n m_aNotifier.dispose();\n}\n\nvoid DocListenerBox::onDocumentCreated( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentOpened( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentSave( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveDone( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveAs( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveAsDone( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentClosed( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentTitleChanged( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentModeChanged( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\n\n\/\/= basctl::LibBox\n\nLibBox::LibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :\n DocListenerBox( pParent ),\n m_xFrame( rFrame )\n{\n FillBox();\n bIgnoreSelect = true; \/\/ do not yet transfer select of 0\n bFillBox = true;\n SelectEntryPos( 0 );\n aCurText = GetEntry( 0 );\n SetSizePixel( Size( 250, 200 ) );\n bIgnoreSelect = false;\n}\n\n\n\nLibBox::~LibBox()\n{\n ClearBox();\n}\n\nvoid LibBox::Update( const SfxStringItem* pItem )\n{\n\n\/\/ if ( !pItem || !pItem->GetValue().Len() )\n FillBox();\n\n if ( pItem )\n {\n aCurText = pItem->GetValue();\n if ( aCurText.isEmpty() )\n aCurText = OUString( IDEResId( RID_STR_ALL ) );\n }\n\n if ( GetSelectEntry() != aCurText )\n SelectEntry( aCurText );\n}\n\nvoid LibBox::ReleaseFocus()\n{\n SfxViewShell* pCurSh = SfxViewShell::Current();\n DBG_ASSERT( pCurSh, \"Current ViewShell not found!\" );\n\n if ( pCurSh )\n {\n Window* pShellWin = pCurSh->GetWindow();\n if ( !pShellWin )\n pShellWin = Application::GetDefDialogParent();\n\n pShellWin->GrabFocus();\n }\n}\n\nvoid LibBox::FillBox()\n{\n SetUpdateMode(false);\n bIgnoreSelect = true;\n\n aCurText = GetSelectEntry();\n\n SelectEntryPos( 0 );\n ClearBox();\n\n \/\/ create list box entries\n sal_Int32 nPos = InsertEntry( OUString( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );\n SetEntryData( nPos, new LibEntry( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_UNKNOWN, OUString() ) );\n InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_USER );\n InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_SHARE );\n\n ScriptDocuments aDocuments( ScriptDocument::getAllScriptDocuments( ScriptDocument::DocumentsSorted ) );\n for ( ScriptDocuments::const_iterator doc = aDocuments.begin();\n doc != aDocuments.end();\n ++doc\n )\n {\n InsertEntries( *doc, LIBRARY_LOCATION_DOCUMENT );\n }\n\n SetUpdateMode(true);\n\n SelectEntry( aCurText );\n if ( !GetSelectEntryCount() )\n {\n SelectEntryPos( GetEntryCount() );\n aCurText = GetSelectEntry();\n }\n bIgnoreSelect = false;\n}\n\nvoid LibBox::InsertEntries( const ScriptDocument& rDocument, LibraryLocation eLocation )\n{\n \/\/ get a sorted list of library names\n Sequence< OUString > aLibNames = rDocument.getLibraryNames();\n sal_Int32 nLibCount = aLibNames.getLength();\n const OUString* pLibNames = aLibNames.getConstArray();\n\n for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )\n {\n OUString aLibName = pLibNames[ i ];\n if ( eLocation == rDocument.getLibraryLocation( aLibName ) )\n {\n OUString aName( rDocument.getTitle( eLocation ) );\n OUString aEntryText( CreateMgrAndLibStr( aName, aLibName ) );\n sal_Int32 nPos = InsertEntry( aEntryText, LISTBOX_APPEND );\n SetEntryData( nPos, new LibEntry( rDocument, eLocation, aLibName ) );\n }\n }\n}\n\nbool LibBox::PreNotify( NotifyEvent& rNEvt )\n{\n bool nDone = false;\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();\n sal_uInt16 nKeyCode = aKeyEvt.GetKeyCode().GetCode();\n switch( nKeyCode )\n {\n case KEY_RETURN:\n {\n NotifyIDE();\n nDone = true;\n }\n break;\n\n case KEY_ESCAPE:\n {\n SelectEntry( aCurText );\n ReleaseFocus();\n nDone = true;\n }\n break;\n }\n }\n else if( rNEvt.GetType() == EVENT_GETFOCUS )\n {\n if ( bFillBox )\n {\n FillBox();\n bFillBox = false;\n }\n }\n else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n {\n if ( !HasChildPathFocus(true) )\n {\n bIgnoreSelect = true;\n bFillBox = true;\n }\n }\n\n return nDone || ListBox::PreNotify( rNEvt );\n}\n\nvoid LibBox::Select()\n{\n if ( !IsTravelSelect() )\n {\n if ( !bIgnoreSelect )\n NotifyIDE();\n else\n SelectEntry( aCurText ); \/\/ since 306... (Select after Escape)\n }\n}\n\nvoid LibBox::NotifyIDE()\n{\n sal_Int32 nSelPos = GetSelectEntryPos();\n if (LibEntry* pEntry = static_cast(GetEntryData(nSelPos)))\n {\n ScriptDocument aDocument( pEntry->GetDocument() );\n SfxUsrAnyItem aDocumentItem( SID_BASICIDE_ARG_DOCUMENT_MODEL, uno::makeAny( aDocument.getDocumentOrNull() ) );\n OUString aLibName = pEntry->GetLibName();\n SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );\n if (SfxDispatcher* pDispatcher = GetDispatcher())\n pDispatcher->Execute(\n SID_BASICIDE_LIBSELECTED,\n SFX_CALLMODE_SYNCHRON, &aDocumentItem, &aLibNameItem, 0L\n );\n }\n ReleaseFocus();\n}\n\nvoid LibBox::ClearBox()\n{\n sal_Int32 nCount = GetEntryCount();\n for ( sal_Int32 i = 0; i < nCount; ++i )\n {\n LibEntry* pEntry = static_cast(GetEntryData( i ));\n delete pEntry;\n }\n ListBox::Clear();\n}\n\n\/\/ class LanguageBoxControl ----------------------------------------------\n\nSFX_IMPL_TOOLBOX_CONTROL( LanguageBoxControl, SfxStringItem );\n\nLanguageBoxControl::LanguageBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\nLanguageBoxControl::~LanguageBoxControl()\n{\n}\n\nvoid LanguageBoxControl::StateChanged( sal_uInt16 nID, SfxItemState eState, const SfxPoolItem* pItem )\n{\n (void)nID;\n if (LanguageBox* pBox = static_cast(GetToolBox().GetItemWindow(GetId())))\n {\n if (eState != SFX_ITEM_AVAILABLE)\n pBox->Disable();\n else\n {\n pBox->Enable();\n pBox->Update(dynamic_cast(pItem));\n }\n }\n}\n\nWindow* LanguageBoxControl::CreateItemWindow( Window *pParent )\n{\n return new LanguageBox( pParent );\n}\n\n\/\/ class basctl::LanguageBox -----------------------------------------------\n\nLanguageBox::LanguageBox( Window* pParent ) :\n\n DocListenerBox( pParent ),\n\n m_sNotLocalizedStr( IDEResId( RID_STR_TRANSLATION_NOTLOCALIZED ) ),\n m_sDefaultLanguageStr( IDEResId( RID_STR_TRANSLATION_DEFAULT ) ),\n\n m_bIgnoreSelect( false )\n\n{\n SetSizePixel( Size( 210, 200 ) );\n\n FillBox();\n}\n\nLanguageBox::~LanguageBox()\n{\n ClearBox();\n}\n\nvoid LanguageBox::FillBox()\n{\n SetUpdateMode(false);\n m_bIgnoreSelect = true;\n m_sCurrentText = GetSelectEntry();\n ClearBox();\n\n boost::shared_ptr pCurMgr(GetShell()->GetCurLocalizationMgr());\n if ( pCurMgr->isLibraryLocalized() )\n {\n Enable();\n SvtLanguageTable aLangTable;\n Locale aDefaultLocale = pCurMgr->getStringResourceManager()->getDefaultLocale();\n Locale aCurrentLocale = pCurMgr->getStringResourceManager()->getCurrentLocale();\n Sequence< Locale > aLocaleSeq = pCurMgr->getStringResourceManager()->getLocales();\n const Locale* pLocale = aLocaleSeq.getConstArray();\n sal_Int32 i, nCount = aLocaleSeq.getLength();\n sal_Int32 nSelPos = LISTBOX_ENTRY_NOTFOUND;\n for ( i = 0; i < nCount; ++i )\n {\n bool bIsDefault = localesAreEqual( aDefaultLocale, pLocale[i] );\n bool bIsCurrent = localesAreEqual( aCurrentLocale, pLocale[i] );\n LanguageType eLangType = LanguageTag::convertToLanguageType( pLocale[i] );\n OUString sLanguage = aLangTable.GetString( eLangType );\n if ( bIsDefault )\n {\n sLanguage += \" \";\n sLanguage += m_sDefaultLanguageStr;\n }\n sal_Int32 nPos = InsertEntry( sLanguage );\n SetEntryData( nPos, new LanguageEntry( sLanguage, pLocale[i], bIsDefault ) );\n\n if ( bIsCurrent )\n nSelPos = nPos;\n }\n\n if ( nSelPos != LISTBOX_ENTRY_NOTFOUND )\n {\n SelectEntryPos( nSelPos );\n m_sCurrentText = GetSelectEntry();\n }\n }\n else\n {\n InsertEntry( m_sNotLocalizedStr );\n SelectEntryPos(0);\n Disable();\n }\n\n SetUpdateMode(true);\n m_bIgnoreSelect = false;\n}\n\nvoid LanguageBox::ClearBox()\n{\n sal_Int32 nCount = GetEntryCount();\n for ( sal_Int32 i = 0; i < nCount; ++i )\n {\n LanguageEntry* pEntry = (LanguageEntry*)GetEntryData(i);\n delete pEntry;\n }\n ListBox::Clear();\n}\n\nvoid LanguageBox::SetLanguage()\n{\n LanguageEntry* pEntry = (LanguageEntry*)GetEntryData( GetSelectEntryPos() );\n if ( pEntry )\n GetShell()->GetCurLocalizationMgr()->handleSetCurrentLocale( pEntry->m_aLocale );\n}\n\nvoid LanguageBox::Select()\n{\n if ( !m_bIgnoreSelect )\n SetLanguage();\n else\n SelectEntry( m_sCurrentText ); \/\/ Select after Escape\n}\n\nbool LanguageBox::PreNotify( NotifyEvent& rNEvt )\n{\n bool nDone = false;\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n sal_uInt16 nKeyCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();\n switch( nKeyCode )\n {\n case KEY_RETURN:\n {\n SetLanguage();\n nDone = true;\n }\n break;\n\n case KEY_ESCAPE:\n {\n SelectEntry( m_sCurrentText );\n nDone = true;\n }\n break;\n }\n }\n else if( rNEvt.GetType() == EVENT_GETFOCUS )\n {\n }\n else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n {\n }\n\n return nDone || ListBox::PreNotify( rNEvt );\n}\n\nvoid LanguageBox::Update( const SfxStringItem* pItem )\n{\n FillBox();\n\n if ( pItem && !pItem->GetValue().isEmpty() )\n {\n m_sCurrentText = pItem->GetValue();\n if ( GetSelectEntry() != m_sCurrentText )\n SelectEntry( m_sCurrentText );\n }\n}\n\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nno temporary instance of SvtLanguageTable necessary here\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \"bastype2.hxx\"\n#include \"basdoc.hxx\"\n\n#include \"localizationmgr.hxx\"\n#include \"managelang.hxx\"\n#include \"dlgresid.hrc\"\n#include \n\n#include \n#include \n#include \n\nnamespace basctl\n{\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\n\nSFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );\n\nLibBoxControl::LibBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\n\n\nLibBoxControl::~LibBoxControl()\n{\n}\n\n\n\nvoid LibBoxControl::StateChanged( sal_uInt16, SfxItemState eState, const SfxPoolItem* pState )\n{\n LibBox* pBox = (LibBox*)GetToolBox().GetItemWindow(GetId());\n\n DBG_ASSERT( pBox, \"Box not found\" );\n if ( !pBox )\n return;\n\n if ( eState != SFX_ITEM_AVAILABLE )\n pBox->Disable();\n else\n {\n pBox->Enable();\n pBox->Update(dynamic_cast(pState));\n }\n}\n\n\n\nWindow* LibBoxControl::CreateItemWindow( Window *pParent )\n{\n return new LibBox( pParent, m_xFrame );\n}\n\n\n\/\/= DocListenerBox\n\n\nDocListenerBox::DocListenerBox( Window* pParent )\n :ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) )\n ,m_aNotifier( *this )\n{\n}\n\nDocListenerBox::~DocListenerBox()\n{\n m_aNotifier.dispose();\n}\n\nvoid DocListenerBox::onDocumentCreated( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentOpened( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentSave( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveDone( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveAs( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentSaveAsDone( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentClosed( const ScriptDocument& \/*_rDocument*\/ )\n{\n FillBox();\n}\n\nvoid DocListenerBox::onDocumentTitleChanged( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\nvoid DocListenerBox::onDocumentModeChanged( const ScriptDocument& \/*_rDocument*\/ )\n{\n \/\/ not interested in\n}\n\n\n\/\/= basctl::LibBox\n\nLibBox::LibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :\n DocListenerBox( pParent ),\n m_xFrame( rFrame )\n{\n FillBox();\n bIgnoreSelect = true; \/\/ do not yet transfer select of 0\n bFillBox = true;\n SelectEntryPos( 0 );\n aCurText = GetEntry( 0 );\n SetSizePixel( Size( 250, 200 ) );\n bIgnoreSelect = false;\n}\n\n\n\nLibBox::~LibBox()\n{\n ClearBox();\n}\n\nvoid LibBox::Update( const SfxStringItem* pItem )\n{\n\n\/\/ if ( !pItem || !pItem->GetValue().Len() )\n FillBox();\n\n if ( pItem )\n {\n aCurText = pItem->GetValue();\n if ( aCurText.isEmpty() )\n aCurText = OUString( IDEResId( RID_STR_ALL ) );\n }\n\n if ( GetSelectEntry() != aCurText )\n SelectEntry( aCurText );\n}\n\nvoid LibBox::ReleaseFocus()\n{\n SfxViewShell* pCurSh = SfxViewShell::Current();\n DBG_ASSERT( pCurSh, \"Current ViewShell not found!\" );\n\n if ( pCurSh )\n {\n Window* pShellWin = pCurSh->GetWindow();\n if ( !pShellWin )\n pShellWin = Application::GetDefDialogParent();\n\n pShellWin->GrabFocus();\n }\n}\n\nvoid LibBox::FillBox()\n{\n SetUpdateMode(false);\n bIgnoreSelect = true;\n\n aCurText = GetSelectEntry();\n\n SelectEntryPos( 0 );\n ClearBox();\n\n \/\/ create list box entries\n sal_Int32 nPos = InsertEntry( OUString( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );\n SetEntryData( nPos, new LibEntry( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_UNKNOWN, OUString() ) );\n InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_USER );\n InsertEntries( ScriptDocument::getApplicationScriptDocument(), LIBRARY_LOCATION_SHARE );\n\n ScriptDocuments aDocuments( ScriptDocument::getAllScriptDocuments( ScriptDocument::DocumentsSorted ) );\n for ( ScriptDocuments::const_iterator doc = aDocuments.begin();\n doc != aDocuments.end();\n ++doc\n )\n {\n InsertEntries( *doc, LIBRARY_LOCATION_DOCUMENT );\n }\n\n SetUpdateMode(true);\n\n SelectEntry( aCurText );\n if ( !GetSelectEntryCount() )\n {\n SelectEntryPos( GetEntryCount() );\n aCurText = GetSelectEntry();\n }\n bIgnoreSelect = false;\n}\n\nvoid LibBox::InsertEntries( const ScriptDocument& rDocument, LibraryLocation eLocation )\n{\n \/\/ get a sorted list of library names\n Sequence< OUString > aLibNames = rDocument.getLibraryNames();\n sal_Int32 nLibCount = aLibNames.getLength();\n const OUString* pLibNames = aLibNames.getConstArray();\n\n for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )\n {\n OUString aLibName = pLibNames[ i ];\n if ( eLocation == rDocument.getLibraryLocation( aLibName ) )\n {\n OUString aName( rDocument.getTitle( eLocation ) );\n OUString aEntryText( CreateMgrAndLibStr( aName, aLibName ) );\n sal_Int32 nPos = InsertEntry( aEntryText, LISTBOX_APPEND );\n SetEntryData( nPos, new LibEntry( rDocument, eLocation, aLibName ) );\n }\n }\n}\n\nbool LibBox::PreNotify( NotifyEvent& rNEvt )\n{\n bool nDone = false;\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();\n sal_uInt16 nKeyCode = aKeyEvt.GetKeyCode().GetCode();\n switch( nKeyCode )\n {\n case KEY_RETURN:\n {\n NotifyIDE();\n nDone = true;\n }\n break;\n\n case KEY_ESCAPE:\n {\n SelectEntry( aCurText );\n ReleaseFocus();\n nDone = true;\n }\n break;\n }\n }\n else if( rNEvt.GetType() == EVENT_GETFOCUS )\n {\n if ( bFillBox )\n {\n FillBox();\n bFillBox = false;\n }\n }\n else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n {\n if ( !HasChildPathFocus(true) )\n {\n bIgnoreSelect = true;\n bFillBox = true;\n }\n }\n\n return nDone || ListBox::PreNotify( rNEvt );\n}\n\nvoid LibBox::Select()\n{\n if ( !IsTravelSelect() )\n {\n if ( !bIgnoreSelect )\n NotifyIDE();\n else\n SelectEntry( aCurText ); \/\/ since 306... (Select after Escape)\n }\n}\n\nvoid LibBox::NotifyIDE()\n{\n sal_Int32 nSelPos = GetSelectEntryPos();\n if (LibEntry* pEntry = static_cast(GetEntryData(nSelPos)))\n {\n ScriptDocument aDocument( pEntry->GetDocument() );\n SfxUsrAnyItem aDocumentItem( SID_BASICIDE_ARG_DOCUMENT_MODEL, uno::makeAny( aDocument.getDocumentOrNull() ) );\n OUString aLibName = pEntry->GetLibName();\n SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );\n if (SfxDispatcher* pDispatcher = GetDispatcher())\n pDispatcher->Execute(\n SID_BASICIDE_LIBSELECTED,\n SFX_CALLMODE_SYNCHRON, &aDocumentItem, &aLibNameItem, 0L\n );\n }\n ReleaseFocus();\n}\n\nvoid LibBox::ClearBox()\n{\n sal_Int32 nCount = GetEntryCount();\n for ( sal_Int32 i = 0; i < nCount; ++i )\n {\n LibEntry* pEntry = static_cast(GetEntryData( i ));\n delete pEntry;\n }\n ListBox::Clear();\n}\n\n\/\/ class LanguageBoxControl ----------------------------------------------\n\nSFX_IMPL_TOOLBOX_CONTROL( LanguageBoxControl, SfxStringItem );\n\nLanguageBoxControl::LanguageBoxControl( sal_uInt16 nSlotId, sal_uInt16 nId, ToolBox& rTbx )\n : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\nLanguageBoxControl::~LanguageBoxControl()\n{\n}\n\nvoid LanguageBoxControl::StateChanged( sal_uInt16 nID, SfxItemState eState, const SfxPoolItem* pItem )\n{\n (void)nID;\n if (LanguageBox* pBox = static_cast(GetToolBox().GetItemWindow(GetId())))\n {\n if (eState != SFX_ITEM_AVAILABLE)\n pBox->Disable();\n else\n {\n pBox->Enable();\n pBox->Update(dynamic_cast(pItem));\n }\n }\n}\n\nWindow* LanguageBoxControl::CreateItemWindow( Window *pParent )\n{\n return new LanguageBox( pParent );\n}\n\n\/\/ class basctl::LanguageBox -----------------------------------------------\n\nLanguageBox::LanguageBox( Window* pParent ) :\n\n DocListenerBox( pParent ),\n\n m_sNotLocalizedStr( IDEResId( RID_STR_TRANSLATION_NOTLOCALIZED ) ),\n m_sDefaultLanguageStr( IDEResId( RID_STR_TRANSLATION_DEFAULT ) ),\n\n m_bIgnoreSelect( false )\n\n{\n SetSizePixel( Size( 210, 200 ) );\n\n FillBox();\n}\n\nLanguageBox::~LanguageBox()\n{\n ClearBox();\n}\n\nvoid LanguageBox::FillBox()\n{\n SetUpdateMode(false);\n m_bIgnoreSelect = true;\n m_sCurrentText = GetSelectEntry();\n ClearBox();\n\n boost::shared_ptr pCurMgr(GetShell()->GetCurLocalizationMgr());\n if ( pCurMgr->isLibraryLocalized() )\n {\n Enable();\n Locale aDefaultLocale = pCurMgr->getStringResourceManager()->getDefaultLocale();\n Locale aCurrentLocale = pCurMgr->getStringResourceManager()->getCurrentLocale();\n Sequence< Locale > aLocaleSeq = pCurMgr->getStringResourceManager()->getLocales();\n const Locale* pLocale = aLocaleSeq.getConstArray();\n sal_Int32 i, nCount = aLocaleSeq.getLength();\n sal_Int32 nSelPos = LISTBOX_ENTRY_NOTFOUND;\n for ( i = 0; i < nCount; ++i )\n {\n bool bIsDefault = localesAreEqual( aDefaultLocale, pLocale[i] );\n bool bIsCurrent = localesAreEqual( aCurrentLocale, pLocale[i] );\n LanguageType eLangType = LanguageTag::convertToLanguageType( pLocale[i] );\n OUString sLanguage = SvtLanguageTable::GetLanguageString( eLangType );\n if ( bIsDefault )\n {\n sLanguage += \" \";\n sLanguage += m_sDefaultLanguageStr;\n }\n sal_Int32 nPos = InsertEntry( sLanguage );\n SetEntryData( nPos, new LanguageEntry( sLanguage, pLocale[i], bIsDefault ) );\n\n if ( bIsCurrent )\n nSelPos = nPos;\n }\n\n if ( nSelPos != LISTBOX_ENTRY_NOTFOUND )\n {\n SelectEntryPos( nSelPos );\n m_sCurrentText = GetSelectEntry();\n }\n }\n else\n {\n InsertEntry( m_sNotLocalizedStr );\n SelectEntryPos(0);\n Disable();\n }\n\n SetUpdateMode(true);\n m_bIgnoreSelect = false;\n}\n\nvoid LanguageBox::ClearBox()\n{\n sal_Int32 nCount = GetEntryCount();\n for ( sal_Int32 i = 0; i < nCount; ++i )\n {\n LanguageEntry* pEntry = (LanguageEntry*)GetEntryData(i);\n delete pEntry;\n }\n ListBox::Clear();\n}\n\nvoid LanguageBox::SetLanguage()\n{\n LanguageEntry* pEntry = (LanguageEntry*)GetEntryData( GetSelectEntryPos() );\n if ( pEntry )\n GetShell()->GetCurLocalizationMgr()->handleSetCurrentLocale( pEntry->m_aLocale );\n}\n\nvoid LanguageBox::Select()\n{\n if ( !m_bIgnoreSelect )\n SetLanguage();\n else\n SelectEntry( m_sCurrentText ); \/\/ Select after Escape\n}\n\nbool LanguageBox::PreNotify( NotifyEvent& rNEvt )\n{\n bool nDone = false;\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n sal_uInt16 nKeyCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();\n switch( nKeyCode )\n {\n case KEY_RETURN:\n {\n SetLanguage();\n nDone = true;\n }\n break;\n\n case KEY_ESCAPE:\n {\n SelectEntry( m_sCurrentText );\n nDone = true;\n }\n break;\n }\n }\n else if( rNEvt.GetType() == EVENT_GETFOCUS )\n {\n }\n else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n {\n }\n\n return nDone || ListBox::PreNotify( rNEvt );\n}\n\nvoid LanguageBox::Update( const SfxStringItem* pItem )\n{\n FillBox();\n\n if ( pItem && !pItem->GetValue().isEmpty() )\n {\n m_sCurrentText = pItem->GetValue();\n if ( GetSelectEntry() != m_sCurrentText )\n SelectEntry( m_sCurrentText );\n }\n}\n\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nclass SFMLWidget : public Gtk::Widget, public sf::Window\n{\n protected:\n sf::VideoMode m_vMode;\n\n virtual void on_size_request(Gtk::Requisition* requisition);\n virtual void on_size_allocate(Gtk::Allocation& allocation);\n virtual void on_map();\n virtual void on_unmap();\n virtual void on_realize();\n virtual void on_unrealize();\n virtual bool on_idle();\n virtual bool on_expose_event(GdkEventExpose* event);\n\n Glib::RefPtr m_refGdkWindow;\n public:\n SFMLWidget(sf::VideoMode Mode);\n virtual ~SFMLWidget();\n};\n\nbool SFMLWidget::on_idle()\n{\n if(m_refGdkWindow)\n {\n this->display();\n }\n\n return true;\n}\n\nSFMLWidget::SFMLWidget(sf::VideoMode Mode)\n : sf::Window(Mode, \"\")\n{\n set_flags(Gtk::NO_WINDOW); \/\/Makes this behave like an interal object rather then a parent window.\n Glib::signal_idle().connect( sigc::mem_fun(*this, &SFMLWidget::on_idle) );\n}\n\nSFMLWidget::~SFMLWidget()\n{\n}\n\nvoid SFMLWidget::on_size_request(Gtk::Requisition* requisition)\n{\n *requisition = Gtk::Requisition();\n\n sf::Vector2u v = this->getSize();\n\n requisition->width = v.x;\n requisition->height = v.y;\n}\n\nvoid SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)\n{\n \/\/Do something with the space that we have actually been given:\n \/\/(We will not be given heights or widths less than we have requested, though\n \/\/we might get more)\n\n this->set_allocation(allocation);\n\n if(m_refGdkWindow)\n {\n m_refGdkWindow->move_resize(allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height() );\n this->setSize(sf::Vector2u(allocation.get_width(), allocation.get_height()));\n }\n}\n\nvoid SFMLWidget::on_map()\n{\n Gtk::Widget::on_map();\n}\n\nvoid SFMLWidget::on_unmap()\n{\n Gtk::Widget::on_unmap();\n}\n\nvoid SFMLWidget::on_realize()\n{\n Gtk::Widget::on_realize();\n\n if(!m_refGdkWindow)\n {\n \/\/Create the GdkWindow:\n GdkWindowAttr attributes;\n memset(&attributes, 0, sizeof(attributes));\n\n Gtk::Allocation allocation = get_allocation();\n\n \/\/Set initial position and size of the Gdk::Window:\n attributes.x = allocation.get_x();\n attributes.y = allocation.get_y();\n attributes.width = allocation.get_width();\n attributes.height = allocation.get_height();\n\n attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;\n attributes.window_type = GDK_WINDOW_CHILD;\n attributes.wclass = GDK_INPUT_OUTPUT;\n\n\n m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,\n GDK_WA_X | GDK_WA_Y);\n unset_flags(Gtk::NO_WINDOW);\n set_window(m_refGdkWindow);\n\n \/\/set colors\n modify_bg(Gtk::STATE_NORMAL , Gdk::Color(\"red\"));\n modify_fg(Gtk::STATE_NORMAL , Gdk::Color(\"blue\"));\n\n \/\/make the widget receive expose events\n m_refGdkWindow->set_user_data(gobj());\n\n this->sf::Window::create((GDK_WINDOW_XID(m_refGdkWindow->gobj())));\n }\n}\n\nvoid SFMLWidget::on_unrealize()\n{\n m_refGdkWindow.clear();\n\n \/\/Call base class:\n Gtk::Widget::on_unrealize();\n}\n\nbool SFMLWidget::on_expose_event(GdkEventExpose* event)\n{\n if(m_refGdkWindow)\n {\n glClearColor(0.25f, 0.25f, 0.25f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n this->display();\n }\n\n return true;\n}\n\nint main(int argc, char* argv[])\n{\n Gtk::Main kit(argc, argv); \/\/Initialize Gtk\n\n Gtk::Window window; \/\/The GTK window will be our top level Window\n\n \/\/Our RenderWindow will never be below 640x480 (unless we explicitly change it)\n \/\/but it may be more then that\n SFMLWidget ourRenderWindow(sf::VideoMode(640, 480));\n\n \/\/ Doesn't draw the renderWindow but makes it so it will draw when we add it to the window\n ourRenderWindow.show();\n\n \/\/VBox is a vertical box, we're going to pack our render window and a button in here\n Gtk::VBox ourVBox;\n\n Gtk::Button ourButton(\"Hello I do nothing\"); \/\/Just a clickable button, it won't be doing anything\n ourButton.show();\n\n ourVBox.pack_start(ourRenderWindow); \/\/Add ourRenderWindow to the top of the VBox\n\n \/\/PACK_SHRINK makes the VBox only allocate enough space to show the button and nothing more\n ourVBox.pack_start(ourButton, Gtk::PACK_SHRINK);\n ourVBox.show();\n\n window.add(ourVBox); \/\/Adds ourVBox to the window so it (and it's children) can be drawn\n\n Gtk::Main::run(window); \/\/Draw the window\n return 0;\n}\nAdd header comments\/\/ window.cpp\n\/\/ Copyright 2013 Matthew Chandler\n\/\/ windowing code. Using GTK to create the window, SFML to do openGL graphics.\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nclass SFMLWidget : public Gtk::Widget, public sf::Window\n{\n protected:\n sf::VideoMode m_vMode;\n\n virtual void on_size_request(Gtk::Requisition* requisition);\n virtual void on_size_allocate(Gtk::Allocation& allocation);\n virtual void on_map();\n virtual void on_unmap();\n virtual void on_realize();\n virtual void on_unrealize();\n virtual bool on_idle();\n virtual bool on_expose_event(GdkEventExpose* event);\n\n Glib::RefPtr m_refGdkWindow;\n public:\n SFMLWidget(sf::VideoMode Mode);\n virtual ~SFMLWidget();\n};\n\nbool SFMLWidget::on_idle()\n{\n if(m_refGdkWindow)\n {\n this->display();\n }\n\n return true;\n}\n\nSFMLWidget::SFMLWidget(sf::VideoMode Mode)\n : sf::Window(Mode, \"\")\n{\n set_flags(Gtk::NO_WINDOW); \/\/Makes this behave like an interal object rather then a parent window.\n Glib::signal_idle().connect( sigc::mem_fun(*this, &SFMLWidget::on_idle) );\n}\n\nSFMLWidget::~SFMLWidget()\n{\n}\n\nvoid SFMLWidget::on_size_request(Gtk::Requisition* requisition)\n{\n *requisition = Gtk::Requisition();\n\n sf::Vector2u v = this->getSize();\n\n requisition->width = v.x;\n requisition->height = v.y;\n}\n\nvoid SFMLWidget::on_size_allocate(Gtk::Allocation& allocation)\n{\n \/\/Do something with the space that we have actually been given:\n \/\/(We will not be given heights or widths less than we have requested, though\n \/\/we might get more)\n\n this->set_allocation(allocation);\n\n if(m_refGdkWindow)\n {\n m_refGdkWindow->move_resize(allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height() );\n this->setSize(sf::Vector2u(allocation.get_width(), allocation.get_height()));\n }\n}\n\nvoid SFMLWidget::on_map()\n{\n Gtk::Widget::on_map();\n}\n\nvoid SFMLWidget::on_unmap()\n{\n Gtk::Widget::on_unmap();\n}\n\nvoid SFMLWidget::on_realize()\n{\n Gtk::Widget::on_realize();\n\n if(!m_refGdkWindow)\n {\n \/\/Create the GdkWindow:\n GdkWindowAttr attributes;\n memset(&attributes, 0, sizeof(attributes));\n\n Gtk::Allocation allocation = get_allocation();\n\n \/\/Set initial position and size of the Gdk::Window:\n attributes.x = allocation.get_x();\n attributes.y = allocation.get_y();\n attributes.width = allocation.get_width();\n attributes.height = allocation.get_height();\n\n attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;\n attributes.window_type = GDK_WINDOW_CHILD;\n attributes.wclass = GDK_INPUT_OUTPUT;\n\n\n m_refGdkWindow = Gdk::Window::create(get_window(), &attributes,\n GDK_WA_X | GDK_WA_Y);\n unset_flags(Gtk::NO_WINDOW);\n set_window(m_refGdkWindow);\n\n \/\/set colors\n modify_bg(Gtk::STATE_NORMAL , Gdk::Color(\"red\"));\n modify_fg(Gtk::STATE_NORMAL , Gdk::Color(\"blue\"));\n\n \/\/make the widget receive expose events\n m_refGdkWindow->set_user_data(gobj());\n\n this->sf::Window::create((GDK_WINDOW_XID(m_refGdkWindow->gobj())));\n }\n}\n\nvoid SFMLWidget::on_unrealize()\n{\n m_refGdkWindow.clear();\n\n \/\/Call base class:\n Gtk::Widget::on_unrealize();\n}\n\nbool SFMLWidget::on_expose_event(GdkEventExpose* event)\n{\n if(m_refGdkWindow)\n {\n glClearColor(0.25f, 0.25f, 0.25f, 0.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n this->display();\n }\n\n return true;\n}\n\nint main(int argc, char* argv[])\n{\n Gtk::Main kit(argc, argv); \/\/Initialize Gtk\n\n Gtk::Window window; \/\/The GTK window will be our top level Window\n\n \/\/Our RenderWindow will never be below 640x480 (unless we explicitly change it)\n \/\/but it may be more then that\n SFMLWidget ourRenderWindow(sf::VideoMode(640, 480));\n\n \/\/ Doesn't draw the renderWindow but makes it so it will draw when we add it to the window\n ourRenderWindow.show();\n\n \/\/VBox is a vertical box, we're going to pack our render window and a button in here\n Gtk::VBox ourVBox;\n\n Gtk::Button ourButton(\"Hello I do nothing\"); \/\/Just a clickable button, it won't be doing anything\n ourButton.show();\n\n ourVBox.pack_start(ourRenderWindow); \/\/Add ourRenderWindow to the top of the VBox\n\n \/\/PACK_SHRINK makes the VBox only allocate enough space to show the button and nothing more\n ourVBox.pack_start(ourButton, Gtk::PACK_SHRINK);\n ourVBox.show();\n\n window.add(ourVBox); \/\/Adds ourVBox to the window so it (and it's children) can be drawn\n\n Gtk::Main::run(window); \/\/Draw the window\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"window.h\"\n\nWindow::Window() {\n \/\/gl.out(\"Created window.\\n\");\n SDL_Window *win = SDL_CreateWindow(\"Hello World!\", 100, 100, 640, 480, SDL_WINDOW_SHOWN);\n if (win == NULL){\n std::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n SDL_Quit();\n\t}\n}\n\nWindow::~Window() {\n \/\/gl.out(\"Closing window.\\n\");\n}\nDeleted window.cpp<|endoftext|>"} {"text":"#define UNICODE\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MODKEY VK_NONCONVERT\n#define SUBMODKEY VK_LSHIFT\n\nusing stdfunc = std::function;\nusing wndtype = std::tuple;\n\ntemplate \nvoid print(T str) {\n std::wcout << str << std::endl;\n}\n\n\/* function declarations *\/\nHWND getHandle();\nstd::wstring getTitle();\nbool start_hook(HINSTANCE, HWND);\nbool stop_hook();\nvoid show_taskbar();\nvoid hide_taskbar();\nvoid create_window(HINSTANCE);\nvoid get_all_window();\nstdfunc func_switcher(const stdfunc&, const stdfunc&);\nstdfunc move_focus(const int);\nstdfunc move_window(const int);\nvoid maximize();\nvoid close_window();\nvoid quit();\nvoid tile_layout();\nvoid spiral_layout();\n\n\/* variables *\/\nHHOOK hhk;\nHWND clientWnd;\nstd::vector wndList;\nstd::vector::iterator focusWnd;\nstd::string layout = \"TILE\";\nstatic std::map arrange = {\n { \"TILE\", tile_layout },\n { \"SPIRAL\", spiral_layout }\n};\nstatic std::map isPressed = {\n { \"MOD\", false },\n { \"SUBMOD\", false }\n};\nstatic std::map callFunc = {\n { 'J', func_switcher( move_focus(1), move_window(2) )},\n { 'K', func_switcher( move_focus(-1), move_window(-2) )},\n { 'M', maximize },\n { 'D', func_switcher( []{}, close_window )},\n { 'Q', quit }\n};\n\n\/* function implementations *\/\nHWND getHandle(wndtype wnd) {\n return std::get<0>(wnd);\n}\n\nstdfunc func_switcher(const stdfunc& func, const stdfunc& sub_func) {\n return [=] {\n !isPressed[\"SUBMOD\"] ? func() : sub_func();\n };\n};\n\nstdfunc move_focus(const int value) {\n return [=] {\n print(value);\n };\n};\n\nstdfunc move_window(const int value) {\n return [=] {\n print(\"move_window\");\n print(value);\n };\n}\n\nvoid maximize() {\n\n}\n\nvoid close_window() {\n\n}\n\nvoid quit() {\n PostQuitMessage(0);\n}\n\nvoid tile_layout() {\n\n}\n\nvoid spiral_layout() {\n\n}\n\nLRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN: {\n callFunc[wParam]();\n break;\n }\n default:\n return DefWindowProc(hWnd, msg, wParam, lParam);\n }\n return 0;\n}\n\nLRESULT CALLBACK LLKeyboardProc(int code, WPARAM wParam, LPARAM lParam) {\n if (code < 0)\n return CallNextHookEx(hhk, code, wParam, lParam);\n\n if (code == HC_ACTION) {\n KBDLLHOOKSTRUCT* tmp = (KBDLLHOOKSTRUCT*)lParam;\n DWORD vkCode = tmp->vkCode;\n bool isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);\n\n static auto switch_flag = [&](const std::string name) {\n isPressed[name] = isKeyDown;\n return CallNextHookEx(hhk, code, wParam, lParam);\n };\n\n if (vkCode == MODKEY)\n switch_flag(\"MOD\");\n else if (vkCode == SUBMODKEY)\n switch_flag(\"SUBMOD\");\n\n if (isPressed[\"MOD\"] && isKeyDown && callFunc.count(vkCode) == 1)\n PostMessage(clientWnd, WM_KEYDOWN, vkCode, lParam);\n }\n\n return CallNextHookEx(hhk, code, wParam, lParam);\n}\n\n\nBOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM lParam) {\n if (IsWindowVisible(hWnd)) {\n static wchar_t buf[128];\n std::wstring str;\n\n GetWindowText(hWnd, buf, 128);\n str = buf;\n if (str == L\"\")\n return TRUE;\n\n std::wstring title = str;\n\n GetClassName(hWnd, buf, 128);\n str = buf;\n if (str == L\"Progman\" || str == L\"MainWindowClass\")\n return TRUE;\n\n print(title);\n print(hWnd);\n print(\"\");\n\n wndList.push_back(std::make_tuple(hWnd));\n }\n\n return TRUE;\n}\n\nbool start_hook(HINSTANCE hInst) {\n hhk = SetWindowsHookEx(WH_KEYBOARD_LL, LLKeyboardProc, hInst, 0);\n\n if (hhk == nullptr) {\n MessageBox(nullptr, TEXT(\"Error in start_hook() : hhk is nullptr\"), nullptr, MB_OK);\n return false;\n }\n\n return true;\n}\n\nbool stop_hook() {\n if (UnhookWindowsHookEx(hhk) == 0) {\n MessageBox(nullptr, TEXT(\"Error in stop_hook()\"), nullptr, MB_OK);\n return false;\n }\n\n return true;\n}\n\nvoid show_taskbar() {\n HWND hTaskBar = FindWindow(TEXT(\"Shell_TrayWnd\"), nullptr);\n HWND hStart = FindWindow(TEXT(\"Button\"), nullptr);\n ShowWindow(hTaskBar, SW_SHOW);\n ShowWindow(hStart, SW_SHOW);\n}\n\nvoid hide_taskbar() {\n HWND hTaskBar = FindWindow(TEXT(\"Shell_TrayWnd\"), nullptr);\n HWND hStart = FindWindow(TEXT(\"Button\"), nullptr);\n ShowWindow(hTaskBar, SW_HIDE);\n ShowWindow(hStart, SW_HIDE);\n}\n\nvoid create_window(HINSTANCE hInstance) {\n WNDCLASSEX wcex;\n auto className = TEXT(\"WintileClass\");\n\n wcex.cbSize = sizeof(WNDCLASSEX);\n wcex.style = 0;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = 0;\n wcex.cbWndExtra = 0;\n wcex.hInstance = hInstance;\n wcex.hIcon = nullptr;\n wcex.hCursor = nullptr;\n wcex.hbrBackground = nullptr;\n wcex.lpszMenuName = nullptr;\n wcex.lpszClassName = className;\n wcex.hIconSm = nullptr;\n\n if (RegisterClassEx(&wcex) == 0)\n return;\n\n clientWnd = CreateWindowEx(0, className, TEXT(\"wintile\"), 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);\n\n if (clientWnd == nullptr)\n return;\n}\n\nvoid get_all_window() {\n EnumWindows(EnumWndProc, (LPARAM)nullptr);\n focusWnd = wndList.begin();\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n MSG msg;\n\n std::setlocale(LC_ALL, \"\");\n create_window(hInstance);\n hide_taskbar();\n get_all_window();\n arrange[layout];\n \/\/MoveWindow(getHandle(wndList[2]), 0, 0, 1280, 800, TRUE);\n start_hook(hInstance);\n\n while (GetMessage(&msg, nullptr, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n stop_hook();\n show_taskbar();\n\n return msg.wParam;\n}\n\nWINDOW_WIDTH, HEIGHT#define UNICODE\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MODKEY VK_NONCONVERT\n#define SUBMODKEY VK_LSHIFT\n\nusing stdfunc = std::function;\nusing wndtype = std::tuple;\n\ntemplate \nvoid print(T str) {\n std::wcout << str << std::endl;\n}\n\n\/* function declarations *\/\nHWND getHandle();\nstd::wstring getTitle();\nbool start_hook(HINSTANCE, HWND);\nbool stop_hook();\nvoid show_taskbar();\nvoid hide_taskbar();\nvoid create_window(HINSTANCE);\nvoid get_all_window();\nstdfunc func_switcher(const stdfunc&, const stdfunc&);\nstdfunc move_focus(const int);\nstdfunc move_window(const int);\nvoid maximize();\nvoid close_window();\nvoid quit();\nvoid tile_layout();\nvoid spiral_layout();\n\n\/* variables *\/\nHHOOK hhk;\nHWND clientWnd;\nstatic const unsigned int WINDOW_WIDTH = GetSystemMetrics(SM_CXSCREEN);\nstatic const unsigned int WINDOW_HEIGHT = GetSystemMetrics(SM_CYSCREEN);\nstd::vector wndList;\nstd::vector::iterator focusWnd;\nstd::string layout = \"TILE\";\nstatic std::map arrange = {\n { \"TILE\", tile_layout },\n { \"SPIRAL\", spiral_layout }\n};\nstatic std::map isPressed = {\n { \"MOD\", false },\n { \"SUBMOD\", false }\n};\nstatic std::map callFunc = {\n { 'J', func_switcher( move_focus(1), move_window(2) )},\n { 'K', func_switcher( move_focus(-1), move_window(-2) )},\n { 'M', maximize },\n { 'D', func_switcher( []{}, close_window )},\n { 'Q', quit }\n};\n\n\/* function implementations *\/\nHWND getHandle(wndtype wnd) {\n return std::get<0>(wnd);\n}\n\nstdfunc func_switcher(const stdfunc& func, const stdfunc& sub_func) {\n return [=] {\n !isPressed[\"SUBMOD\"] ? func() : sub_func();\n };\n};\n\nstdfunc move_focus(const int value) {\n return [=] {\n print(value);\n };\n};\n\nstdfunc move_window(const int value) {\n return [=] {\n print(\"move_window\");\n print(value);\n };\n}\n\nvoid maximize() {\n\n}\n\nvoid close_window() {\n\n}\n\nvoid quit() {\n PostQuitMessage(0);\n}\n\nvoid tile_layout() {\n\n}\n\nvoid spiral_layout() {\n\n}\n\nLRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n switch (msg) {\n case WM_KEYDOWN: {\n callFunc[wParam]();\n break;\n }\n default:\n return DefWindowProc(hWnd, msg, wParam, lParam);\n }\n return 0;\n}\n\nLRESULT CALLBACK LLKeyboardProc(int code, WPARAM wParam, LPARAM lParam) {\n if (code < 0)\n return CallNextHookEx(hhk, code, wParam, lParam);\n\n if (code == HC_ACTION) {\n KBDLLHOOKSTRUCT* tmp = (KBDLLHOOKSTRUCT*)lParam;\n DWORD vkCode = tmp->vkCode;\n bool isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);\n\n static auto switch_flag = [&](const std::string name) {\n isPressed[name] = isKeyDown;\n return CallNextHookEx(hhk, code, wParam, lParam);\n };\n\n if (vkCode == MODKEY)\n switch_flag(\"MOD\");\n else if (vkCode == SUBMODKEY)\n switch_flag(\"SUBMOD\");\n\n if (isPressed[\"MOD\"] && isKeyDown && callFunc.count(vkCode) == 1)\n PostMessage(clientWnd, WM_KEYDOWN, vkCode, lParam);\n }\n\n return CallNextHookEx(hhk, code, wParam, lParam);\n}\n\n\nBOOL CALLBACK EnumWndProc(HWND hWnd, LPARAM lParam) {\n if (IsWindowVisible(hWnd)) {\n static wchar_t buf[128];\n std::wstring str;\n\n GetWindowText(hWnd, buf, 128);\n str = buf;\n if (str == L\"\")\n return TRUE;\n\n std::wstring title = str;\n\n GetClassName(hWnd, buf, 128);\n str = buf;\n if (str == L\"Progman\" || str == L\"MainWindowClass\")\n return TRUE;\n\n print(title);\n print(hWnd);\n print(\"\");\n\n wndList.push_back(std::make_tuple(hWnd));\n }\n\n return TRUE;\n}\n\nbool start_hook(HINSTANCE hInst) {\n hhk = SetWindowsHookEx(WH_KEYBOARD_LL, LLKeyboardProc, hInst, 0);\n\n if (hhk == nullptr) {\n MessageBox(nullptr, TEXT(\"Error in start_hook() : hhk is nullptr\"), nullptr, MB_OK);\n return false;\n }\n\n return true;\n}\n\nbool stop_hook() {\n if (UnhookWindowsHookEx(hhk) == 0) {\n MessageBox(nullptr, TEXT(\"Error in stop_hook()\"), nullptr, MB_OK);\n return false;\n }\n\n return true;\n}\n\nvoid show_taskbar() {\n HWND hTaskBar = FindWindow(TEXT(\"Shell_TrayWnd\"), nullptr);\n HWND hStart = FindWindow(TEXT(\"Button\"), nullptr);\n ShowWindow(hTaskBar, SW_SHOW);\n ShowWindow(hStart, SW_SHOW);\n}\n\nvoid hide_taskbar() {\n HWND hTaskBar = FindWindow(TEXT(\"Shell_TrayWnd\"), nullptr);\n HWND hStart = FindWindow(TEXT(\"Button\"), nullptr);\n ShowWindow(hTaskBar, SW_HIDE);\n ShowWindow(hStart, SW_HIDE);\n}\n\nvoid create_window(HINSTANCE hInstance) {\n WNDCLASSEX wcex;\n auto className = TEXT(\"WintileClass\");\n\n wcex.cbSize = sizeof(WNDCLASSEX);\n wcex.style = 0;\n wcex.lpfnWndProc = WndProc;\n wcex.cbClsExtra = 0;\n wcex.cbWndExtra = 0;\n wcex.hInstance = hInstance;\n wcex.hIcon = nullptr;\n wcex.hCursor = nullptr;\n wcex.hbrBackground = nullptr;\n wcex.lpszMenuName = nullptr;\n wcex.lpszClassName = className;\n wcex.hIconSm = nullptr;\n\n if (RegisterClassEx(&wcex) == 0)\n return;\n\n clientWnd = CreateWindowEx(0, className, TEXT(\"wintile\"), 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);\n\n if (clientWnd == nullptr)\n return;\n}\n\nvoid get_all_window() {\n EnumWindows(EnumWndProc, (LPARAM)nullptr);\n focusWnd = wndList.begin();\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n MSG msg;\n\n std::setlocale(LC_ALL, \"\");\n create_window(hInstance);\n hide_taskbar();\n get_all_window();\n arrange[layout];\n \/\/MoveWindow(getHandle(wndList[2]), 0, 0, 1280, 800, TRUE);\n start_hook(hInstance);\n\n while (GetMessage(&msg, nullptr, 0, 0) > 0) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n stop_hook();\n show_taskbar();\n\n return msg.wParam;\n}\n\n<|endoftext|>"} {"text":"#include \"crypto.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sha256.h\"\n\nconst int PACKET_DATA_LENGTH = 32; \/\/bytes\nconst int PACKET_CHECKSUM_LENGTH = 32;\nconst int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;\n\nchar* OTP(unsigned long long* index, const unsigned long long amount);\nchar* xorCharArray(const char* first, const char* second, unsigned long long length);\nunsigned long long unsignedLongLongRand();\nchar* longToCharArray(unsigned long long num, int size);\nunsigned long long charArrayToLong(const char* data, int size);\nbool charArrayEquals(const char* data1, const char* data2, int size);\nchar* concat(const char* left, const char* right, int sizel, int sizer);\nchar* sha_256(char* buf);\n\n\/\/ send command\nssize_t cwrite(int fd, const void *buf, size_t count) {\n\t\/\/long indexOfPad = random integer from 0 to size of OTP in bytes\n\tunsigned long long* indexOfPad = unsignedLongLongRand();\n\t\/\/char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);\n\tchar* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);\n\t\/\/send nonce to reciever\n\tint n;\n\tn = write(fd, nonce, PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/1\n\t\/\/long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));\n\tunsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));\n\t\/\/2\n\t\/\/byte* response = response from receiver\n\tchar buffer[PACKET_LENGTH];\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\tn = write(fd, \"NO\", PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\tn = write(fd, \"NO\", PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn -1;\n\t}\n\telse if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {\n\t\t\/\/myChecksum != response\n\t\treturn -1;\n\t}\n\t\/\/send ok to reciever\n\tn = write(fd, \"OK\", PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/2.1\n\t\/\/2.2\n\t\/\/for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {\n\tfor(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {\n\t\t\/\/char* toSend = buf[bufferIndex];\n\t\tchar* toSend = buf[bufferIndex];\n\t\t\/\/char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* key = OTP(indexOfPad, PACKET_LENGTH);\n\t\t\/\/char* mac = sha-256(concat(toSend, key));\n\t\tchar* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));\n\t\t\/\/char* message = concat(toSend, mac);\n\t\tchar* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);\n\t\t\/\/char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* pad = OTP(indexOfPad, PACKET_LENGTH);\n\t\t\/\/send xor(message, pad) to reciever \n\t\tn = write(fd, xorCharArray(message, pad), PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\t\/\/3\n\t}\n}\n\n\/\/ recv command\nssize_t cread(int fd, void *buf, size_t count) {\n\t\/\/1\n\t\/\/wait for nonce from sender\n\tchar buffer[PACKET_LENGTH];\n\tint n;\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\treturn -1;\n\t}\n\t\/\/long indexOfPad;\n\t\/\/indexOfPad = charArrayToLong(message recieved from sender);\n\tunsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);\n\t\/\/byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\tchar* message = OTP(&indexOfPad, PACKET_LENGTH);\n\t\/\/byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\tchar* pad = OTP(&indexOfPad, PACKET_LENGTH);\n\t\/\/byte* reply = xor(message, pad);\n\tchar* reply = xorCharArray(message, pad, PACKET_LENGTH);\n\t\/\/send reply to sender\n\tn = write(fd, reply, PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/2\n\t\/\/2.1\n\t\/\/recieve ok, if not retry, abort, ignore?\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\treturn -1;\n\t}\n\telse if(std::strcmp(buffer, \"OK\") != 0) {\n\t\t\/\/error - not ok\n\t\treturn -1;\n\t}\n\t\/\/2.2\n\t\/\/int amount_recv = 0;\n\tint amount_recv = 0;\n\t\/\/while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {\n\twhile(amount_recv + PACKET_DATA_LENGTH < len) {\n\t\t\/\/3\n\t\t\/\/byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender\n\t\tchar data[PACKET_LENGTH];\n\t\tamount_recv += read(fd, data, PACKET_LENGTH);\n\t\t\/\/byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* key = OTP(&indexOfPad, PACKET_LENGTH);\n\t\t\/\/pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* pad = OTP(&indexOfPad, PACKET_LENGTH);\n\t\t\/\/byte* messsage = xor(data, pad);\n\t\tchar* message = xorCharArray(data, pad, PACKET_LENGTH);\n\t\t\/\/byte* checksum = data + PACKET_DATA_LENGTH; checksum is last part after the data\n\t\tchar* checksum = message + PACKET_DATA_LENGTH;\n\t\t\/\/byte* mac = sha-256(concat(messsage, key)); recompute mac\n\t\t\/\/std::string msgStr(message);\n\t\t\/\/std::string keyStr(key);\n\t\tchar* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));\n\t\tif(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {\n\t\t\t\/\/checksum != mac\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t\/\/copy message into buffer\n\t\tfor(int i = 0; i < PACKET_DATA_LENGTH; i++) {\n\t\t\tbuf[i] = message[i];\n\t\t}\n\t\tbuf += PACKET_DATA_LENGTH;\n\t}\n\treturn amount_recv;\t\n}\n\nchar* OTP(unsigned long long* index, const unsigned long long amount) {\n\tstd::ifstream pad;\n\tpad.open(\"otp.key\");\n\tpad.seekg(*index);\n\tchar result[amount];\n\tpad.read(result, amount);\n\tpad.close();\n\t*index += amount;\n\treturn result;\n\t\/\/byte pad[amount]; allocate amount bytes to return\n\t\/\/seek to index in OTP\n\t\/\/for(long i = 0; i < amount; i++)\n\t\t\/\/pad[i] = readByte(); read in each byte from the file\n\t\/\/*index += amount; increment index so we don't use the same pad twice\n\t\/\/return pad;\n}\n\nchar* xorCharArray(const char* first, const char* second, unsigned long long length) {\n\t\/\/byte result[length];\n\tchar result[length];\n\t\/\/for(long i = 0; i < length; i++) {\n\tfor(unsigned long long i = 0; i < length; i++) {\n\t\tresult[i] = first[i] ^ second[i];\n\t}\n\treturn result;\n}\n\nunsigned long long unsignedLongLongRand() {\n unsigned long long rand1 = abs(rand());\n unsigned long long rand2 = abs(rand());\n rand1 <<= (sizeof(int)*8); \n unsigned long long randULL = (rand1 | rand2); \n return randULL;\n}\n\nchar* longToCharArray(unsigned long long num, int size) {\n\treturn reinterpret_cast(num);\n}\n\nunsigned long long charArrayToLong(const char* data, int size){\n\treturn reinterpret_cast(data);\n}\n\nbool charArrayEquals(const char* data1, const char* data2, int size) {\n\tfor(int i = 0; i < size; i++) {\n\t\tif(data1[i] != data2[i]) return false;\n\t}\n\treturn true;\n}\n\nchar* concat(const char* left, const char* right, int sizel, int sizer) {\n\tchar result[sizel + sizer];\n\tfor(int i = 0; i < sizel; i++) {\n\t\tresult[i] = left[i];\n\t}\n\tfor(int i = 0; i < sizer; i++) {\n\t\tresult[sizel + i] = right[i];\n\t}\n\treturn result;\n\t\/\/std::string msgStr(left);\n\t\/\/std::string keyStr(right);\n\t\/\/return &(left + right)[0];\n}\n\nchar* sha_256(char* buf) {\n\treturn &sha256(buf)[0];\n}\nadded heap stuff#include \"crypto.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sha256.h\"\n\nconst int PACKET_DATA_LENGTH = 32; \/\/bytes\nconst int PACKET_CHECKSUM_LENGTH = 32;\nconst int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;\n\nchar* OTP(unsigned long long* index, const unsigned long long amount);\nchar* xorCharArray(const char* first, const char* second, unsigned long long length);\nunsigned long long unsignedLongLongRand();\nchar* longToCharArray(unsigned long long num, int size);\nunsigned long long charArrayToLong(const char* data, int size);\nbool charArrayEquals(const char* data1, const char* data2, int size);\nchar* concat(const char* left, const char* right, int sizel, int sizer);\nchar* sha_256(char* buf);\n\n\/\/ send command\nssize_t cwrite(int fd, const void *buf, size_t count) {\n\t\/\/long indexOfPad = random integer from 0 to size of OTP in bytes\n\tunsigned long long* indexOfPad = unsignedLongLongRand();\n\t\/\/char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);\n\tchar* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);\n\t\/\/send nonce to reciever\n\tint n;\n\tn = write(fd, nonce, PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/1\n\t\/\/long myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));\n\tunsigned long long myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH));\n\t\/\/2\n\t\/\/byte* response = response from receiver\n\tchar buffer[PACKET_LENGTH];\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\tn = write(fd, \"NO\", PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\tn = write(fd, \"NO\", PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn -1;\n\t}\n\telse if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {\n\t\t\/\/myChecksum != response\n\t\treturn -1;\n\t}\n\t\/\/send ok to reciever\n\tn = write(fd, \"OK\", PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/2.1\n\t\/\/2.2\n\t\/\/for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {\n\tfor(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {\n\t\t\/\/char* toSend = buf[bufferIndex];\n\t\tchar* toSend = buf[bufferIndex];\n\t\t\/\/char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* key = OTP(indexOfPad, PACKET_LENGTH);\n\t\t\/\/char* mac = sha-256(concat(toSend, key));\n\t\tchar* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));\n\t\t\/\/char* message = concat(toSend, mac);\n\t\tchar* message = concat(toSend, mac, bufferIndex, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);\n\t\t\/\/char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* pad = OTP(indexOfPad, PACKET_LENGTH);\n\t\t\/\/send xor(message, pad) to reciever \n\t\tn = write(fd, xorCharArray(message, pad), PACKET_LENGTH);\n\t\tif (n < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\t\/\/3\n\t}\n}\n\n\/\/ recv command\nssize_t cread(int fd, void *buf, size_t count) {\n\t\/\/1\n\t\/\/wait for nonce from sender\n\tchar buffer[PACKET_LENGTH];\n\tint n;\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\treturn -1;\n\t}\n\t\/\/long indexOfPad;\n\t\/\/indexOfPad = charArrayToLong(message recieved from sender);\n\tunsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);\n\t\/\/byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\tchar* message = OTP(&indexOfPad, PACKET_LENGTH);\n\t\/\/byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\tchar* pad = OTP(&indexOfPad, PACKET_LENGTH);\n\t\/\/byte* reply = xor(message, pad);\n\tchar* reply = xorCharArray(message, pad, PACKET_LENGTH);\n\t\/\/send reply to sender\n\tn = write(fd, reply, PACKET_LENGTH);\n\tif (n < 0) {\n\t\treturn -1;\n\t}\n\t\/\/2\n\t\/\/2.1\n\t\/\/recieve ok, if not retry, abort, ignore?\n\tn = read(fd, buffer, PACKET_LENGTH);\n\tif (n < 0) {\n\t\t\/\/error\n\t\treturn -1;\n\t}\n\telse if (n == 0) {\n\t\t\/\/error - no message\n\t\treturn -1;\n\t}\n\telse if(std::strcmp(buffer, \"OK\") != 0) {\n\t\t\/\/error - not ok\n\t\treturn -1;\n\t}\n\t\/\/2.2\n\t\/\/int amount_recv = 0;\n\tint amount_recv = 0;\n\t\/\/while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {\n\twhile(amount_recv + PACKET_DATA_LENGTH < len) {\n\t\t\/\/3\n\t\t\/\/byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender\n\t\tchar data[PACKET_LENGTH];\n\t\tamount_recv += read(fd, data, PACKET_LENGTH);\n\t\t\/\/byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* key = OTP(&indexOfPad, PACKET_LENGTH);\n\t\t\/\/pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);\n\t\tchar* pad = OTP(&indexOfPad, PACKET_LENGTH);\n\t\t\/\/byte* messsage = xor(data, pad);\n\t\tchar* message = xorCharArray(data, pad, PACKET_LENGTH);\n\t\t\/\/byte* checksum = data + PACKET_DATA_LENGTH; checksum is last part after the data\n\t\tchar* checksum = message + PACKET_DATA_LENGTH;\n\t\t\/\/byte* mac = sha-256(concat(messsage, key)); recompute mac\n\t\t\/\/std::string msgStr(message);\n\t\t\/\/std::string keyStr(key);\n\t\tchar* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));\n\t\tif(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {\n\t\t\t\/\/checksum != mac\n\t\t\tdelete[] mac;\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\t\/\/copy message into buffer\n\t\tfor(int i = 0; i < PACKET_DATA_LENGTH; i++) {\n\t\t\tbuf[i] = message[i];\n\t\t}\n\t\tbuf += PACKET_DATA_LENGTH;\n\t\tdelete[] mac;\n\t}\n\treturn amount_recv;\t\n}\n\nchar* OTP(unsigned long long* index, const unsigned long long amount) {\n\tstd::ifstream pad;\n\tpad.open(\"otp.key\");\n\tpad.seekg(*index);\n\tchar result[amount];\n\tpad.read(result, amount);\n\tpad.close();\n\t*index += amount;\n\treturn result;\n\t\/\/byte pad[amount]; allocate amount bytes to return\n\t\/\/seek to index in OTP\n\t\/\/for(long i = 0; i < amount; i++)\n\t\t\/\/pad[i] = readByte(); read in each byte from the file\n\t\/\/*index += amount; increment index so we don't use the same pad twice\n\t\/\/return pad;\n}\n\nchar* xorCharArray(const char* first, const char* second, unsigned long long length) {\n\t\/\/byte result[length];\n\tchar result[length];\n\t\/\/for(long i = 0; i < length; i++) {\n\tfor(unsigned long long i = 0; i < length; i++) {\n\t\tresult[i] = first[i] ^ second[i];\n\t}\n\treturn result;\n}\n\nunsigned long long unsignedLongLongRand() {\n unsigned long long rand1 = abs(rand());\n unsigned long long rand2 = abs(rand());\n rand1 <<= (sizeof(int)*8); \n unsigned long long randULL = (rand1 | rand2); \n return randULL;\n}\n\nchar* longToCharArray(unsigned long long num, int size) {\n\treturn reinterpret_cast(num);\n}\n\nunsigned long long charArrayToLong(const char* data, int size){\n\treturn reinterpret_cast(data);\n}\n\nbool charArrayEquals(const char* data1, const char* data2, int size) {\n\tfor(int i = 0; i < size; i++) {\n\t\tif(data1[i] != data2[i]) return false;\n\t}\n\treturn true;\n}\n\nchar* concat(const char* left, const char* right, int sizel, int sizer) {\n\tchar* result = new char[sizel + sizer];\n\tfor(int i = 0; i < sizel; i++) {\n\t\tresult[i] = left[i];\n\t}\n\tfor(int i = 0; i < sizer; i++) {\n\t\tresult[sizel + i] = right[i];\n\t}\n\treturn result;\n\t\/\/std::string msgStr(left);\n\t\/\/std::string keyStr(right);\n\t\/\/return &(left + right)[0];\n}\n\nchar* sha_256(char* buf) {\n\treturn &sha256(buf)[0];\n}\n<|endoftext|>"} {"text":"\/* \n * Copyright (c) 2013-2014, Alberto Corona \n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"parser.h\"\n\nParser::Parser() {};\nParser::~Parser() {};\n\nint Parser::OpenConfig(const char *build_file)\n{\n\tif (AssertYML(build_file) == 1) {\n\t\tconf = fopen(build_file, \"r\");\n\t\tParseConfig();\n\t\tReadValues();\n\t\tCloseConfig();\n\t\treturn 1;\n\t} else {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint Parser::ParseConfig()\n{\n\tif (conf != NULL) {\n\t\tyaml_parser_initialize(&parser);\n\t\tyaml_parser_set_input_file(&parser, conf);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint Parser::CloseConfig()\n{\n\tif ((&parser != NULL) && (conf != NULL)) {\n\t\tyaml_parser_delete(&parser);\n\t\tfclose(conf);\n\t\treturn 1;\n\t} else {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint Parser::AssertYML(const char *build_file)\n{\n\tconst char *ext;\n\text = strrchr(build_file, '.');\n\tif (opendir(build_file) != NULL) {\n\t\tprintf(\"Error: %s is a directory\\n\", build_file);\n\t\treturn -3;\n\t}\n\tif (!ext) {\n\t\tprintf(\"Error: %s has no extension\\n\", build_file);\n\t\treturn -1;\n\t}\n\tif ((strcmp(ext + 1, \"yml\") == 0) || (strcmp(ext + 1, \"yaml\") == 0) || (strcmp(ext + 1, \"ybf\") == 0)) {\n\t\treturn 1;\n\t} else {\n\t\tprintf(\"Error: %s is not a valid build file\\n\", build_file);\n\t\treturn -2;\n\t}\n\treturn 0;\n}\n\nint Parser::ReadValues()\n{\n\tdo {\n\t\tyaml_parser_scan(&parser, &token);\n\t\tswitch (token.type) {\n\t\tcase YAML_VERSION_DIRECTIVE_TOKEN:\n\t\t\tbreak;\n\t\tcase YAML_NO_TOKEN:\n\t\t\tprintf(\"No token\\n\");\n\t\t\tbreak;\n\t\tcase YAML_STREAM_START_TOKEN:\n\t\t\tprintf(\"Stream start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_STREAM_END_TOKEN:\n\t\t\tprintf(\"Stream end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_KEY_TOKEN:\n\t\t\tprintf(\"\\tKey token: \");\n\t\t\tbreak;\n\t\tcase YAML_VALUE_TOKEN:\n\t\t\tprintf(\"\\t\\tValue token: \");\n\t\t\tbreak;\n\t\tcase YAML_TAG_DIRECTIVE_TOKEN:\n\t\t\tprintf(\"Tag directive: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_DOCUMENT_START_TOKEN:\n\t\t\tprintf(\"Document start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_DOCUMENT_END_TOKEN:\n\t\t\tprintf(\"Document end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_SEQUENCE_START_TOKEN:\n\t\t\tprintf(\"Block sequence start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_END_TOKEN:\n\t\t\tprintf(\"Block sequence end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_MAPPING_START_TOKEN:\n\t\t\tprintf(\"Block Mapping start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_SEQUENCE_START_TOKEN:\n\t\t\tprintf(\"Sequence start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_SEQUENCE_END_TOKEN:\n\t\t\tprintf(\"Sequence end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_MAPPING_START_TOKEN:\n\t\t\tprintf(\"Mapping start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_MAPPING_END_TOKEN:\n\t\t\tprintf(\"Mapping end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_ENTRY_TOKEN:\n\t\t\tprintf(\"Block entry\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_ENTRY_TOKEN:\n\t\t\tprintf(\"Block entry token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_ALIAS_TOKEN:\n\t\t\tprintf(\"Alias token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_ANCHOR_TOKEN:\n\t\t\tprintf(\"Anchor token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_TAG_TOKEN:\n\t\t\tprintf(\"Tag token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_SCALAR_TOKEN:\n\t\t\tprintf(\"%s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\t}\n\t} while (token.type != YAML_STREAM_END_TOKEN);\n\tyaml_token_delete(&token);\n\treturn 0;\n}\nparser: fix opening a non-existing file\/* \n * Copyright (c) 2013-2014, Alberto Corona \n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \"parser.h\"\n\nParser::Parser() {};\nParser::~Parser() {};\n\nint Parser::OpenConfig(const char *build_file)\n{\n\tif (AssertYML(build_file) == 1) {\n\t\tconf = fopen(build_file, \"r\");\n\t\tif (conf == NULL) {\n\t\t\tprintf(\"Error: No file named %s\\n\", build_file);\n\t\t\treturn -2;\n\t\t}\n\t\tParseConfig();\n\t\tReadValues();\n\t\tCloseConfig();\n\t\treturn 1;\n\t} else {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint Parser::ParseConfig()\n{\n\tif (conf != NULL) {\n\t\tyaml_parser_initialize(&parser);\n\t\tyaml_parser_set_input_file(&parser, conf);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint Parser::CloseConfig()\n{\n\tif ((&parser != NULL) && (conf != NULL)) {\n\t\tyaml_parser_delete(&parser);\n\t\tfclose(conf);\n\t\treturn 1;\n\t} else {\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint Parser::AssertYML(const char *build_file)\n{\n\tconst char *ext;\n\text = strrchr(build_file, '.');\n\tif (opendir(build_file) != NULL) {\n\t\tprintf(\"Error: %s is a directory\\n\", build_file);\n\t\treturn -3;\n\t}\n\tif (!ext) {\n\t\tprintf(\"Error: %s has no extension\\n\", build_file);\n\t\treturn -1;\n\t}\n\tif ((strcmp(ext + 1, \"yml\") == 0) || (strcmp(ext + 1, \"yaml\") == 0) || (strcmp(ext + 1, \"ybf\") == 0)) {\n\t\treturn 1;\n\t} else {\n\t\tprintf(\"Error: %s is not a valid build file\\n\", build_file);\n\t\treturn -2;\n\t}\n\treturn 0;\n}\n\nint Parser::ReadValues()\n{\n\tdo {\n\t\tyaml_parser_scan(&parser, &token);\n\t\tswitch (token.type) {\n\t\tcase YAML_VERSION_DIRECTIVE_TOKEN:\n\t\t\tbreak;\n\t\tcase YAML_NO_TOKEN:\n\t\t\tprintf(\"No token\\n\");\n\t\t\tbreak;\n\t\tcase YAML_STREAM_START_TOKEN:\n\t\t\tprintf(\"Stream start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_STREAM_END_TOKEN:\n\t\t\tprintf(\"Stream end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_KEY_TOKEN:\n\t\t\tprintf(\"\\tKey token: \");\n\t\t\tbreak;\n\t\tcase YAML_VALUE_TOKEN:\n\t\t\tprintf(\"\\t\\tValue token: \");\n\t\t\tbreak;\n\t\tcase YAML_TAG_DIRECTIVE_TOKEN:\n\t\t\tprintf(\"Tag directive: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_DOCUMENT_START_TOKEN:\n\t\t\tprintf(\"Document start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_DOCUMENT_END_TOKEN:\n\t\t\tprintf(\"Document end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_SEQUENCE_START_TOKEN:\n\t\t\tprintf(\"Block sequence start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_END_TOKEN:\n\t\t\tprintf(\"Block sequence end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_MAPPING_START_TOKEN:\n\t\t\tprintf(\"Block Mapping start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_SEQUENCE_START_TOKEN:\n\t\t\tprintf(\"Sequence start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_SEQUENCE_END_TOKEN:\n\t\t\tprintf(\"Sequence end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_MAPPING_START_TOKEN:\n\t\t\tprintf(\"Mapping start\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_MAPPING_END_TOKEN:\n\t\t\tprintf(\"Mapping end\\n\");\n\t\t\tbreak;\n\t\tcase YAML_BLOCK_ENTRY_TOKEN:\n\t\t\tprintf(\"Block entry\\n\");\n\t\t\tbreak;\n\t\tcase YAML_FLOW_ENTRY_TOKEN:\n\t\t\tprintf(\"Block entry token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_ALIAS_TOKEN:\n\t\t\tprintf(\"Alias token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_ANCHOR_TOKEN:\n\t\t\tprintf(\"Anchor token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_TAG_TOKEN:\n\t\t\tprintf(\"Tag token: %s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\tcase YAML_SCALAR_TOKEN:\n\t\t\tprintf(\"%s\\n\", token.data.scalar.value);\n\t\t\tbreak;\n\t\t}\n\t} while (token.type != YAML_STREAM_END_TOKEN);\n\tyaml_token_delete(&token);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/============================================================================\n\/\/ Name : pel.cpp\n\/\/ Author : Joe Selman\n\/\/ Version :\n\n\/\/============================================================================\n\n#include \"PELConfig.h\"\n\n#include \n#include \nnamespace po = boost::program_options;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"pelmap.h\"\n#include \"logic\/el_syntax.h\"\n#include \"logic\/folparser.h\"\n#include \"logic\/domain.h\"\n#include \"log.h\"\n#include \"logic\/moves.h\"\n#include \"logic\/maxwalksat.h\"\n#include \"logic\/unit_prop.h\"\n\n\n\/\/ TODO: pelmap is the exe name? probably should rename this.\n\nint main(int argc, char* argv[]) {\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t (\"help\", \"produce help message\")\n\t (\"version,v\", \"print version and exit\")\n\t (\"max\", po::value(), \"maximum value an interval endpoint can take\")\n\t (\"min\", po::value(), \"minimum value an interval endpoint can take\")\n\t (\"evalModel,e\", \"simply print the model weight of the facts file\")\n\t (\"prob,p\", po::value()->default_value(0.25), \"probability of taking a random move\")\n\t (\"iterations,i\", po::value()->default_value(1000), \"number of iterations before returning a model\")\n\t (\"output,o\", po::value(), \"output model file\")\n\t (\"unitProp,u\", \"perform unit propagation only and exit\")\n\t;\n\n\tpo::options_description hidden(\"Hidden options\");\n\thidden.add_options()\n\t\t(\"facts-file\", po::value(), \"facts file\")\n\t\t(\"formula-file\", po::value(), \"formula file\")\n\t;\n\tpo::positional_options_description p;\n\tp.add(\"facts-file\", 1);\n\tp.add(\"formula-file\", 1);\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(desc).add(hidden);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"version\")) {\n\t\tstd::cout << \"pelmap version \" << PEL_VERSION_MAJOR << \".\" << PEL_VERSION_MINOR << std::endl;\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tif (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n\t std::cout << \"Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n\t\tstd::cout << desc << std::endl;\n\t return EXIT_FAILURE;\n\t}\n\n\t\/\/ setup our logging facilities\n\tFILE* debugFile = fopen(\"debug.log\", \"w\");\n\tif (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n\telse FilePolicy::stream() = debugFile;\n\tFileLog::globalLogLevel() = LOG_DEBUG;\n\n\tLOG(LOG_INFO) << \"Opened log file for new session\";\n\n\t\/\/ make sure we can open the output model file, if specified\n\tFILE* outputFile = NULL;\n\tif (vm.count(\"output\")) {\n\t\toutputFile = fopen(vm[\"output\"].as().c_str(), \"w\");\n\t\tif (!outputFile) {\n\t\t\tstd::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as() << \"\\\" for writing.\" << std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\tboost::shared_ptr d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as(), vm[\"formula-file\"].as());\n\tif (vm.count(\"max\") || vm.count(\"min\")) {\n\t\tInterval maxInt = d->maxInterval();\n\t\tif (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as());\n\t\tif (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as());\n\t\td->setMaxInterval(maxInt);\n\t}\n\n\tModel model = d->defaultModel();\n\n\tLOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\tLOG(LOG_DEBUG) << \"observation predicates: \";\n\tfor(std::map::const_iterator it = d->observedPredicates().begin();\n\t\t\tit != d->observedPredicates().end();\n\t\t\tit++) {\n\t\tLOG(LOG_DEBUG) << \"\\t\" << it->first;\n\t}\n\n\tif (vm.count(\"evalModel\")) {\n\t\tLOG(LOG_INFO) << \"evaluating model...\";\n\t\tunsigned long sum = 0;\n\t\t\/\/ evaluate the weight of each formula in the domain\n\t\tfor(FormulaList::const_iterator it = d->formulas().begin(); it != d->formulas().end(); it++) {\n\t\t\tELSentence formula = *it;\n\t\t\tSISet satisfied = d->satisfied(*(formula.sentence()), model);\n\t\t\tunsigned long weight = d->score(formula, model);\n\t\t\tsum += weight;\n\t\t\tLOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n\t\t}\n\t\tLOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n\t} else if (vm.count(\"unitProp\")) {\n\t doUnitProp(d);\n\t} else {\n\t\tdouble p = vm[\"prob\"].as();\n\t\tunsigned int iterations = vm[\"iterations\"].as();\n\n\t\tLOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n\t\tModel defModel = d->defaultModel();\n\t\tModel maxModel = maxWalkSat(*d, iterations, p, &defModel);\n\t\tLOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n\t\tLOG_PRINT(LOG_INFO) << maxModel.toString();\n\t\tif (vm.count(\"output\")) {\n\t\t\t\/\/ log it to the output file as well\n\t\t\tfprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n\t\t\t\t\tvm[\"facts-file\"].as().c_str(),\n\t\t\t\t\tvm[\"formula-file\"].as().c_str());\n\t\t\tstd::string timeStr;\n\t\t\t{\n\t\t\t\ttime_t rawtime;\n\t\t\t\tstruct tm * timeinfo;\n\t\t\t\ttime (&rawtime);\n\t\t\t\ttimeinfo = localtime (&rawtime);\n\t\t\t\ttimeStr = asctime(timeinfo);\n\t\t\t}\n\t\t\tfprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n\t\t\tfprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n\t\t\t\t\titerations,\n\t\t\t\t\tp);\n\t\t\tfputs(maxModel.toString().c_str(), outputFile);\n\t\t}\n\t}\n\n\t\/\/ Should be good and close files?\n\treturn EXIT_SUCCESS;\n}\n\nnamespace {\nvoid doUnitProp(boost::shared_ptr& d) {\n LOG(LOG_INFO) << \"performing unit propagation...\";\n QCNFClauseList clauses = convertToQCNFClauseList(d->formulas());\n if (!d->assumeClosedWorld()) {\n LOG(LOG_ERROR) << \"doUnitProp(): cannot be called on a domain that is not a closed world - this code needs to be rewritten!\";\n return;\n }\n}\n}\nsome debugging code written for unit prop\/\/============================================================================\n\/\/ Name : pel.cpp\n\/\/ Author : Joe Selman\n\/\/ Version :\n\n\/\/============================================================================\n\n#include \"PELConfig.h\"\n\n#include \n#include \nnamespace po = boost::program_options;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"pelmap.h\"\n#include \"logic\/el_syntax.h\"\n#include \"logic\/folparser.h\"\n#include \"logic\/domain.h\"\n#include \"log.h\"\n#include \"logic\/moves.h\"\n#include \"logic\/maxwalksat.h\"\n#include \"logic\/unit_prop.h\"\n\n\n\/\/ TODO: pelmap is the exe name? probably should rename this.\n\nint main(int argc, char* argv[]) {\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t (\"help\", \"produce help message\")\n\t (\"version,v\", \"print version and exit\")\n\t (\"max\", po::value(), \"maximum value an interval endpoint can take\")\n\t (\"min\", po::value(), \"minimum value an interval endpoint can take\")\n\t (\"evalModel,e\", \"simply print the model weight of the facts file\")\n\t (\"prob,p\", po::value()->default_value(0.25), \"probability of taking a random move\")\n\t (\"iterations,i\", po::value()->default_value(1000), \"number of iterations before returning a model\")\n\t (\"output,o\", po::value(), \"output model file\")\n\t (\"unitProp,u\", \"perform unit propagation only and exit\")\n\t;\n\n\tpo::options_description hidden(\"Hidden options\");\n\thidden.add_options()\n\t\t(\"facts-file\", po::value(), \"facts file\")\n\t\t(\"formula-file\", po::value(), \"formula file\")\n\t;\n\tpo::positional_options_description p;\n\tp.add(\"facts-file\", 1);\n\tp.add(\"formula-file\", 1);\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(desc).add(hidden);\n\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"version\")) {\n\t\tstd::cout << \"pelmap version \" << PEL_VERSION_MAJOR << \".\" << PEL_VERSION_MINOR << std::endl;\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tif (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n\t std::cout << \"Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n\t\tstd::cout << desc << std::endl;\n\t return EXIT_FAILURE;\n\t}\n\n\t\/\/ setup our logging facilities\n\tFILE* debugFile = fopen(\"debug.log\", \"w\");\n\tif (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n\telse FilePolicy::stream() = debugFile;\n\tFileLog::globalLogLevel() = LOG_DEBUG;\n\n\tLOG(LOG_INFO) << \"Opened log file for new session\";\n\n\t\/\/ make sure we can open the output model file, if specified\n\tFILE* outputFile = NULL;\n\tif (vm.count(\"output\")) {\n\t\toutputFile = fopen(vm[\"output\"].as().c_str(), \"w\");\n\t\tif (!outputFile) {\n\t\t\tstd::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as() << \"\\\" for writing.\" << std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\n\tboost::shared_ptr d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as(), vm[\"formula-file\"].as());\n\tif (vm.count(\"max\") || vm.count(\"min\")) {\n\t\tInterval maxInt = d->maxInterval();\n\t\tif (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as());\n\t\tif (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as());\n\t\td->setMaxInterval(maxInt);\n\t}\n\n\tModel model = d->defaultModel();\n\n\tLOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\tLOG(LOG_DEBUG) << \"observation predicates: \";\n\tfor(std::map::const_iterator it = d->observedPredicates().begin();\n\t\t\tit != d->observedPredicates().end();\n\t\t\tit++) {\n\t\tLOG(LOG_DEBUG) << \"\\t\" << it->first;\n\t}\n\n\tif (vm.count(\"evalModel\")) {\n\t\tLOG(LOG_INFO) << \"evaluating model...\";\n\t\tunsigned long sum = 0;\n\t\t\/\/ evaluate the weight of each formula in the domain\n\t\tfor(FormulaList::const_iterator it = d->formulas().begin(); it != d->formulas().end(); it++) {\n\t\t\tELSentence formula = *it;\n\t\t\tSISet satisfied = d->satisfied(*(formula.sentence()), model);\n\t\t\tunsigned long weight = d->score(formula, model);\n\t\t\tsum += weight;\n\t\t\tLOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n\t\t\tLOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n\t\t}\n\t\tLOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n\t} else if (vm.count(\"unitProp\")) {\n\t doUnitProp(d);\n\t} else {\n\t\tdouble p = vm[\"prob\"].as();\n\t\tunsigned int iterations = vm[\"iterations\"].as();\n\n\t\tLOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n\t\tModel defModel = d->defaultModel();\n\t\tModel maxModel = maxWalkSat(*d, iterations, p, &defModel);\n\t\tLOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n\t\tLOG_PRINT(LOG_INFO) << maxModel.toString();\n\t\tif (vm.count(\"output\")) {\n\t\t\t\/\/ log it to the output file as well\n\t\t\tfprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n\t\t\t\t\tvm[\"facts-file\"].as().c_str(),\n\t\t\t\t\tvm[\"formula-file\"].as().c_str());\n\t\t\tstd::string timeStr;\n\t\t\t{\n\t\t\t\ttime_t rawtime;\n\t\t\t\tstruct tm * timeinfo;\n\t\t\t\ttime (&rawtime);\n\t\t\t\ttimeinfo = localtime (&rawtime);\n\t\t\t\ttimeStr = asctime(timeinfo);\n\t\t\t}\n\t\t\tfprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n\t\t\tfprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n\t\t\t\t\titerations,\n\t\t\t\t\tp);\n\t\t\tfputs(maxModel.toString().c_str(), outputFile);\n\t\t}\n\t}\n\n\t\/\/ Should be good and close files?\n\treturn EXIT_SUCCESS;\n}\n\nnamespace {\nvoid doUnitProp(boost::shared_ptr& d) {\n LOG(LOG_INFO) << \"performing unit propagation...\";\n FormulaList formulas = d->formulas();\n\n \/\/ add quantification to any formulas that may be missing them\n for (FormulaList::iterator it = formulas.begin(); it != formulas.end(); it++) {\n if (!it->isQuantified()) {\n SISet everywhere(false, d->maxInterval());\n everywhere.add(d->maxSpanInterval());\n it->setQuantification(everywhere);\n }\n }\n QCNFClauseList clauses = convertToQCNFClauseList(formulas);\n\n if (!d->assumeClosedWorld()) {\n LOG(LOG_ERROR) << \"doUnitProp(): cannot be called on a domain that is not a closed world - this code needs to be rewritten!\";\n return;\n }\n \/\/ convert all the facts into unit clauses\n Model obs = d->defaultModel();\n std::set atoms = obs.atoms();\n\n for (std::set::const_iterator it = atoms.begin(); it != atoms.end(); it++) {\n SISet trueAt = obs.getAtom(*it);\n SISet falseAt = trueAt.compliment();\n\n \/\/ TODO: why make a copy? we should have the original shared_ptr\n boost::shared_ptr atomTrue(new Atom(*it));\n boost::shared_ptr atomFalse(new Negation(atomTrue));\n CNFClause a, b;\n a.push_back(atomTrue);\n b.push_back(atomFalse);\n QCNFClause c, d;\n c.first = a;\n d.first = b;\n c.second = trueAt;\n d.second = falseAt;\n\n if (c.second.size() != 0) clauses.push_back(c);\n if (d.second.size() != 0) clauses.push_back(d);\n }\n\n for (QCNFClauseList::iterator it = clauses.begin(); it != clauses.end(); it++) {\n std::cout << \"clause: \";\n for (CNFClause::iterator it2 = it->first.begin(); it2 != it->first.end(); it2++) {\n if (it2 != it->first.begin()) std::cout << \", \";\n std::cout << (*it2)->toString();\n }\n std::cout << \" @ \" << it->second.toString() << std::endl;\n }\n\n QUnitsFormulasPair reducedList = performUnitPropagation(clauses);\n std::cout << \"unit prop performed, now we have:\" << std::endl;\n}\n}\n<|endoftext|>"} {"text":"#include \"worker.h\"\r\n#include \r\n#include \r\n\r\nWorker::Worker(QObject *parent) : QObject(parent){\r\n giFileSize = 0;\r\n}\r\n\r\nvoid Worker::worker_slot_loadFile(QFile *file)\r\n{\r\n \/\/qDebug() << \"Begin worker_slot_loadFile, file: \" << file->fileName();\r\n\r\n QString line = \"\";\r\n QString text = \"\";\r\n QTextStream in(file);\r\n while (!in.atEnd()) {\r\n line = in.readLine();\r\n text.append(line + \"\\n\");\r\n }\r\n in.flush();\r\n file->close();\r\n text.remove(text.lastIndexOf(\"\\n\"),1);\r\n emit worker_signal_appendText(text);\r\n\r\n \/\/qDebug() << \"End worker_slot_loadFile\";\r\n}\r\n\r\nvoid Worker::worker_slot_tailFile(QFile *file)\r\n{\r\n if(file->size() > giFileSize) {\r\n int liDiff = file->size() - giFileSize;\r\n if(file->open(QIODevice::ReadOnly | QIODevice::Text)) {\r\n if(file->seek(giFileSize)) {\r\n QString lsText = QString(file->read(liDiff));\r\n emit worker_signal_insertText(lsText);\r\n giFileSize = file->size();\r\n }\r\n file->close();\r\n }\r\n } else {\r\n giFileSize = file->size();\r\n }\r\n}\r\n\r\nvoid Worker::worker_slot_setCurrentFileSize(int aiFileSize)\r\n{\r\n this->giFileSize = aiFileSize;\r\n}\r\n\r\nDeleted comments#include \"worker.h\"\r\n#include \r\n#include \r\n\r\nWorker::Worker(QObject *parent) : QObject(parent){\r\n giFileSize = 0;\r\n}\r\n\r\nvoid Worker::worker_slot_loadFile(QFile *file)\r\n{\r\n QString line = \"\";\r\n QString text = \"\";\r\n QTextStream in(file);\r\n while (!in.atEnd()) {\r\n line = in.readLine();\r\n text.append(line + \"\\n\");\r\n }\r\n in.flush();\r\n file->close();\r\n text.remove(text.lastIndexOf(\"\\n\"),1);\r\n emit worker_signal_appendText(text);\r\n}\r\n\r\nvoid Worker::worker_slot_tailFile(QFile *file)\r\n{\r\n if(file->size() > giFileSize) {\r\n int liDiff = file->size() - giFileSize;\r\n if(file->open(QIODevice::ReadOnly | QIODevice::Text)) {\r\n if(file->seek(giFileSize)) {\r\n QString lsText = QString(file->read(liDiff));\r\n emit worker_signal_insertText(lsText);\r\n giFileSize = file->size();\r\n }\r\n file->close();\r\n }\r\n } else {\r\n giFileSize = file->size();\r\n }\r\n}\r\n\r\nvoid Worker::worker_slot_setCurrentFileSize(int aiFileSize)\r\n{\r\n this->giFileSize = aiFileSize;\r\n}\r\n\r\n<|endoftext|>"} {"text":"#include \"perfmon.hpp\"\n#include \"arch\/arch.hpp\"\n#include \"utils.hpp\"\n#include \n\n\/* The var list keeps track of all of the perfmon_t objects. *\/\n\nintrusive_list_t &get_var_list() {\n \n \/* Getter function so that we can be sure that var_list is initialized before it is needed,\n as advised by the C++ FAQ. Otherwise, a perfmon_t might be initialized before the var list\n was initialized. *\/\n \n static intrusive_list_t var_list;\n return var_list;\n}\n\n\/* Class that wraps a pthread spinlock.\n\nTODO: This should live in the arch\/ directory. *\/\n\nclass spinlock_t {\n pthread_spinlock_t l;\npublic:\n spinlock_t() {\n pthread_spin_init(&l, PTHREAD_PROCESS_PRIVATE);\n }\n ~spinlock_t() {\n pthread_spin_destroy(&l);\n }\n void lock() {\n int res = pthread_spin_lock(&l);\n guarantee_err(res == 0, \"could not lock spin lock\");\n }\n void unlock() {\n int res = pthread_spin_unlock(&l);\n guarantee_err(res == 0, \"could not unlock spin lock\");\n }\n};\n\nspinlock_t &get_var_lock() {\n \n \/* To avoid static initialization fiasco *\/\n \n static spinlock_t lock;\n return lock;\n}\n\n\/* This is the function that actually gathers the stats. It is illegal to create or destroy\nperfmon_t objects while a perfmon_fsm_t is active. *\/\n\nstruct perfmon_fsm_t :\n public home_cpu_mixin_t\n{\n perfmon_callback_t *cb;\n perfmon_stats_t *dest;\n std::vector data;\n int messages_out;\n explicit perfmon_fsm_t(perfmon_stats_t *dest) : cb(NULL), dest(dest) {\n data.reserve(get_var_list().size());\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n data.push_back(p->begin_stats());\n }\n messages_out = get_num_cpus();\n for (int i = 0; i < get_num_cpus(); i++) {\n do_on_cpu(i, this, &perfmon_fsm_t::visit);\n }\n }\n bool visit() {\n int i = 0;\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n p->visit_stats(data[i++]);\n }\n do_on_cpu(home_cpu, this, &perfmon_fsm_t::have_visited);\n return true;\n }\n bool have_visited() {\n messages_out--;\n if (messages_out == 0) {\n int i = 0;\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n p->end_stats(data[i++], dest);\n }\n if (cb) {\n cb->on_perfmon_stats();\n delete this;\n } else {\n \/* Don't delete ourself; perfmon_get_stats() will delete us *\/\n }\n }\n return true;\n }\n};\n\nbool perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {\n \n perfmon_fsm_t *fsm = new perfmon_fsm_t(dest);\n if (fsm->messages_out == 0) {\n \/* It has already finished *\/\n delete fsm;\n return true;\n } else {\n \/* It has not finished yet *\/\n fsm->cb = cb;\n return false;\n }\n}\n\n\/* Constructor and destructor register and deregister the perfmon.\n\nRight now, it is illegal to make perfmon_t objects that are not static variables, so\nwe don't have to worry about locking the var list. If we locked it, then we could\ncreate and destroy perfmon_ts at runtime. *\/\n\nperfmon_t::perfmon_t()\n{\n get_var_lock().lock();\n get_var_list().push_back(this);\n get_var_lock().unlock();\n}\n\nperfmon_t::~perfmon_t() {\n \n get_var_lock().lock();\n get_var_list().remove(this);\n get_var_lock().unlock();\n}\n\n\/* perfmon_counter_t *\/\n\nperfmon_counter_t::perfmon_counter_t(std::string name)\n : name(name)\n{\n for (int i = 0; i < MAX_CPUS; i++) values[i] = 0;\n}\n\nint64_t &perfmon_counter_t::get() {\n return values[get_cpu_id()];\n}\n\nvoid *perfmon_counter_t::begin_stats() {\n return new int64_t[get_num_cpus()];\n}\n\nvoid perfmon_counter_t::visit_stats(void *data) {\n ((int64_t *)data)[get_cpu_id()] = get();\n}\n\nvoid perfmon_counter_t::end_stats(void *data, perfmon_stats_t *dest) {\n int64_t value = 0;\n for (int i = 0; i < get_num_cpus(); i++) value += ((int64_t *)data)[i];\n (*dest)[name] = format(value);\n delete[] (int64_t *)data;\n}\n\n\/* perfmon_sampler_t *\/\n\nperfmon_sampler_t::perfmon_sampler_t(std::string name, ticks_t length, bool include_rate)\n : name(name), length(length), include_rate(include_rate) { }\n\nvoid perfmon_sampler_t::expire() {\n ticks_t now = get_ticks();\n std::deque &queue = values[get_cpu_id()];\n while (!queue.empty() && queue.front().timestamp + length < now) queue.pop_front();\n}\n\nvoid perfmon_sampler_t::record(value_t v) {\n expire();\n values[get_cpu_id()].push_back(sample_t(v, get_ticks()));\n}\n\nstruct perfmon_sampler_step_t {\n uint64_t counts[MAX_CPUS];\n perfmon_sampler_t::value_t values[MAX_CPUS], mins[MAX_CPUS], maxes[MAX_CPUS];\n};\n\nvoid *perfmon_sampler_t::begin_stats() {\n return new perfmon_sampler_step_t;\n}\n\nvoid perfmon_sampler_t::visit_stats(void *data) {\n perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;\n expire();\n d->values[get_cpu_id()] = 0;\n d->counts[get_cpu_id()] = 0;\n for (std::deque::iterator it = values[get_cpu_id()].begin();\n it != values[get_cpu_id()].end(); it++) {\n d->values[get_cpu_id()] += (*it).value;\n if (d->counts[get_cpu_id()] > 0) {\n d->mins[get_cpu_id()] = std::min(d->mins[get_cpu_id()], (*it).value);\n d->maxes[get_cpu_id()] = std::max(d->maxes[get_cpu_id()], (*it).value);\n } else {\n d->mins[get_cpu_id()] = (*it).value;\n d->maxes[get_cpu_id()] = (*it).value;\n }\n d->counts[get_cpu_id()]++;\n }\n}\n\nvoid perfmon_sampler_t::end_stats(void *data, perfmon_stats_t *dest) {\n perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;\n perfmon_sampler_t::value_t value = 0;\n uint64_t count = 0;\n perfmon_sampler_t::value_t min = 0, max = 0; \/* Initializers to make GCC shut up *\/\n bool have_any = false;\n for (int i = 0; i < get_num_cpus(); i++) {\n value += d->values[i];\n count += d->counts[i];\n if (d->counts[i]) {\n if (have_any) {\n min = std::min(d->mins[i], min);\n max = std::max(d->maxes[i], max);\n } else {\n min = d->mins[i];\n max = d->maxes[i];\n have_any = true;\n }\n }\n }\n if (have_any) {\n (*dest)[name + \"_avg\"] = format(value \/ count);\n (*dest)[name + \"_min\"] = format(min);\n (*dest)[name + \"_max\"] = format(max);\n } else {\n (*dest)[name + \"_avg\"] = \"-\";\n (*dest)[name + \"_min\"] = \"-\";\n (*dest)[name + \"_max\"] = \"-\";\n }\n if (include_rate) {\n (*dest)[name + \"_persec\"] = format(count \/ ticks_to_secs(length));\n }\n delete d;\n};\n\nAdded a comment.#include \"perfmon.hpp\"\n#include \"arch\/arch.hpp\"\n#include \"utils.hpp\"\n#include \n\n\/* The var list keeps track of all of the perfmon_t objects. *\/\n\nintrusive_list_t &get_var_list() {\n \n \/* Getter function so that we can be sure that var_list is initialized before it is needed,\n as advised by the C++ FAQ. Otherwise, a perfmon_t might be initialized before the var list\n was initialized. *\/\n \n static intrusive_list_t var_list;\n return var_list;\n}\n\n\/* Class that wraps a pthread spinlock.\n\nTODO: This should live in the arch\/ directory. *\/\n\nclass spinlock_t {\n pthread_spinlock_t l;\npublic:\n spinlock_t() {\n pthread_spin_init(&l, PTHREAD_PROCESS_PRIVATE);\n }\n ~spinlock_t() {\n pthread_spin_destroy(&l);\n }\n void lock() {\n int res = pthread_spin_lock(&l);\n guarantee_err(res == 0, \"could not lock spin lock\");\n }\n void unlock() {\n int res = pthread_spin_unlock(&l);\n guarantee_err(res == 0, \"could not unlock spin lock\");\n }\n};\n\n\/* The var lock protects the var list when it is being modified. In theory, this should all work\nautomagically because the constructor of every perfmon_t calls get_var_lock(), causing the var lock\nto be constructed before the first perfmon, so it is destroyed after the last perfmon. *\/\n\nspinlock_t &get_var_lock() {\n \n \/* To avoid static initialization fiasco *\/\n \n static spinlock_t lock;\n return lock;\n}\n\n\/* This is the function that actually gathers the stats. It is illegal to create or destroy\nperfmon_t objects while a perfmon_fsm_t is active. *\/\n\nstruct perfmon_fsm_t :\n public home_cpu_mixin_t\n{\n perfmon_callback_t *cb;\n perfmon_stats_t *dest;\n std::vector data;\n int messages_out;\n explicit perfmon_fsm_t(perfmon_stats_t *dest) : cb(NULL), dest(dest) {\n data.reserve(get_var_list().size());\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n data.push_back(p->begin_stats());\n }\n messages_out = get_num_cpus();\n for (int i = 0; i < get_num_cpus(); i++) {\n do_on_cpu(i, this, &perfmon_fsm_t::visit);\n }\n }\n bool visit() {\n int i = 0;\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n p->visit_stats(data[i++]);\n }\n do_on_cpu(home_cpu, this, &perfmon_fsm_t::have_visited);\n return true;\n }\n bool have_visited() {\n messages_out--;\n if (messages_out == 0) {\n int i = 0;\n for (perfmon_t *p = get_var_list().head(); p; p = get_var_list().next(p)) {\n p->end_stats(data[i++], dest);\n }\n if (cb) {\n cb->on_perfmon_stats();\n delete this;\n } else {\n \/* Don't delete ourself; perfmon_get_stats() will delete us *\/\n }\n }\n return true;\n }\n};\n\nbool perfmon_get_stats(perfmon_stats_t *dest, perfmon_callback_t *cb) {\n \n perfmon_fsm_t *fsm = new perfmon_fsm_t(dest);\n if (fsm->messages_out == 0) {\n \/* It has already finished *\/\n delete fsm;\n return true;\n } else {\n \/* It has not finished yet *\/\n fsm->cb = cb;\n return false;\n }\n}\n\n\/* Constructor and destructor register and deregister the perfmon.\n\nRight now, it is illegal to make perfmon_t objects that are not static variables, so\nwe don't have to worry about locking the var list. If we locked it, then we could\ncreate and destroy perfmon_ts at runtime. *\/\n\nperfmon_t::perfmon_t()\n{\n get_var_lock().lock();\n get_var_list().push_back(this);\n get_var_lock().unlock();\n}\n\nperfmon_t::~perfmon_t() {\n \n get_var_lock().lock();\n get_var_list().remove(this);\n get_var_lock().unlock();\n}\n\n\/* perfmon_counter_t *\/\n\nperfmon_counter_t::perfmon_counter_t(std::string name)\n : name(name)\n{\n for (int i = 0; i < MAX_CPUS; i++) values[i] = 0;\n}\n\nint64_t &perfmon_counter_t::get() {\n return values[get_cpu_id()];\n}\n\nvoid *perfmon_counter_t::begin_stats() {\n return new int64_t[get_num_cpus()];\n}\n\nvoid perfmon_counter_t::visit_stats(void *data) {\n ((int64_t *)data)[get_cpu_id()] = get();\n}\n\nvoid perfmon_counter_t::end_stats(void *data, perfmon_stats_t *dest) {\n int64_t value = 0;\n for (int i = 0; i < get_num_cpus(); i++) value += ((int64_t *)data)[i];\n (*dest)[name] = format(value);\n delete[] (int64_t *)data;\n}\n\n\/* perfmon_sampler_t *\/\n\nperfmon_sampler_t::perfmon_sampler_t(std::string name, ticks_t length, bool include_rate)\n : name(name), length(length), include_rate(include_rate) { }\n\nvoid perfmon_sampler_t::expire() {\n ticks_t now = get_ticks();\n std::deque &queue = values[get_cpu_id()];\n while (!queue.empty() && queue.front().timestamp + length < now) queue.pop_front();\n}\n\nvoid perfmon_sampler_t::record(value_t v) {\n expire();\n values[get_cpu_id()].push_back(sample_t(v, get_ticks()));\n}\n\nstruct perfmon_sampler_step_t {\n uint64_t counts[MAX_CPUS];\n perfmon_sampler_t::value_t values[MAX_CPUS], mins[MAX_CPUS], maxes[MAX_CPUS];\n};\n\nvoid *perfmon_sampler_t::begin_stats() {\n return new perfmon_sampler_step_t;\n}\n\nvoid perfmon_sampler_t::visit_stats(void *data) {\n perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;\n expire();\n d->values[get_cpu_id()] = 0;\n d->counts[get_cpu_id()] = 0;\n for (std::deque::iterator it = values[get_cpu_id()].begin();\n it != values[get_cpu_id()].end(); it++) {\n d->values[get_cpu_id()] += (*it).value;\n if (d->counts[get_cpu_id()] > 0) {\n d->mins[get_cpu_id()] = std::min(d->mins[get_cpu_id()], (*it).value);\n d->maxes[get_cpu_id()] = std::max(d->maxes[get_cpu_id()], (*it).value);\n } else {\n d->mins[get_cpu_id()] = (*it).value;\n d->maxes[get_cpu_id()] = (*it).value;\n }\n d->counts[get_cpu_id()]++;\n }\n}\n\nvoid perfmon_sampler_t::end_stats(void *data, perfmon_stats_t *dest) {\n perfmon_sampler_step_t *d = (perfmon_sampler_step_t *)data;\n perfmon_sampler_t::value_t value = 0;\n uint64_t count = 0;\n perfmon_sampler_t::value_t min = 0, max = 0; \/* Initializers to make GCC shut up *\/\n bool have_any = false;\n for (int i = 0; i < get_num_cpus(); i++) {\n value += d->values[i];\n count += d->counts[i];\n if (d->counts[i]) {\n if (have_any) {\n min = std::min(d->mins[i], min);\n max = std::max(d->maxes[i], max);\n } else {\n min = d->mins[i];\n max = d->maxes[i];\n have_any = true;\n }\n }\n }\n if (have_any) {\n (*dest)[name + \"_avg\"] = format(value \/ count);\n (*dest)[name + \"_min\"] = format(min);\n (*dest)[name + \"_max\"] = format(max);\n } else {\n (*dest)[name + \"_avg\"] = \"-\";\n (*dest)[name + \"_min\"] = \"-\";\n (*dest)[name + \"_max\"] = \"-\";\n }\n if (include_rate) {\n (*dest)[name + \"_persec\"] = format(count \/ ticks_to_secs(length));\n }\n delete d;\n};\n\n<|endoftext|>"} {"text":"\/*\n * Main authors:\n * Jason Nguyen \n * Guido Tack \n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \n#include \"process.h\"\n#include \"ide.h\"\n#include \"mainwindow.h\"\n#include \"exception.h\"\n\n#ifndef Q_OS_WIN\n#include \n#include \n#include \n#include \n#endif\n\n#ifdef Q_OS_WIN\n#define pathSep \";\"\n#else\n#define pathSep \":\"\n#endif\n\nvoid Process::start(const QString &program, const QStringList &arguments, const QString &path)\n{\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n QString curPath = env.value(\"PATH\");\n QString addPath = IDE::instance()->appDir();\n if (!path.isEmpty())\n addPath = path + pathSep + addPath;\n env.insert(\"PATH\", addPath + pathSep + curPath);\n setProcessEnvironment(env);\n#ifdef Q_OS_WIN\n _putenv_s(\"PATH\", (addPath + pathSep + curPath).toStdString().c_str());\n jobObject = CreateJobObject(nullptr, nullptr);\n connect(this, SIGNAL(started()), this, SLOT(attachJob()));\n#else\n setenv(\"PATH\", (addPath + pathSep + curPath).toStdString().c_str(), 1);\n#endif\n QProcess::start(program,arguments, QIODevice::Unbuffered | QIODevice::ReadWrite);\n#ifdef Q_OS_WIN\n _putenv_s(\"PATH\", curPath.toStdString().c_str());\n#else\n setenv(\"PATH\", curPath.toStdString().c_str(), 1);\n#endif\n}\n\nvoid Process::terminate()\n{\n#ifdef Q_OS_WIN\n QString pipe;\n QTextStream ts(&pipe);\n ts << \"\\\\\\\\.\\\\pipe\\\\minizinc-\" << processId();\n auto pipeName = pipe.toStdString();\n HANDLE hNamedPipe = CreateFileA(pipeName.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (hNamedPipe) {\n WriteFile(hNamedPipe, nullptr, 0, nullptr, nullptr);\n CloseHandle(hNamedPipe);\n }\n#else\n ::killpg(processId(), SIGINT);\n#endif\n if (!waitForFinished(500)) {\n if (state() != QProcess::NotRunning) {\n#ifdef Q_OS_WIN\n TerminateJobObject(jobObject, EXIT_FAILURE);\n#else\n ::killpg(processId(), SIGKILL);\n#endif\n if (!waitForFinished(500)) {\n kill();\n waitForFinished();\n }\n }\n }\n}\n\nvoid Process::setupChildProcess()\n{\n#ifndef Q_OS_WIN\n if (::setpgid(0,0)) {\n std::cerr << \"Error: Failed to create sub-process\\n\";\n }\n#endif\n}\n\n#ifdef Q_OS_WIN\nvoid Process::attachJob()\n{\n AssignProcessToJobObject(jobObject, pid()->hProcess);\n}\n#endif\n\nvoid MznDriver::setLocation(const QString &mznDistribPath)\n{\n clear();\n\n _minizincExecutable = \"minizinc\";\n _mznDistribPath = mznDistribPath;\n\n MznProcess p;\n p.run({\"--version\"});\n if (!p.waitForStarted() || !p.waitForFinished()) {\n clear();\n throw ProcessError(\"Failed to find or launch MiniZinc executable.\");\n }\n\n _versionString = p.readAllStandardOutput() + p.readAllStandardError();\n QRegularExpression version_regexp(\"version (\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\");\n QRegularExpressionMatch path_match = version_regexp.match(_versionString);\n if (path_match.hasMatch()) {\n _version = QVersionNumber(\n path_match.captured(1).toInt(),\n path_match.captured(2).toInt(),\n path_match.captured(3).toInt()\n );\n } else {\n QString message = _versionString;\n clear();\n throw DriverError(message);\n }\n\n auto minVersion = QVersionNumber(2, 5, 0);\n if (_version < minVersion) {\n clear();\n throw DriverError(\"Versions of MiniZinc before \" + minVersion.toString() + \" are not supported.\");\n }\n\n p.run({\"--config-dirs\"});\n if (p.waitForStarted() && p.waitForFinished()) {\n QString allOutput = p.readAllStandardOutput();\n QJsonDocument jd = QJsonDocument::fromJson(allOutput.toUtf8());\n if (!jd.isNull()) {\n QJsonObject sj = jd.object();\n _userSolverConfigDir = sj[\"userSolverConfigDir\"].toString();\n _userConfigFile = sj[\"userConfigFile\"].toString();\n _mznStdlibDir = sj[\"mznStdlibDir\"].toString();\n }\n }\n p.run({\"--solvers-json\"});\n if (p.waitForStarted() && p.waitForFinished()) {\n QString allOutput = p.readAllStandardOutput();\n QJsonDocument jd = QJsonDocument::fromJson(allOutput.toUtf8());\n if (!jd.isNull()) {\n _solvers.clear();\n QJsonArray allSolvers = jd.array();\n for (auto item : allSolvers) {\n QJsonObject sj = item.toObject();\n Solver s(sj);\n _solvers.append(s);\n }\n }\n }\n}\n\nSolver* MznDriver::defaultSolver(void)\n{\n for (auto& solver : solvers()) {\n if (solver.isDefaultSolver) {\n return &solver;\n }\n }\n return nullptr;\n}\n\nvoid MznDriver::setDefaultSolver(const Solver& s)\n{\n for (auto& solver : solvers()) {\n solver.isDefaultSolver = &solver == &s;\n }\n\n QFile uc(userConfigFile());\n QJsonObject jo;\n if (uc.exists()) {\n if (uc.open(QFile::ReadOnly)) {\n QJsonDocument doc = QJsonDocument::fromJson(uc.readAll());\n if (doc.isNull()) {\n throw DriverError(\"Cannot modify user configuration file \" + userConfigFile());\n }\n jo = doc.object();\n uc.close();\n }\n }\n QJsonArray tagdefs = jo.contains(\"tagDefaults\") ? jo[\"tagDefaults\"].toArray() : QJsonArray();\n bool hadDefault = false;\n for (int i=0; i::of(&MznProcess::finished), [=](int, QProcess::ExitStatus) {\n onExited();\n });\n connect(this, &MznProcess::errorOccurred, [=](QProcess::ProcessError) {\n onExited();\n });\n}\n\nvoid MznProcess::run(const QStringList& args, const QString& cwd)\n{\n Q_ASSERT(state() == NotRunning);\n setWorkingDirectory(cwd);\n Process::start(MznDriver::get().minizincExecutable(), args, MznDriver::get().mznDistribPath());\n}\n\nvoid MznProcess::run(const SolverConfiguration& sc, const QStringList& args, const QString& cwd)\n{\n temp = new QTemporaryFile(QDir::tempPath() + \"\/mzn_XXXXXX.json\");\n if (!temp->open()) {\n emit errorOccurred(QProcess::FailedToStart);\n return;\n }\n QString paramFile = temp->fileName();\n temp->write(sc.toJSON());\n temp->close();\n QStringList newArgs;\n newArgs << \"--param-file\" << paramFile << args;\n setWorkingDirectory(cwd);\n Process::start(MznDriver::get().minizincExecutable(), newArgs, MznDriver::get().mznDistribPath());\n}\n\nqint64 MznProcess::timeElapsed()\n{\n if (elapsedTimer.isValid()) {\n return elapsedTimer.elapsed();\n }\n return finalTime;\n}\n\nvoid MznProcess::onExited()\n{\n finalTime = elapsedTimer.elapsed();\n elapsedTimer.invalidate();\n delete temp;\n temp = nullptr;\n}\n\nSolveProcess::SolveProcess(QObject* parent) :\n MznProcess(parent)\n{\n connect(this, &SolveProcess::readyReadStandardOutput, this, &SolveProcess::onStdout);\n connect(this, &SolveProcess::readyReadStandardError, this, &SolveProcess::onStderr);\n connect(this, QOverload::of(&SolveProcess::finished), this, &SolveProcess::onFinished);\n}\n\nvoid SolveProcess::solve(const SolverConfiguration& sc, const QString& modelFile, const QStringList& dataFiles, const QStringList& extraArgs)\n{\n state = State::Output;\n outputBuffer.clear();\n htmlBuffer.clear();\n jsonBuffer.clear();\n\n QFileInfo fi(modelFile);\n QStringList args;\n args << extraArgs << modelFile << dataFiles;\n MznProcess::run(sc, args, fi.canonicalPath());\n}\n\nvoid SolveProcess::onStdout()\n{\n setReadChannel(QProcess::ProcessChannel::StandardOutput);\n\n while (canReadLine()) {\n auto line = QString::fromUtf8(readLine());\n processStdout(line);\n }\n}\n\nvoid SolveProcess::onStderr()\n{\n setReadChannel(QProcess::ProcessChannel::StandardError);\n\n while (canReadLine()) {\n auto line = QString::fromUtf8(readLine());\n processStderr(line);\n }\n}\n\nvoid SolveProcess::processStdout(QString line)\n{\n auto trimmed = line.trimmed();\n QRegExp jsonPattern(\"^(?:%%%(top|bottom))?%%%mzn-json(-init)?:(.*)\");\n\n \/\/ Can appear in any state\n if (trimmed.startsWith(\"%%%mzn-stat\")) {\n emit statisticOutput(line);\n return;\n } else if (trimmed.startsWith(\"%%%mzn-progress\")) {\n auto split = trimmed.split(\" \");\n bool ok = split.length() == 2;\n if (ok) {\n auto progress = split[1].toFloat(&ok);\n if (ok) {\n emit progressOutput(progress);\n return;\n }\n }\n }\n\n switch (state) {\n case State::Output: \/\/ Normal solution output\n if (trimmed == \"----------\") {\n outputBuffer << line;\n emit solutionOutput(outputBuffer.join(\"\"));\n if (!visBuffer.isEmpty()) {\n emit jsonOutput(false, visBuffer);\n visBuffer.clear();\n }\n outputBuffer.clear();\n } else if (trimmed == \"==========\" || trimmed == \"=====UNKNOWN=====\" || trimmed == \"=====ERROR=====\") {\n outputBuffer << line;\n emit finalStatus(outputBuffer.join(\"\"));\n outputBuffer.clear();\n } else if (jsonPattern.exactMatch(trimmed)) {\n auto captures = jsonPattern.capturedTexts();\n state = captures[2] == \"-init\" ? State::JSONInit : State::JSON;\n QString area = captures[1].isEmpty() ? \"top\" : captures[1];\n auto jsonArea = area == \"bottom\" ? Qt::BottomDockWidgetArea : Qt::TopDockWidgetArea;\n auto jsonPath = captures[3];\n visBuffer << VisOutput(VisWindowSpec(jsonPath, jsonArea));\n } else if (trimmed == \"%%%mzn-html-start\") {\n state = State::HTML;\n } else {\n outputBuffer << line;\n }\n break;\n case State::HTML: \/\/ Seen %%%mzn-html-start\n if (trimmed.startsWith(\"%%%mzn-html-end\")) {\n emit htmlOutput(htmlBuffer.join(\"\"));\n state = State::Output;\n htmlBuffer.clear();\n } else {\n htmlBuffer << line;\n }\n break;\n case State::JSONInit: \/\/ Seen %%%mzn-json-init\n if (trimmed == \"%%%mzn-json-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n state = State::Output;\n jsonBuffer.clear();\n } else if (trimmed == \"%%%mzn-json-init-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n emit jsonOutput(true, visBuffer);\n state = State::Output;\n jsonBuffer.clear();\n visBuffer.clear();\n } else {\n jsonBuffer << trimmed;\n }\n break;\n case State::JSON: \/\/ Seen %%%mzn-json\n if (trimmed == \"%%%mzn-json-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n state = State::Output;\n jsonBuffer.clear();\n } else if (trimmed == \"%%%mzn-json-time\") {\n \/\/ Wrap current buffer in array with elapsed time\n jsonBuffer.prepend(\"[\");\n jsonBuffer << \",\" << QString().number(timeElapsed()) << \"]\";\n } else {\n jsonBuffer << trimmed;\n }\n break;\n }\n}\n\nvoid SolveProcess::processStderr(QString line)\n{\n auto trimmed = line.trimmed();\n emit stdErrorOutput(line);\n}\n\nvoid SolveProcess::onFinished(int exitCode, QProcess::ExitStatus status)\n{\n \/\/ Finish processing remaining stdout\n onStdout();\n if (!atEnd()) {\n processStdout(readAll());\n }\n if (!outputBuffer.isEmpty()) {\n emit fragment(outputBuffer.join(\"\"));\n outputBuffer.clear();\n }\n \/\/ Finish processing remaining stderr\n onStderr();\n if (!atEnd()) {\n processStderr(readAll());\n }\n\n emit complete(exitCode, status);\n}\nEnsure stderr fragments appear when a newline is in stdout\/*\n * Main authors:\n * Jason Nguyen \n * Guido Tack \n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \n#include \"process.h\"\n#include \"ide.h\"\n#include \"mainwindow.h\"\n#include \"exception.h\"\n\n#ifndef Q_OS_WIN\n#include \n#include \n#include \n#include \n#endif\n\n#ifdef Q_OS_WIN\n#define pathSep \";\"\n#else\n#define pathSep \":\"\n#endif\n\nvoid Process::start(const QString &program, const QStringList &arguments, const QString &path)\n{\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n QString curPath = env.value(\"PATH\");\n QString addPath = IDE::instance()->appDir();\n if (!path.isEmpty())\n addPath = path + pathSep + addPath;\n env.insert(\"PATH\", addPath + pathSep + curPath);\n setProcessEnvironment(env);\n#ifdef Q_OS_WIN\n _putenv_s(\"PATH\", (addPath + pathSep + curPath).toStdString().c_str());\n jobObject = CreateJobObject(nullptr, nullptr);\n connect(this, SIGNAL(started()), this, SLOT(attachJob()));\n#else\n setenv(\"PATH\", (addPath + pathSep + curPath).toStdString().c_str(), 1);\n#endif\n QProcess::start(program,arguments, QIODevice::Unbuffered | QIODevice::ReadWrite);\n#ifdef Q_OS_WIN\n _putenv_s(\"PATH\", curPath.toStdString().c_str());\n#else\n setenv(\"PATH\", curPath.toStdString().c_str(), 1);\n#endif\n}\n\nvoid Process::terminate()\n{\n#ifdef Q_OS_WIN\n QString pipe;\n QTextStream ts(&pipe);\n ts << \"\\\\\\\\.\\\\pipe\\\\minizinc-\" << processId();\n auto pipeName = pipe.toStdString();\n HANDLE hNamedPipe = CreateFileA(pipeName.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (hNamedPipe) {\n WriteFile(hNamedPipe, nullptr, 0, nullptr, nullptr);\n CloseHandle(hNamedPipe);\n }\n#else\n ::killpg(processId(), SIGINT);\n#endif\n if (!waitForFinished(500)) {\n if (state() != QProcess::NotRunning) {\n#ifdef Q_OS_WIN\n TerminateJobObject(jobObject, EXIT_FAILURE);\n#else\n ::killpg(processId(), SIGKILL);\n#endif\n if (!waitForFinished(500)) {\n kill();\n waitForFinished();\n }\n }\n }\n}\n\nvoid Process::setupChildProcess()\n{\n#ifndef Q_OS_WIN\n if (::setpgid(0,0)) {\n std::cerr << \"Error: Failed to create sub-process\\n\";\n }\n#endif\n}\n\n#ifdef Q_OS_WIN\nvoid Process::attachJob()\n{\n AssignProcessToJobObject(jobObject, pid()->hProcess);\n}\n#endif\n\nvoid MznDriver::setLocation(const QString &mznDistribPath)\n{\n clear();\n\n _minizincExecutable = \"minizinc\";\n _mznDistribPath = mznDistribPath;\n\n MznProcess p;\n p.run({\"--version\"});\n if (!p.waitForStarted() || !p.waitForFinished()) {\n clear();\n throw ProcessError(\"Failed to find or launch MiniZinc executable.\");\n }\n\n _versionString = p.readAllStandardOutput() + p.readAllStandardError();\n QRegularExpression version_regexp(\"version (\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\");\n QRegularExpressionMatch path_match = version_regexp.match(_versionString);\n if (path_match.hasMatch()) {\n _version = QVersionNumber(\n path_match.captured(1).toInt(),\n path_match.captured(2).toInt(),\n path_match.captured(3).toInt()\n );\n } else {\n QString message = _versionString;\n clear();\n throw DriverError(message);\n }\n\n auto minVersion = QVersionNumber(2, 5, 0);\n if (_version < minVersion) {\n clear();\n throw DriverError(\"Versions of MiniZinc before \" + minVersion.toString() + \" are not supported.\");\n }\n\n p.run({\"--config-dirs\"});\n if (p.waitForStarted() && p.waitForFinished()) {\n QString allOutput = p.readAllStandardOutput();\n QJsonDocument jd = QJsonDocument::fromJson(allOutput.toUtf8());\n if (!jd.isNull()) {\n QJsonObject sj = jd.object();\n _userSolverConfigDir = sj[\"userSolverConfigDir\"].toString();\n _userConfigFile = sj[\"userConfigFile\"].toString();\n _mznStdlibDir = sj[\"mznStdlibDir\"].toString();\n }\n }\n p.run({\"--solvers-json\"});\n if (p.waitForStarted() && p.waitForFinished()) {\n QString allOutput = p.readAllStandardOutput();\n QJsonDocument jd = QJsonDocument::fromJson(allOutput.toUtf8());\n if (!jd.isNull()) {\n _solvers.clear();\n QJsonArray allSolvers = jd.array();\n for (auto item : allSolvers) {\n QJsonObject sj = item.toObject();\n Solver s(sj);\n _solvers.append(s);\n }\n }\n }\n}\n\nSolver* MznDriver::defaultSolver(void)\n{\n for (auto& solver : solvers()) {\n if (solver.isDefaultSolver) {\n return &solver;\n }\n }\n return nullptr;\n}\n\nvoid MznDriver::setDefaultSolver(const Solver& s)\n{\n for (auto& solver : solvers()) {\n solver.isDefaultSolver = &solver == &s;\n }\n\n QFile uc(userConfigFile());\n QJsonObject jo;\n if (uc.exists()) {\n if (uc.open(QFile::ReadOnly)) {\n QJsonDocument doc = QJsonDocument::fromJson(uc.readAll());\n if (doc.isNull()) {\n throw DriverError(\"Cannot modify user configuration file \" + userConfigFile());\n }\n jo = doc.object();\n uc.close();\n }\n }\n QJsonArray tagdefs = jo.contains(\"tagDefaults\") ? jo[\"tagDefaults\"].toArray() : QJsonArray();\n bool hadDefault = false;\n for (int i=0; i::of(&MznProcess::finished), [=](int, QProcess::ExitStatus) {\n onExited();\n });\n connect(this, &MznProcess::errorOccurred, [=](QProcess::ProcessError) {\n onExited();\n });\n}\n\nvoid MznProcess::run(const QStringList& args, const QString& cwd)\n{\n Q_ASSERT(state() == NotRunning);\n setWorkingDirectory(cwd);\n Process::start(MznDriver::get().minizincExecutable(), args, MznDriver::get().mznDistribPath());\n}\n\nvoid MznProcess::run(const SolverConfiguration& sc, const QStringList& args, const QString& cwd)\n{\n temp = new QTemporaryFile(QDir::tempPath() + \"\/mzn_XXXXXX.json\");\n if (!temp->open()) {\n emit errorOccurred(QProcess::FailedToStart);\n return;\n }\n QString paramFile = temp->fileName();\n temp->write(sc.toJSON());\n temp->close();\n QStringList newArgs;\n newArgs << \"--param-file\" << paramFile << args;\n setWorkingDirectory(cwd);\n Process::start(MznDriver::get().minizincExecutable(), newArgs, MznDriver::get().mznDistribPath());\n}\n\nqint64 MznProcess::timeElapsed()\n{\n if (elapsedTimer.isValid()) {\n return elapsedTimer.elapsed();\n }\n return finalTime;\n}\n\nvoid MznProcess::onExited()\n{\n finalTime = elapsedTimer.elapsed();\n elapsedTimer.invalidate();\n delete temp;\n temp = nullptr;\n}\n\nSolveProcess::SolveProcess(QObject* parent) :\n MznProcess(parent)\n{\n connect(this, &SolveProcess::readyReadStandardOutput, this, &SolveProcess::onStdout);\n connect(this, &SolveProcess::readyReadStandardError, this, &SolveProcess::onStderr);\n connect(this, QOverload::of(&SolveProcess::finished), this, &SolveProcess::onFinished);\n}\n\nvoid SolveProcess::solve(const SolverConfiguration& sc, const QString& modelFile, const QStringList& dataFiles, const QStringList& extraArgs)\n{\n state = State::Output;\n outputBuffer.clear();\n htmlBuffer.clear();\n jsonBuffer.clear();\n\n QFileInfo fi(modelFile);\n QStringList args;\n args << extraArgs << modelFile << dataFiles;\n MznProcess::run(sc, args, fi.canonicalPath());\n}\n\nvoid SolveProcess::onStdout()\n{\n setReadChannel(QProcess::ProcessChannel::StandardOutput);\n\n \/\/ There might be a fragment on stderr without a new line\n \/\/ This should be shown now since stdout has a newline\n \/\/ to emulate console behaviour\n if (canReadLine()) {\n \/\/ All available stderr must be a fragment since otherwise\n \/\/ onStderr would have processed it already\n auto fragment = QString::fromUtf8(readAllStandardError());\n if (!fragment.isEmpty()) {\n processStderr(fragment);\n }\n }\n\n while (canReadLine()) {\n auto line = QString::fromUtf8(readLine());\n processStdout(line);\n }\n}\n\nvoid SolveProcess::onStderr()\n{\n setReadChannel(QProcess::ProcessChannel::StandardError);\n\n while (canReadLine()) {\n auto line = QString::fromUtf8(readLine());\n processStderr(line);\n }\n}\n\nvoid SolveProcess::processStdout(QString line)\n{\n auto trimmed = line.trimmed();\n QRegExp jsonPattern(\"^(?:%%%(top|bottom))?%%%mzn-json(-init)?:(.*)\");\n\n \/\/ Can appear in any state\n if (trimmed.startsWith(\"%%%mzn-stat\")) {\n emit statisticOutput(line);\n return;\n } else if (trimmed.startsWith(\"%%%mzn-progress\")) {\n auto split = trimmed.split(\" \");\n bool ok = split.length() == 2;\n if (ok) {\n auto progress = split[1].toFloat(&ok);\n if (ok) {\n emit progressOutput(progress);\n return;\n }\n }\n }\n\n switch (state) {\n case State::Output: \/\/ Normal solution output\n if (trimmed == \"----------\") {\n outputBuffer << line;\n emit solutionOutput(outputBuffer.join(\"\"));\n if (!visBuffer.isEmpty()) {\n emit jsonOutput(false, visBuffer);\n visBuffer.clear();\n }\n outputBuffer.clear();\n } else if (trimmed == \"==========\" || trimmed == \"=====UNKNOWN=====\" || trimmed == \"=====ERROR=====\") {\n outputBuffer << line;\n emit finalStatus(outputBuffer.join(\"\"));\n outputBuffer.clear();\n } else if (jsonPattern.exactMatch(trimmed)) {\n auto captures = jsonPattern.capturedTexts();\n state = captures[2] == \"-init\" ? State::JSONInit : State::JSON;\n QString area = captures[1].isEmpty() ? \"top\" : captures[1];\n auto jsonArea = area == \"bottom\" ? Qt::BottomDockWidgetArea : Qt::TopDockWidgetArea;\n auto jsonPath = captures[3];\n visBuffer << VisOutput(VisWindowSpec(jsonPath, jsonArea));\n } else if (trimmed == \"%%%mzn-html-start\") {\n state = State::HTML;\n } else {\n outputBuffer << line;\n }\n break;\n case State::HTML: \/\/ Seen %%%mzn-html-start\n if (trimmed.startsWith(\"%%%mzn-html-end\")) {\n emit htmlOutput(htmlBuffer.join(\"\"));\n state = State::Output;\n htmlBuffer.clear();\n } else {\n htmlBuffer << line;\n }\n break;\n case State::JSONInit: \/\/ Seen %%%mzn-json-init\n if (trimmed == \"%%%mzn-json-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n state = State::Output;\n jsonBuffer.clear();\n } else if (trimmed == \"%%%mzn-json-init-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n emit jsonOutput(true, visBuffer);\n state = State::Output;\n jsonBuffer.clear();\n visBuffer.clear();\n } else {\n jsonBuffer << trimmed;\n }\n break;\n case State::JSON: \/\/ Seen %%%mzn-json\n if (trimmed == \"%%%mzn-json-end\") {\n visBuffer.last().data = jsonBuffer.join(\" \");\n state = State::Output;\n jsonBuffer.clear();\n } else if (trimmed == \"%%%mzn-json-time\") {\n \/\/ Wrap current buffer in array with elapsed time\n jsonBuffer.prepend(\"[\");\n jsonBuffer << \",\" << QString().number(timeElapsed()) << \"]\";\n } else {\n jsonBuffer << trimmed;\n }\n break;\n }\n}\n\nvoid SolveProcess::processStderr(QString line)\n{\n auto trimmed = line.trimmed();\n emit stdErrorOutput(line);\n}\n\nvoid SolveProcess::onFinished(int exitCode, QProcess::ExitStatus status)\n{\n \/\/ Finish processing remaining stdout\n onStdout();\n if (!atEnd()) {\n processStdout(readAll());\n }\n if (!outputBuffer.isEmpty()) {\n emit fragment(outputBuffer.join(\"\"));\n outputBuffer.clear();\n }\n \/\/ Finish processing remaining stderr\n onStderr();\n if (!atEnd()) {\n processStderr(readAll());\n }\n\n emit complete(exitCode, status);\n}\n<|endoftext|>"} {"text":"\n#ifndef STAN_MATH_OPENCL_KERNELS_BERNOULLI_LOGIT_GLM_LPMF_HPP\n#define STAN_MATH_OPENCL_KERNELS_BERNOULLI_LOGIT_GLM_LPMF_HPP\n#ifdef STAN_OPENCL\n\n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* bernoulli_logit_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/** \\ingroup opencl_kernels\n * GPU implementation of Generalized Linear Model (GLM)\n * with Bernoulli distribution and logit link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[out] logp_global partially summed log probability (1 value per\n * work group)\n * @param[out] theta_derivative_global derivative with respect to x * beta +\n * alpha\n * @param[out] theta_derivative_sum partially summed theta_derivative_global\n * (1 value per work group)\n * @param[in] y_global binary vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param N number of cases\n * @param M number of attributes\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param need_theta_derivative interpreted as boolean - whether\n * theta_derivative needs to be computed\n * @param need_theta_derivative_sum interpreted as boolean - whether\n * theta_derivative_sum needs to be computed\n *\/\n __kernel void bernoulli_logit_glm(\n __global double* logp_global, __global double* theta_derivative_global,\n __global double* theta_derivative_sum, const __global int* y_global,\n const __global double* x, const __global double* alpha,\n const __global double* beta, const int N, const int M,\n const int is_alpha_vector, const int need_theta_derivative,\n const int need_theta_derivative_sum) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wg_id = get_group_id(0);\n\n __local double local_storage[LOCAL_SIZE_];\n\n double logp = 0;\n double theta_derivative = 0;\n \/\/ Most calculations only happen for relevant data within next if.\n \/\/ Exceptions are reductions between threads that need barriers.\n if (gid < N) {\n double ytheta = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n ytheta += x[j + gid] * beta[i];\n }\n const int y = y_global[gid];\n const double sign_ = 2 * y - 1;\n ytheta += alpha[gid * is_alpha_vector];\n ytheta *= sign_;\n if (y > 1 || y < 0 || !isfinite(ytheta)) {\n \/\/ this signals that an exception must be raised\n logp = NAN;\n }\n const double exp_m_ytheta = exp(-ytheta);\n\n const double cutoff = 20.0;\n if (ytheta > cutoff) {\n logp -= exp_m_ytheta;\n theta_derivative = -exp_m_ytheta;\n } else if (ytheta < -cutoff) {\n logp += ytheta;\n theta_derivative = sign_;\n } else {\n logp += -log1p(exp_m_ytheta);\n theta_derivative = sign_ * exp_m_ytheta \/ (exp_m_ytheta + 1);\n }\n\n if (need_theta_derivative) {\n theta_derivative_global[gid] = theta_derivative;\n }\n }\n \/\/ Sum logp, calculated by different threads.\n \/\/ Since we can't sum between different work groups, we emit one number\n \/\/ per work group. These must be summed on CPU for final result.\n local_storage[lid] = logp;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n local_storage[lid] += local_storage[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n logp_global[wg_id] = local_storage[0];\n }\n\n if (need_theta_derivative_sum) {\n \/\/ Sum theta_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n local_storage[lid] = theta_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n local_storage[lid] += local_storage[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n theta_derivative_sum[wg_id] = local_storage[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/** \\ingroup opencl_kernels\n * See the docs for \\link kernels\/bernoulli_logit_glm_lpmf.hpp\n * bernoulli_logit_glm() \\endlink\n *\/\nconst kernel_cl\n bernoulli_logit_glm(\"bernoulli_logit_glm\",\n {bernoulli_logit_glm_kernel_code},\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\nRevert \"missed one file\"\n#ifndef STAN_MATH_OPENCL_KERNELS_BERNOULLI_LOGIT_GLM_LPMF_HPP\n#define STAN_MATH_OPENCL_KERNELS_BERNOULLI_LOGIT_GLM_LPMF_HPP\n#ifdef STAN_OPENCL\n\n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* bernoulli_logit_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/** \\ingroup opencl_kernels\n * GPU implementation of Generalized Linear Model (GLM)\n * with Bernoulli distribution and logit link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[out] logp_global partially summed log probability (1 value per\n * work group)\n * @param[out] theta_derivative_global derivative with respect to x * beta +\n * alpha\n * @param[out] theta_derivative_sum partially summed theta_derivative_global\n * (1 value per work group)\n * @param[in] y_global binary vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param N number of cases\n * @param M number of attributes\n * @param is_y_vector 0 or 1 - whether y is a vector (alternatively\n * it is a scalar)\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param need_theta_derivative interpreted as boolean - whether\n * theta_derivative needs to be computed\n * @param need_theta_derivative_sum interpreted as boolean - whether\n * theta_derivative_sum needs to be computed\n *\/\n __kernel void bernoulli_logit_glm(\n __global double* logp_global, __global double* theta_derivative_global,\n __global double* theta_derivative_sum, const __global int* y_global,\n const __global double* x, const __global double* alpha,\n const __global double* beta, const int N, const int M,\n const int is_y_vector, const int is_alpha_vector,\n const int need_theta_derivative, const int need_theta_derivative_sum) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wg_id = get_group_id(0);\n\n __local double local_storage[LOCAL_SIZE_];\n\n double logp = 0;\n double theta_derivative = 0;\n \/\/ Most calculations only happen for relevant data within next if.\n \/\/ Exceptions are reductions between threads that need barriers.\n if (gid < N) {\n double ytheta = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n ytheta += x[j + gid] * beta[i];\n }\n const int y = y_global[gid * is_y_vector];\n const double sign_ = 2 * y - 1;\n ytheta += alpha[gid * is_alpha_vector];\n ytheta *= sign_;\n if (y > 1 || y < 0 || !isfinite(ytheta)) {\n \/\/ this signals that an exception must be raised\n logp = NAN;\n }\n const double exp_m_ytheta = exp(-ytheta);\n\n const double cutoff = 20.0;\n if (ytheta > cutoff) {\n logp -= exp_m_ytheta;\n theta_derivative = -exp_m_ytheta;\n } else if (ytheta < -cutoff) {\n logp += ytheta;\n theta_derivative = sign_;\n } else {\n logp += -log1p(exp_m_ytheta);\n theta_derivative = sign_ * exp_m_ytheta \/ (exp_m_ytheta + 1);\n }\n\n if (need_theta_derivative) {\n theta_derivative_global[gid] = theta_derivative;\n }\n }\n \/\/ Sum logp, calculated by different threads.\n \/\/ Since we can't sum between different work groups, we emit one number\n \/\/ per work group. These must be summed on CPU for final result.\n local_storage[lid] = logp;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n local_storage[lid] += local_storage[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n logp_global[wg_id] = local_storage[0];\n }\n\n if (need_theta_derivative_sum) {\n \/\/ Sum theta_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n local_storage[lid] = theta_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n local_storage[lid] += local_storage[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n theta_derivative_sum[wg_id] = local_storage[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/** \\ingroup opencl_kernels\n * See the docs for \\link kernels\/bernoulli_logit_glm_lpmf.hpp\n * bernoulli_logit_glm() \\endlink\n *\/\nconst kernel_cl\n bernoulli_logit_glm(\"bernoulli_logit_glm\",\n {bernoulli_logit_glm_kernel_code},\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n\n#include \"api\/Compiler.hh\"\n#include \"api\/DataFile.hh\"\n#include \"api\/Decoder.hh\"\n#include \"api\/Encoder.hh\"\n#include \"api\/Generic.hh\"\n#include \"api\/Specific.hh\"\n#include \"api\/ValidSchema.hh\"\n#include \"google\/cloud\/bigquery\/storage\/v1beta1\/storage.grpc.pb.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/lib\/core\/threadpool.h\"\n#include \"tensorflow\/core\/lib\/strings\/stringprintf.h\"\n#include \"tensorflow_io\/bigquery\/kernels\/bigquery_lib.h\"\n\nnamespace tensorflow {\nnamespace {\n\nnamespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1;\nstatic constexpr int kMaxReceiveMessageSize = 1 << 24; \/\/ 16 MBytes\n\nclass BigQueryClientOp : public OpKernel {\n public:\n explicit BigQueryClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n }\n\n ~BigQueryClientOp() override {\n if (cinfo_.resource_is_private_to_kernel()) {\n if (!cinfo_.resource_manager()\n ->Delete(cinfo_.container(),\n cinfo_.name())\n .ok()) {\n \/\/ Do nothing; the resource can have been deleted by session resets.\n }\n }\n }\n\n void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {\n mutex_lock l(mu_);\n if (!initialized_) {\n ResourceMgr* mgr = ctx->resource_manager();\n OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));\n BigQueryClientResource* resource;\n OP_REQUIRES_OK(\n ctx,\n mgr->LookupOrCreate(\n cinfo_.container(), cinfo_.name(), &resource,\n [this, ctx](\n BigQueryClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n std::string server_name =\n \"dns:\/\/\/bigquerystorage.googleapis.com\";\n auto creds = ::grpc::GoogleDefaultCredentials();\n grpc::ChannelArguments args;\n args.SetMaxReceiveMessageSize(kMaxReceiveMessageSize);\n args.SetUserAgentPrefix(\"tensorflow\");\n args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0);\n args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 60 * 1000);\n auto channel = ::grpc::CreateCustomChannel(\n server_name, creds, args);\n VLOG(3) << \"Creating GRPC channel\";\n auto stub =\n absl::make_unique(\n channel);\n VLOG(3) << \"Done creating GRPC channel\";\n\n *ret = new BigQueryClientResource(std::move(stub));\n return Status::OK();\n }));\n core::ScopedUnref resource_cleanup(resource);\n initialized_ = true;\n }\n OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput(\n ctx, 0, cinfo_.container(), cinfo_.name(),\n MakeTypeIndex()));\n }\n\n private:\n mutex mu_;\n ContainerInfo cinfo_ GUARDED_BY(mu_);\n bool initialized_ GUARDED_BY(mu_) = false;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"IO>BigQueryClient\").Device(DEVICE_CPU),\n BigQueryClientOp);\n\nclass BigQueryReadSessionOp : public OpKernel {\n public:\n explicit BigQueryReadSessionOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"parent\", &parent_));\n OP_REQUIRES(ctx, !parent_.empty(),\n errors::InvalidArgument(\"parent must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"project_id\", &project_id_));\n OP_REQUIRES(ctx, !project_id_.empty(),\n errors::InvalidArgument(\"project_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"table_id\", &table_id_));\n OP_REQUIRES(ctx, !table_id_.empty(),\n errors::InvalidArgument(\"table_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"dataset_id\", &dataset_id_));\n OP_REQUIRES(ctx, !dataset_id_.empty(),\n errors::InvalidArgument(\"dataset_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"selected_fields\", &selected_fields_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"output_types\", &output_types_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"row_restriction\", &row_restriction_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"requested_streams\", &requested_streams_));\n }\n\n void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {\n mutex_lock l(mu_);\n ResourceMgr* mgr = ctx->resource_manager();\n OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));\n\n BigQueryClientResource* client_resource;\n OP_REQUIRES_OK(\n ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &client_resource));\n core::ScopedUnref scoped_unref(client_resource);\n\n apiv1beta1::CreateReadSessionRequest createReadSessionRequest;\n createReadSessionRequest.mutable_table_reference()->set_project_id(\n project_id_);\n createReadSessionRequest.mutable_table_reference()->set_dataset_id(\n dataset_id_);\n createReadSessionRequest.mutable_table_reference()->set_table_id(table_id_);\n createReadSessionRequest.set_parent(parent_);\n *createReadSessionRequest.mutable_read_options()\n ->mutable_selected_fields() = {selected_fields_.begin(),\n selected_fields_.end()};\n createReadSessionRequest.mutable_read_options()->set_row_restriction(\n row_restriction_); \n createReadSessionRequest.set_requested_streams(requested_streams_);\n createReadSessionRequest.set_format(apiv1beta1::DataFormat::AVRO);\n VLOG(3) << \"createReadSessionRequest: \"\n << createReadSessionRequest.DebugString();\n ::grpc::ClientContext context;\n context.AddMetadata(\"x-goog-request-params\",\n strings::Printf(\"table_reference.dataset_id=%s&table_\"\n \"reference.project_id=%s\",\n dataset_id_.c_str(),\n project_id_.c_str()));\n context.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_seconds(60, GPR_TIMESPAN)));\n\n std::shared_ptr readSessionResponse =\n std::make_shared();\n VLOG(3) << \"calling readSession\";\n ::grpc::Status status = client_resource->get_stub()->CreateReadSession(\n &context, createReadSessionRequest, readSessionResponse.get());\n if (!status.ok()) {\n VLOG(3) << \"readSession status:\" << GrpcStatusToString(status);\n ctx->CtxFailure(GrpcStatusToTfStatus(status));\n return;\n }\n VLOG(3) << \"readSession response:\" << readSessionResponse->DebugString();\n if (readSessionResponse->has_avro_schema()) {\n VLOG(3) << \"avro schema:\" << readSessionResponse->avro_schema().schema();\n }\n\n Tensor* streams_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n \"streams\",\n {readSessionResponse->streams_size()},\n &streams_t));\n auto streams_vec = streams_t->vec();\n for (int i = 0; i < readSessionResponse->streams_size(); i++) {\n streams_vec(i) = readSessionResponse->streams(i).name();\n }\n Tensor* avro_schema_t = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\"avro_schema\", {}, &avro_schema_t));\n avro_schema_t->scalar()() =\n readSessionResponse->avro_schema().schema();\n }\n\n private:\n \/\/ Note: these fields are const after construction.\n string parent_;\n string project_id_;\n string table_id_;\n string dataset_id_;\n std::vector selected_fields_;\n std::vector output_types_;\n string row_restriction_;\n int requested_streams_;\n\n mutex mu_;\n ContainerInfo cinfo_ GUARDED_BY(mu_);\n bool initialized_ GUARDED_BY(mu_) = false;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"IO>BigQueryReadSession\").Device(DEVICE_CPU),\n BigQueryReadSessionOp);\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\nUse balanced sharding strategy in bigquery read session. (#601)\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n\n#include \"api\/Compiler.hh\"\n#include \"api\/DataFile.hh\"\n#include \"api\/Decoder.hh\"\n#include \"api\/Encoder.hh\"\n#include \"api\/Generic.hh\"\n#include \"api\/Specific.hh\"\n#include \"api\/ValidSchema.hh\"\n#include \"google\/cloud\/bigquery\/storage\/v1beta1\/storage.grpc.pb.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/lib\/core\/threadpool.h\"\n#include \"tensorflow\/core\/lib\/strings\/stringprintf.h\"\n#include \"tensorflow_io\/bigquery\/kernels\/bigquery_lib.h\"\n\nnamespace tensorflow {\nnamespace {\n\nnamespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1;\nstatic constexpr int kMaxReceiveMessageSize = 1 << 24; \/\/ 16 MBytes\n\nclass BigQueryClientOp : public OpKernel {\n public:\n explicit BigQueryClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n }\n\n ~BigQueryClientOp() override {\n if (cinfo_.resource_is_private_to_kernel()) {\n if (!cinfo_.resource_manager()\n ->Delete(cinfo_.container(),\n cinfo_.name())\n .ok()) {\n \/\/ Do nothing; the resource can have been deleted by session resets.\n }\n }\n }\n\n void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {\n mutex_lock l(mu_);\n if (!initialized_) {\n ResourceMgr* mgr = ctx->resource_manager();\n OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));\n BigQueryClientResource* resource;\n OP_REQUIRES_OK(\n ctx,\n mgr->LookupOrCreate(\n cinfo_.container(), cinfo_.name(), &resource,\n [this, ctx](\n BigQueryClientResource** ret) EXCLUSIVE_LOCKS_REQUIRED(mu_) {\n std::string server_name =\n \"dns:\/\/\/bigquerystorage.googleapis.com\";\n auto creds = ::grpc::GoogleDefaultCredentials();\n grpc::ChannelArguments args;\n args.SetMaxReceiveMessageSize(kMaxReceiveMessageSize);\n args.SetUserAgentPrefix(\"tensorflow\");\n args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0);\n args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 60 * 1000);\n auto channel = ::grpc::CreateCustomChannel(\n server_name, creds, args);\n VLOG(3) << \"Creating GRPC channel\";\n auto stub =\n absl::make_unique(\n channel);\n VLOG(3) << \"Done creating GRPC channel\";\n\n *ret = new BigQueryClientResource(std::move(stub));\n return Status::OK();\n }));\n core::ScopedUnref resource_cleanup(resource);\n initialized_ = true;\n }\n OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput(\n ctx, 0, cinfo_.container(), cinfo_.name(),\n MakeTypeIndex()));\n }\n\n private:\n mutex mu_;\n ContainerInfo cinfo_ GUARDED_BY(mu_);\n bool initialized_ GUARDED_BY(mu_) = false;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"IO>BigQueryClient\").Device(DEVICE_CPU),\n BigQueryClientOp);\n\nclass BigQueryReadSessionOp : public OpKernel {\n public:\n explicit BigQueryReadSessionOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"parent\", &parent_));\n OP_REQUIRES(ctx, !parent_.empty(),\n errors::InvalidArgument(\"parent must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"project_id\", &project_id_));\n OP_REQUIRES(ctx, !project_id_.empty(),\n errors::InvalidArgument(\"project_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"table_id\", &table_id_));\n OP_REQUIRES(ctx, !table_id_.empty(),\n errors::InvalidArgument(\"table_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"dataset_id\", &dataset_id_));\n OP_REQUIRES(ctx, !dataset_id_.empty(),\n errors::InvalidArgument(\"dataset_id must be non-empty\"));\n\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"selected_fields\", &selected_fields_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"output_types\", &output_types_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"row_restriction\", &row_restriction_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"requested_streams\", &requested_streams_));\n }\n\n void Compute(OpKernelContext* ctx) override LOCKS_EXCLUDED(mu_) {\n mutex_lock l(mu_);\n ResourceMgr* mgr = ctx->resource_manager();\n OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def()));\n\n BigQueryClientResource* client_resource;\n OP_REQUIRES_OK(\n ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &client_resource));\n core::ScopedUnref scoped_unref(client_resource);\n\n apiv1beta1::CreateReadSessionRequest createReadSessionRequest;\n createReadSessionRequest.mutable_table_reference()->set_project_id(\n project_id_);\n createReadSessionRequest.mutable_table_reference()->set_dataset_id(\n dataset_id_);\n createReadSessionRequest.mutable_table_reference()->set_table_id(table_id_);\n createReadSessionRequest.set_parent(parent_);\n *createReadSessionRequest.mutable_read_options()\n ->mutable_selected_fields() = {selected_fields_.begin(),\n selected_fields_.end()};\n createReadSessionRequest.mutable_read_options()->set_row_restriction(\n row_restriction_); \n createReadSessionRequest.set_requested_streams(requested_streams_);\n createReadSessionRequest.set_sharding_strategy(apiv1beta1::ShardingStrategy::BALANCED);\n createReadSessionRequest.set_format(apiv1beta1::DataFormat::AVRO);\n VLOG(3) << \"createReadSessionRequest: \"\n << createReadSessionRequest.DebugString();\n ::grpc::ClientContext context;\n context.AddMetadata(\"x-goog-request-params\",\n strings::Printf(\"table_reference.dataset_id=%s&table_\"\n \"reference.project_id=%s\",\n dataset_id_.c_str(),\n project_id_.c_str()));\n context.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_seconds(60, GPR_TIMESPAN)));\n\n std::shared_ptr readSessionResponse =\n std::make_shared();\n VLOG(3) << \"calling readSession\";\n ::grpc::Status status = client_resource->get_stub()->CreateReadSession(\n &context, createReadSessionRequest, readSessionResponse.get());\n if (!status.ok()) {\n VLOG(3) << \"readSession status:\" << GrpcStatusToString(status);\n ctx->CtxFailure(GrpcStatusToTfStatus(status));\n return;\n }\n VLOG(3) << \"readSession response:\" << readSessionResponse->DebugString();\n if (readSessionResponse->has_avro_schema()) {\n VLOG(3) << \"avro schema:\" << readSessionResponse->avro_schema().schema();\n }\n\n Tensor* streams_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\n \"streams\",\n {readSessionResponse->streams_size()},\n &streams_t));\n auto streams_vec = streams_t->vec();\n for (int i = 0; i < readSessionResponse->streams_size(); i++) {\n streams_vec(i) = readSessionResponse->streams(i).name();\n }\n Tensor* avro_schema_t = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\"avro_schema\", {}, &avro_schema_t));\n avro_schema_t->scalar()() =\n readSessionResponse->avro_schema().schema();\n }\n\n private:\n \/\/ Note: these fields are const after construction.\n string parent_;\n string project_id_;\n string table_id_;\n string dataset_id_;\n std::vector selected_fields_;\n std::vector output_types_;\n string row_restriction_;\n int requested_streams_;\n\n mutex mu_;\n ContainerInfo cinfo_ GUARDED_BY(mu_);\n bool initialized_ GUARDED_BY(mu_) = false;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"IO>BigQueryReadSession\").Device(DEVICE_CPU),\n BigQueryReadSessionOp);\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \n\n#include \"engine.h\"\n#include \"entity.h\"\n#include \"geometry.h\"\n#include \"engine_event.h\"\n#include \"misc.h\"\n#include \"wall.h\"\n#include \"player.h\"\n#include \n#include \n#include \n#include \n#include \"commands.h\"\n\nusing namespace sf;\n\nstatic bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b);\n\nvoid Engine::play(void) {\n\twhile (step()) {\n\t\tEvent e;\n\t\twhile (window.pollEvent(e)) {\n\t\t\tif (e.type == Event::Closed) {\n\t\t\t\tquit();\n\t\t\t} else if (e.type == Event::KeyPressed) {\n\t\t\t\tif (e.key.code == Keyboard::Escape) quit();\n\t\t\t} else if (e.type == Event::JoystickConnected) {\n\t\t\t\taddPlayer(0, e.joystickConnect.joystickId);\n\t\t\t} else if (e.type == Event::JoystickDisconnected) {\n\t\t\t\tPlayer *pl = getPlayerByJoystickId(e.joystickConnect.joystickId);\n\t\t\t\tif (pl) {destroy(pl);destroy_flagged();}\n\t\t\t} else if (KeymapController::maybeConcerned(e)) {\n\t\t\t\tcontroller_activity(e);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Engine::controller_activity(Event &e) {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); it++) {\n\t\tPlayer *pl = dynamic_cast(*it);\n\t\tif (!pl) continue;\n\t\tKeymapController *c = dynamic_cast(pl->getController());\n\t\tif (c) {\n\t\t\tint ojoyid = -1;\n\t\t\tif (c->isConcerned(e, ojoyid)) return;\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\/* this key event is not owned by a player, have a look at controller templates *\/\n\tstd::vector &cd = cdef.forplayer;\n\tfor(unsigned i = 0; i < cd.size(); i++) {\n\t\tint ojoyid = -1;\n\t\tif (cd[i] && cd[i]->isConcerned(e, ojoyid)) {\n\t\t\taddPlayer(i, ojoyid);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nPlayer *Engine::getPlayerByJoystickId(int joyid) {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); it++) {\n\t\tPlayer *pl = dynamic_cast(*it);\n\t\tif (!pl) continue;\n\t\tKeymapController *c = dynamic_cast(pl->getController());\n\t\tif (c) {\n\t\t\tif (c->getJoystickId() == joyid) return pl;\n\t\t\tcontinue;\n\t\t}\n\t\tJoystickController *j = dynamic_cast(pl->getController());\n\t\tif (j) {\n\t\t\tif (j->getJoystickId() == joyid) return pl;\n\t\t}\n\t}\n\treturn NULL;\n}\nvoid Engine::addPlayer(unsigned cid, int joyid) {\n\tif (cid >= cdef.forplayer.size()) return;\n\tif (cid == 0 && joyid == -1) {\n\t\t\/* search a free joystick *\/\n\t\tfor(unsigned i=0; i < Joystick::Count; i++) {\n\t\t\tif (Joystick::isConnected(i) && !getPlayerByJoystickId(i)) {\n\t\t\t\tjoyid = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!cdef.forplayer[cid]) {\n\t\tfprintf(stderr, \"Error: no controller %d found for new player\\n\", cid);\n\t\treturn;\n\t}\n\tif (cid > 0) joyid = -1;\n\tadd(new Player(cdef.forplayer[cid]->clone(joyid), this));\n}\nEntity *Engine::getMapBoundariesEntity() {\n\treturn map_boundaries_entity;\n}\nTextureCache *Engine::getTextureCache(void) const {\n\treturn &texture_cache;\n}\nVector2d Engine::map_size(void) {\n\tVector2u sz = window.getSize();\n\treturn Vector2d(sz.x, sz.y);\n}\nEngine::EntitiesIterator Engine::begin_entities() {\n\treturn entities.begin();\n}\nEngine::EntitiesIterator Engine::end_entities() {\n\treturn entities.end();\n}\nEngine::Engine() {\n\tfirst_step = true;\n\tmust_quit = false;\n\twindow.create(VideoMode(1920,1080), \"Tank window\", Style::Default);\n\twindow.setVerticalSyncEnabled(true);\n\twindow.clear(Color::White);\n\tscore_font.loadFromFile(\"\/usr\/share\/fonts\/truetype\/droid\/DroidSans.ttf\");\n\n\tload_texture(background, background_texture, \"sprites\/dirt.jpg\");\n\tVector2d sz = map_size();\n\tbackground.setTextureRect(IntRect(0,0,sz.x,sz.y));\n\tmap_boundaries_entity = new Wall(0,0,sz.x,sz.y, NULL, this);\n\tadd(map_boundaries_entity);\n\tload_keymap(cdef, \"keymap.json\");\n}\nEngine::~Engine() {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tdelete (*it);\n\t}\n\twindow.close();\n}\nvoid Engine::seekCollisions(Entity *entity) {\n\tint i=100;\n\tbool retry = false;\n\tdo {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tEntity *centity = (*it);\n\t\tSegment vect;\n\t\tvect.pt1 = entity->position;\n\t\tvect.pt2 = entity->position;\n\t\tMoveContext ctx(IT_GHOST, vect);\n\t\tif (interacts(this, ctx, entity, centity)) {\n\t\t\tCollisionEvent e;\n\t\t\te.first = entity;\n\t\t\te.second = centity;\n\t\t\te.interaction = IT_GHOST;\n\t\t\tbroadcast(&e);\n\t\t\tif (e.retry) retry = true;\n\t\t}\n\t}\n\t} while(retry && --i > 0);\n}\nvoid Engine::add(Entity *entity) {\n\tentity->setEngine(this);\n\tentities.push_back(entity);\n\t\/* signal spawn-time collisions *\/\n\tseekCollisions(entity);\n}\nvoid Engine::destroy(Entity *entity) { \/* Removes entity from engine and deletes the underlying object *\/\n\tentity->setKilled();\n}\nvoid Engine::broadcast(EngineEvent *event) {\n\t\/* assume iterators may be invalidated during event processing, because new items may be added *\/\n\t\/* note that entities may be set to killed, but cannot be removed from the list (they are only flagged) *\/\n\n\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\tEntity *entity = entities[i];\n\t\tif (!entity->isKilled()) entity->event_received(event);\n\t}\n}\nvoid Engine::quit(void) {\n\tmust_quit = true;\n}\nbool Engine::step(void) {\n\tif (must_quit) return false;\n\tif (first_step) {clock.restart();first_step=false;}\n\tdraw();\n\tcompute_physics();\n\tdestroy_flagged();\n\treturn !must_quit;\n}\nvoid draw_score(RenderTarget &target, Font &ft, int score, Color color, Vector2d pos) {\n\tText text;\n\tchar sscore[256];\n\tsprintf(sscore, \"%d\", score);\n\ttext.setCharacterSize(128);\n\ttext.setString(sscore);\n\ttext.setColor(color);\n\ttext.setPosition(Vector2f(pos.x, pos.y));\n\ttext.setFont(ft);\n\n\ttarget.draw(text);\n}\nvoid Engine::draw(void) {\n\tVector2d scorepos;\n\tscorepos.x = 16;\n\tscorepos.y = 16;\n\twindow.clear();\n\twindow.draw(background);\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\t(*it)->draw(window);\n\n\t\tif (Player *pl = dynamic_cast((*it))) {\n\t\t\tdraw_score(window, score_font, pl->getScore(), pl->getColor(), scorepos);\n\t\t\tscorepos.x += 384+16;\n\t\t}\n\t}\n\twindow.display();\n}\nstatic double getEntityRadius(Entity *a) {\n\treturn a->getSize().x\/2;\n}\nstatic DoubleRect getEntityBoundingRectangle(Entity *a) {\n\tVector2d pos = a->position;\n\tVector2d size = a->getSize();\n\tDoubleRect r;\n\tr.left = pos.x;\n\tr.top = pos.y;\n\tr.width = size.x;\n\tr.height = size.y;\n\treturn r;\n}\nstatic Circle getEntityCircle(Entity *a) {\n\tCircle circle;\n\tcircle.filled = true;\n\tcircle.center = a->position;\n\tcircle.radius = getEntityRadius(a);\n\treturn circle;\n}\n\/* Note: Dynamic entities must be circle-shaped *\/\nstatic bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b) {\n\tif (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_RECTANGLE) {\n\t\tGeomRectangle gr;\n\t\tgr.filled = (b != engine->getMapBoundariesEntity());\n\t\tgr.r = getEntityBoundingRectangle(b);\n\t\treturn moveCircleToRectangle(getEntityRadius(a), ctx, gr);\n\t} else if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_CIRCLE) {\n\t\treturn moveCircleToCircle(getEntityRadius(a), ctx, getEntityCircle(b));\n\t} else {\n\t\treturn false;\n\t}\n}\nbool moveCircleToRectangle(double radius, MoveContext &ctx, const DoubleRect &r);\nbool moveCircleToCircle(double radius, MoveContext &ctx, const Circle &colli);\n\nstatic bool quasi_equals(double a, double b) {\n\treturn fabs(a-b) <= 1e-3*(fabs(a)+fabs(b));\n}\nvoid Engine::compute_physics(void) {\n\tInt64 tm = clock.getElapsedTime().asMicroseconds();\n\tif (tm == 0) return;\n\tclock.restart();\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tEntity *entity = (*it);\n\t\tif (entity->isKilled()) continue;\n\t\tVector2d movement = entity->movement(tm);\n\t\tVector2d old_speed = movement;\n\t\told_speed.x \/= tm;\n\t\told_speed.y \/= tm;\n\t\tSegment vect;\n\t\tvect.pt1 = entity->position;\n\t\tvect.pt2 = vect.pt1 + movement;\n\t\tif ((fabs(movement.x)+fabs(movement.y)) < 1e-4) continue;\n\t\tMoveContext ctx(IT_GHOST, vect);\n\t\tfor(int pass=0; pass < 2; ++pass)\n\t\tfor (EntitiesIterator itc=entities.begin(); itc != entities.end(); ++itc) {\n\t\t\tEntity *centity = *itc;\n\t\t\tif (centity->isKilled()) continue;\n\t\t\tif (entity->isKilled()) break;\n\t\t\tif (centity == entity) continue;\n\t\t\tctx.interaction = IT_GHOST;\n\t\t\tMoveContext ctxtemp = ctx;\n\t\t\tif (interacts(this, ctxtemp, entity, centity)) {\n\t\t\t\tif (entity->isKilled() || centity->isKilled()) continue;\n\t\t\t\tCollisionEvent e;\n\t\t\t\te.type = COLLIDE_EVENT;\n\t\t\t\te.first = entity;\n\t\t\t\te.second = centity;\n\t\t\t\te.interaction = IT_GHOST; \/* default interaction type *\/\n\t\t\t\tbroadcast(&e); \/* should set e.interaction *\/\n\t\t\t\tctx.interaction = e.interaction;\n\t\t\t\tif (pass == 1 && ctx.interaction != IT_GHOST) {\n\t\t\t\t\t\/* On second interaction in the same frame, cancel movement *\/\n\t\t\t\t\tctx.vect.pt2 = ctx.vect.pt1 = entity->position;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tinteracts(this, ctx, entity, centity);\n\t\t\t}\n\t\t}\n\t\tif (entity->isKilled()) continue;\n\t\tvect = ctx.vect;\n\t\tCompletedMovementEvent e;\n\t\te.type = COMPLETED_MOVEMENT_EVENT;\n\t\te.entity = entity;\n\t\te.position = vect.pt2;\n\t\tVector2d new_speed = ctx.nmove;\n\t\tnew_speed.x \/= tm;\n\t\tnew_speed.y \/= tm;\n\t\tif (quasi_equals(old_speed.x, new_speed.x) && quasi_equals(old_speed.y, new_speed.y)) {\n\t\t\te.new_speed = old_speed;\n\t\t\te.has_new_speed = false;\n\t\t} else {\n\t\t\te.new_speed = new_speed;\n\t\t\te.has_new_speed = true;\n\t\t}\n\t\tbroadcast(&e);\n\t}\n}\nvoid Engine::destroy_flagged(void) {\n\tbool some_got_deleted;\n\tdo {\n\t\tsome_got_deleted = false;\n\t\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\t\tEntity *entity = entities[i];\n\t\t\tif (entity->isKilled()) {\n\t\t\t\tsome_got_deleted = true;\n\t\t\t\tEntityDestroyedEvent e;\n\t\t\t\te.type = ENTITY_DESTROYED_EVENT;\n\t\t\t\te.entity = entity;\n\t\t\t\tbroadcast(&e);\n\t\t\t\tentities.erase(entities.begin()+i);\n\t\t\t\tdelete entity;\n\t\t\t\t--i;\n\t\t\t}\n\t\t}\n\t} while(some_got_deleted);\n#if 0\n\tif (some_got_deleted) fprintf(stderr, \"[now, I'm going to physically destroy things]\\n\");\n\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\tEntity *entity = entities[i];\n\t\tif (entity->isKilled()) {\n\t\t\tentities.erase(entities.begin()+i);\n\t\t\tdelete entity;\n\t\t\t--i;\n\t\t}\n\t}\n\tif (some_got_deleted) fprintf(stderr, \"[\/physically destroyed things]\\n\");\n#endif\n}\n\nFixed bug that ignored keypress events in controller spawning code.#include \n\n#include \"engine.h\"\n#include \"entity.h\"\n#include \"geometry.h\"\n#include \"engine_event.h\"\n#include \"misc.h\"\n#include \"wall.h\"\n#include \"player.h\"\n#include \n#include \n#include \n#include \n#include \"commands.h\"\n\nusing namespace sf;\n\nstatic bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b);\n\nvoid Engine::play(void) {\n\twhile (step()) {\n\t\tEvent e;\n\t\twhile (window.pollEvent(e)) {\n\t\t\tif (e.type == Event::Closed) {\n\t\t\t\tquit();\n\t\t\t} else if (e.type == Event::KeyPressed) {\n\t\t\t\tif (e.key.code == Keyboard::Escape) quit();\n\t\t\t} else if (e.type == Event::JoystickConnected) {\n\t\t\t\taddPlayer(0, e.joystickConnect.joystickId);\n\t\t\t} else if (e.type == Event::JoystickDisconnected) {\n\t\t\t\tPlayer *pl = getPlayerByJoystickId(e.joystickConnect.joystickId);\n\t\t\t\tif (pl) {destroy(pl);destroy_flagged();}\n\t\t\t}\n\t\t\tif (KeymapController::maybeConcerned(e)) {\n\t\t\t\tcontroller_activity(e);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Engine::controller_activity(Event &e) {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); it++) {\n\t\tPlayer *pl = dynamic_cast(*it);\n\t\tif (!pl) continue;\n\t\tKeymapController *c = dynamic_cast(pl->getController());\n\t\tif (c) {\n\t\t\tint ojoyid = -1;\n\t\t\tif (c->isConcerned(e, ojoyid)) return;\n\t\t\tcontinue;\n\t\t}\n\t}\n\t\/* this key event is not owned by a player, have a look at controller templates *\/\n\tstd::vector &cd = cdef.forplayer;\n\tfor(unsigned i = 0; i < cd.size(); i++) {\n\t\tint ojoyid = -1;\n\t\tif (cd[i] && cd[i]->isConcerned(e, ojoyid)) {\n\t\t\taddPlayer(i, ojoyid);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nPlayer *Engine::getPlayerByJoystickId(int joyid) {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); it++) {\n\t\tPlayer *pl = dynamic_cast(*it);\n\t\tif (!pl) continue;\n\t\tKeymapController *c = dynamic_cast(pl->getController());\n\t\tif (c) {\n\t\t\tif (c->getJoystickId() == joyid) return pl;\n\t\t\tcontinue;\n\t\t}\n\t\tJoystickController *j = dynamic_cast(pl->getController());\n\t\tif (j) {\n\t\t\tif (j->getJoystickId() == joyid) return pl;\n\t\t}\n\t}\n\treturn NULL;\n}\nvoid Engine::addPlayer(unsigned cid, int joyid) {\n\tif (cid >= cdef.forplayer.size()) return;\n\tif (cid == 0 && joyid == -1) {\n\t\t\/* search a free joystick *\/\n\t\tfor(unsigned i=0; i < Joystick::Count; i++) {\n\t\t\tif (Joystick::isConnected(i) && !getPlayerByJoystickId(i)) {\n\t\t\t\tjoyid = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!cdef.forplayer[cid]) {\n\t\tfprintf(stderr, \"Error: no controller %d found for new player\\n\", cid);\n\t\treturn;\n\t}\n\tif (cid > 0) joyid = -1;\n\tadd(new Player(cdef.forplayer[cid]->clone(joyid), this));\n}\nEntity *Engine::getMapBoundariesEntity() {\n\treturn map_boundaries_entity;\n}\nTextureCache *Engine::getTextureCache(void) const {\n\treturn &texture_cache;\n}\nVector2d Engine::map_size(void) {\n\tVector2u sz = window.getSize();\n\treturn Vector2d(sz.x, sz.y);\n}\nEngine::EntitiesIterator Engine::begin_entities() {\n\treturn entities.begin();\n}\nEngine::EntitiesIterator Engine::end_entities() {\n\treturn entities.end();\n}\nEngine::Engine() {\n\tfirst_step = true;\n\tmust_quit = false;\n\twindow.create(VideoMode(1920,1080), \"Tank window\", Style::Default);\n\twindow.setVerticalSyncEnabled(true);\n\twindow.clear(Color::White);\n\tscore_font.loadFromFile(\"\/usr\/share\/fonts\/truetype\/droid\/DroidSans.ttf\");\n\n\tload_texture(background, background_texture, \"sprites\/dirt.jpg\");\n\tVector2d sz = map_size();\n\tbackground.setTextureRect(IntRect(0,0,sz.x,sz.y));\n\tmap_boundaries_entity = new Wall(0,0,sz.x,sz.y, NULL, this);\n\tadd(map_boundaries_entity);\n\tload_keymap(cdef, \"keymap.json\");\n}\nEngine::~Engine() {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tdelete (*it);\n\t}\n\twindow.close();\n}\nvoid Engine::seekCollisions(Entity *entity) {\n\tint i=100;\n\tbool retry = false;\n\tdo {\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tEntity *centity = (*it);\n\t\tSegment vect;\n\t\tvect.pt1 = entity->position;\n\t\tvect.pt2 = entity->position;\n\t\tMoveContext ctx(IT_GHOST, vect);\n\t\tif (interacts(this, ctx, entity, centity)) {\n\t\t\tCollisionEvent e;\n\t\t\te.first = entity;\n\t\t\te.second = centity;\n\t\t\te.interaction = IT_GHOST;\n\t\t\tbroadcast(&e);\n\t\t\tif (e.retry) retry = true;\n\t\t}\n\t}\n\t} while(retry && --i > 0);\n}\nvoid Engine::add(Entity *entity) {\n\tentity->setEngine(this);\n\tentities.push_back(entity);\n\t\/* signal spawn-time collisions *\/\n\tseekCollisions(entity);\n}\nvoid Engine::destroy(Entity *entity) { \/* Removes entity from engine and deletes the underlying object *\/\n\tentity->setKilled();\n}\nvoid Engine::broadcast(EngineEvent *event) {\n\t\/* assume iterators may be invalidated during event processing, because new items may be added *\/\n\t\/* note that entities may be set to killed, but cannot be removed from the list (they are only flagged) *\/\n\n\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\tEntity *entity = entities[i];\n\t\tif (!entity->isKilled()) entity->event_received(event);\n\t}\n}\nvoid Engine::quit(void) {\n\tmust_quit = true;\n}\nbool Engine::step(void) {\n\tif (must_quit) return false;\n\tif (first_step) {clock.restart();first_step=false;}\n\tdraw();\n\tcompute_physics();\n\tdestroy_flagged();\n\treturn !must_quit;\n}\nvoid draw_score(RenderTarget &target, Font &ft, int score, Color color, Vector2d pos) {\n\tText text;\n\tchar sscore[256];\n\tsprintf(sscore, \"%d\", score);\n\ttext.setCharacterSize(128);\n\ttext.setString(sscore);\n\ttext.setColor(color);\n\ttext.setPosition(Vector2f(pos.x, pos.y));\n\ttext.setFont(ft);\n\n\ttarget.draw(text);\n}\nvoid Engine::draw(void) {\n\tVector2d scorepos;\n\tscorepos.x = 16;\n\tscorepos.y = 16;\n\twindow.clear();\n\twindow.draw(background);\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\t(*it)->draw(window);\n\n\t\tif (Player *pl = dynamic_cast((*it))) {\n\t\t\tdraw_score(window, score_font, pl->getScore(), pl->getColor(), scorepos);\n\t\t\tscorepos.x += 384+16;\n\t\t}\n\t}\n\twindow.display();\n}\nstatic double getEntityRadius(Entity *a) {\n\treturn a->getSize().x\/2;\n}\nstatic DoubleRect getEntityBoundingRectangle(Entity *a) {\n\tVector2d pos = a->position;\n\tVector2d size = a->getSize();\n\tDoubleRect r;\n\tr.left = pos.x;\n\tr.top = pos.y;\n\tr.width = size.x;\n\tr.height = size.y;\n\treturn r;\n}\nstatic Circle getEntityCircle(Entity *a) {\n\tCircle circle;\n\tcircle.filled = true;\n\tcircle.center = a->position;\n\tcircle.radius = getEntityRadius(a);\n\treturn circle;\n}\n\/* Note: Dynamic entities must be circle-shaped *\/\nstatic bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b) {\n\tif (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_RECTANGLE) {\n\t\tGeomRectangle gr;\n\t\tgr.filled = (b != engine->getMapBoundariesEntity());\n\t\tgr.r = getEntityBoundingRectangle(b);\n\t\treturn moveCircleToRectangle(getEntityRadius(a), ctx, gr);\n\t} else if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_CIRCLE) {\n\t\treturn moveCircleToCircle(getEntityRadius(a), ctx, getEntityCircle(b));\n\t} else {\n\t\treturn false;\n\t}\n}\nbool moveCircleToRectangle(double radius, MoveContext &ctx, const DoubleRect &r);\nbool moveCircleToCircle(double radius, MoveContext &ctx, const Circle &colli);\n\nstatic bool quasi_equals(double a, double b) {\n\treturn fabs(a-b) <= 1e-3*(fabs(a)+fabs(b));\n}\nvoid Engine::compute_physics(void) {\n\tInt64 tm = clock.getElapsedTime().asMicroseconds();\n\tif (tm == 0) return;\n\tclock.restart();\n\tfor(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) {\n\t\tEntity *entity = (*it);\n\t\tif (entity->isKilled()) continue;\n\t\tVector2d movement = entity->movement(tm);\n\t\tVector2d old_speed = movement;\n\t\told_speed.x \/= tm;\n\t\told_speed.y \/= tm;\n\t\tSegment vect;\n\t\tvect.pt1 = entity->position;\n\t\tvect.pt2 = vect.pt1 + movement;\n\t\tif ((fabs(movement.x)+fabs(movement.y)) < 1e-4) continue;\n\t\tMoveContext ctx(IT_GHOST, vect);\n\t\tfor(int pass=0; pass < 2; ++pass)\n\t\tfor (EntitiesIterator itc=entities.begin(); itc != entities.end(); ++itc) {\n\t\t\tEntity *centity = *itc;\n\t\t\tif (centity->isKilled()) continue;\n\t\t\tif (entity->isKilled()) break;\n\t\t\tif (centity == entity) continue;\n\t\t\tctx.interaction = IT_GHOST;\n\t\t\tMoveContext ctxtemp = ctx;\n\t\t\tif (interacts(this, ctxtemp, entity, centity)) {\n\t\t\t\tif (entity->isKilled() || centity->isKilled()) continue;\n\t\t\t\tCollisionEvent e;\n\t\t\t\te.type = COLLIDE_EVENT;\n\t\t\t\te.first = entity;\n\t\t\t\te.second = centity;\n\t\t\t\te.interaction = IT_GHOST; \/* default interaction type *\/\n\t\t\t\tbroadcast(&e); \/* should set e.interaction *\/\n\t\t\t\tctx.interaction = e.interaction;\n\t\t\t\tif (pass == 1 && ctx.interaction != IT_GHOST) {\n\t\t\t\t\t\/* On second interaction in the same frame, cancel movement *\/\n\t\t\t\t\tctx.vect.pt2 = ctx.vect.pt1 = entity->position;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tinteracts(this, ctx, entity, centity);\n\t\t\t}\n\t\t}\n\t\tif (entity->isKilled()) continue;\n\t\tvect = ctx.vect;\n\t\tCompletedMovementEvent e;\n\t\te.type = COMPLETED_MOVEMENT_EVENT;\n\t\te.entity = entity;\n\t\te.position = vect.pt2;\n\t\tVector2d new_speed = ctx.nmove;\n\t\tnew_speed.x \/= tm;\n\t\tnew_speed.y \/= tm;\n\t\tif (quasi_equals(old_speed.x, new_speed.x) && quasi_equals(old_speed.y, new_speed.y)) {\n\t\t\te.new_speed = old_speed;\n\t\t\te.has_new_speed = false;\n\t\t} else {\n\t\t\te.new_speed = new_speed;\n\t\t\te.has_new_speed = true;\n\t\t}\n\t\tbroadcast(&e);\n\t}\n}\nvoid Engine::destroy_flagged(void) {\n\tbool some_got_deleted;\n\tdo {\n\t\tsome_got_deleted = false;\n\t\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\t\tEntity *entity = entities[i];\n\t\t\tif (entity->isKilled()) {\n\t\t\t\tsome_got_deleted = true;\n\t\t\t\tEntityDestroyedEvent e;\n\t\t\t\te.type = ENTITY_DESTROYED_EVENT;\n\t\t\t\te.entity = entity;\n\t\t\t\tbroadcast(&e);\n\t\t\t\tentities.erase(entities.begin()+i);\n\t\t\t\tdelete entity;\n\t\t\t\t--i;\n\t\t\t}\n\t\t}\n\t} while(some_got_deleted);\n#if 0\n\tif (some_got_deleted) fprintf(stderr, \"[now, I'm going to physically destroy things]\\n\");\n\tfor(size_t i=0; i < entities.size(); ++i) {\n\t\tEntity *entity = entities[i];\n\t\tif (entity->isKilled()) {\n\t\t\tentities.erase(entities.begin()+i);\n\t\t\tdelete entity;\n\t\t\t--i;\n\t\t}\n\t}\n\tif (some_got_deleted) fprintf(stderr, \"[\/physically destroyed things]\\n\");\n#endif\n}\n\n<|endoftext|>"} {"text":"\/\/ Regression test for\n\/\/ https:\/\/bugs.llvm.org\/show_bug.cgi?id=32434\n\n\/\/ RUN: %clangxx_asan -fexceptions -O0 %s -o %t\n\/\/ RUN: %run %t\n\n#include \n#include \n#include \n\nnamespace {\n\n\/\/ Not instrumented because std::rethrow_exception is a [[noreturn]] function,\n\/\/ for which the compiler would emit a call to __asan_handle_no_return which\n\/\/ unpoisons the stack.\n\/\/ We emulate here some code not compiled with asan. This function is not\n\/\/ [[noreturn]] because the scenario we're emulating doesn't always throw. If it\n\/\/ were [[noreturn]], the calling code would emit a call to\n\/\/ __asan_handle_no_return.\nvoid __attribute__((no_sanitize(\"address\")))\nuninstrumented_rethrow_exception(std::exception_ptr const &exc_ptr) {\n std::rethrow_exception(exc_ptr);\n}\n\nchar *poisoned1;\nchar *poisoned2;\n\n\/\/ Create redzones for stack variables in shadow memory and call\n\/\/ std::rethrow_exception which should unpoison the entire stack.\nvoid create_redzones_and_throw(std::exception_ptr const &exc_ptr) {\n char a[100];\n poisoned1 = a - 1;\n poisoned2 = a + sizeof(a);\n assert(__asan_address_is_poisoned(poisoned1));\n assert(__asan_address_is_poisoned(poisoned2));\n uninstrumented_rethrow_exception(exc_ptr);\n}\n\n} \/\/ namespace\n\n\/\/ Check that std::rethrow_exception is intercepted by asan and the interception\n\/\/ unpoisons the stack.\n\/\/ If std::rethrow_exception is NOT intercepted, then calls to this function\n\/\/ from instrumented code will still unpoison the stack because\n\/\/ std::rethrow_exception is a [[noreturn]] function and any [[noreturn]]\n\/\/ function call will be instrumented with __asan_handle_no_return.\n\/\/ However, calls to std::rethrow_exception from UNinstrumented code will not\n\/\/ unpoison the stack, so we need to intercept std::rethrow_exception to\n\/\/ unpoison the stack.\nint main() {\n \/\/ In some implementations of std::make_exception_ptr, e.g. libstdc++ prior to\n \/\/ gcc 7, this function calls __cxa_throw. The __cxa_throw is intercepted by\n \/\/ asan to unpoison the entire stack; since this test essentially tests that\n \/\/ the stack is unpoisoned by a call to std::rethrow_exception, we need to\n \/\/ generate the exception_ptr BEFORE we have the local variables poison the\n \/\/ stack.\n std::exception_ptr my_exception_ptr = std::make_exception_ptr(\"up\");\n\n try {\n create_redzones_and_throw(my_exception_ptr);\n } catch(char const *) {\n assert(!__asan_region_is_poisoned(poisoned1, poisoned2 - poisoned1 + 1));\n }\n}\nMark intercept-rethrow-exception.cc as XFAIL on NetBSD\/\/ Regression test for\n\/\/ https:\/\/bugs.llvm.org\/show_bug.cgi?id=32434\n\n\/\/ RUN: %clangxx_asan -fexceptions -O0 %s -o %t\n\/\/ RUN: %run %t\n\n\/\/ The current implementation of this functionality requires special\n\/\/ combination of libraries that are not used by default on NetBSD\n\/\/ XFAIL: netbsd\n\n#include \n#include \n#include \n\nnamespace {\n\n\/\/ Not instrumented because std::rethrow_exception is a [[noreturn]] function,\n\/\/ for which the compiler would emit a call to __asan_handle_no_return which\n\/\/ unpoisons the stack.\n\/\/ We emulate here some code not compiled with asan. This function is not\n\/\/ [[noreturn]] because the scenario we're emulating doesn't always throw. If it\n\/\/ were [[noreturn]], the calling code would emit a call to\n\/\/ __asan_handle_no_return.\nvoid __attribute__((no_sanitize(\"address\")))\nuninstrumented_rethrow_exception(std::exception_ptr const &exc_ptr) {\n std::rethrow_exception(exc_ptr);\n}\n\nchar *poisoned1;\nchar *poisoned2;\n\n\/\/ Create redzones for stack variables in shadow memory and call\n\/\/ std::rethrow_exception which should unpoison the entire stack.\nvoid create_redzones_and_throw(std::exception_ptr const &exc_ptr) {\n char a[100];\n poisoned1 = a - 1;\n poisoned2 = a + sizeof(a);\n assert(__asan_address_is_poisoned(poisoned1));\n assert(__asan_address_is_poisoned(poisoned2));\n uninstrumented_rethrow_exception(exc_ptr);\n}\n\n} \/\/ namespace\n\n\/\/ Check that std::rethrow_exception is intercepted by asan and the interception\n\/\/ unpoisons the stack.\n\/\/ If std::rethrow_exception is NOT intercepted, then calls to this function\n\/\/ from instrumented code will still unpoison the stack because\n\/\/ std::rethrow_exception is a [[noreturn]] function and any [[noreturn]]\n\/\/ function call will be instrumented with __asan_handle_no_return.\n\/\/ However, calls to std::rethrow_exception from UNinstrumented code will not\n\/\/ unpoison the stack, so we need to intercept std::rethrow_exception to\n\/\/ unpoison the stack.\nint main() {\n \/\/ In some implementations of std::make_exception_ptr, e.g. libstdc++ prior to\n \/\/ gcc 7, this function calls __cxa_throw. The __cxa_throw is intercepted by\n \/\/ asan to unpoison the entire stack; since this test essentially tests that\n \/\/ the stack is unpoisoned by a call to std::rethrow_exception, we need to\n \/\/ generate the exception_ptr BEFORE we have the local variables poison the\n \/\/ stack.\n std::exception_ptr my_exception_ptr = std::make_exception_ptr(\"up\");\n\n try {\n create_redzones_and_throw(my_exception_ptr);\n } catch(char const *) {\n assert(!__asan_region_is_poisoned(poisoned1, poisoned2 - poisoned1 + 1));\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \"player.h\"\n#include \"matrix.h\"\n#include \"math.h\"\n\nnamespace konstructs {\n\n using namespace Eigen;\n using nonstd::nullopt;\n\n static float CAMERA_OFFSET = 0.5f;\n static Vector3f CAMERA_OFFSET_VECTOR = Vector3f(0, CAMERA_OFFSET, 0);\n\n Player::Player(const int _id, const Vector3f _position, const float _rx,\n const float _ry):\n id(_id), position(_position), mrx(_rx), mry(_ry), flying(false), dy(0) {}\n\n Matrix4f Player::direction() const {\n return (Affine3f(AngleAxisf(mrx, Vector3f::UnitX())) *\n Affine3f(AngleAxisf(mry, Vector3f::UnitY()))).matrix();\n }\n\n Matrix4f Player::translation() const {\n return (Affine3f(Translation3f(position)) *\n Affine3f(AngleAxisf(-mry, Vector3f::UnitY())) *\n Affine3f(AngleAxisf(-mrx, Vector3f::UnitX()))).matrix();\n }\n\n Matrix4f Player::view() const {\n return (Affine3f(AngleAxisf(mrx, Vector3f::UnitX())) *\n Affine3f(AngleAxisf(mry, Vector3f::UnitY())) *\n Affine3f(Translation3f(-camera()))).matrix();\n }\n\n Vector3f Player::camera() const {\n return position + CAMERA_OFFSET_VECTOR;\n }\n\n Vector3f Player::camera_direction() const {\n float m = cosf(mrx);\n Vector3f vec(cosf(mry - (M_PI \/ 2.0f)) * m, -sinf(mrx), sinf(mry - (M_PI \/ 2.0f)) * m);\n vec.normalize();\n return vec;\n }\n\n Vector3f Player::update_position(int sz, int sx, float dt,\n const World &world, const BlockData &blocks,\n const float near_distance, const bool jump) {\n float vx = 0, vy = 0, vz = 0;\n if (!sz && !sx) { \/\/ Not mowing in X or Z\n vx = 0;\n vz = 0;\n } else { \/\/ Moving in X or Z\n\n\n float strafe = atan2f(sz, sx);\n\n if (flying) {\n float m = cosf(mrx);\n float y = sinf(mrx);\n if (sx) {\n if (!sz) {\n y = 0;\n }\n m = 1;\n }\n if (sz < 0) {\n y = -y;\n }\n vx = cosf(mry + strafe) * m;\n vy = y;\n vz = sinf(mry + strafe) * m;\n } else {\n vx = cosf(mry + strafe);\n vy = 0;\n vz = sinf(mry + strafe);\n }\n }\n\n if(jump) {\n if(flying) {\n \/\/ Jump in flight moves upward at constant speed\n vy = 1;\n } else if(dy == 0) {\n \/\/ Jump when walking changes the acceleration upwards to 8\n dy = 8;\n } else {\n \/\/ Get middle of block\n Vector3i iPos((int)(position[0] + 0.5f), (int)(position[1]), (int)(position[2] + 0.5f));\n ChunkData *chunk = world.chunk_at(iPos).get();\n if(blocks.state[chunk->get(iPos)] == STATE_LIQUID) {\n dy = 5.5;\n }\n }\n }\n\n float speed = flying ? 20 : 5;\n int estimate =\n roundf(sqrtf(powf(vx * speed, 2) +\n powf(vy * speed + std::abs(dy) * 2, 2) +\n powf(vz * speed, 2)) * dt * 8);\n int step = std::max(8, estimate);\n float ut = dt \/ step;\n vx = vx * ut * speed;\n vy = vy * ut * speed;\n vz = vz * ut * speed;\n for (int i = 0; i < step; i++) {\n if (flying) {\n \/\/ When flying upwards acceleration is constant i.e. not falling\n dy = 0;\n } else {\n \/\/ Calculate \"gravity\" by decreasing upwards acceleration\n dy -= ut * 25;\n dy = std::max(dy, -250.0f);\n }\n position += Vector3f(vx, vy + dy * ut, vz);\n if (collide(world, blocks, near_distance)) {\n dy = 0;\n }\n }\n if (position[1] < 0) {\n position[1] = 2;\n }\n return position;\n }\n\n optional> Player::looking_at(const World &world,\n const BlockData &blocks) const {\n optional> block(nullopt);\n float best = 0;\n const Vector3f v = camera_direction();\n const Vector3f camera_position = camera();\n int p = chunked(camera_position[0]);\n int q = chunked(camera_position[2]);\n int k = chunked(camera_position[1]);\n const auto &atAndAround = world.atAndAround({p, q, k});\n for (const auto &chunk: atAndAround) {\n const auto &seen = chunk->get(camera_position, v, 8.0f, blocks);\n if (seen) {\n auto h = seen->second;\n float d = sqrtf(powf(h.position[0] - camera_position[0], 2) +\n powf(h.position[1] - camera_position[1], 2) +\n powf(h.position[2] - camera_position[2], 2));\n if (best == 0 || d < best) {\n best = d;\n block = seen;\n }\n }\n }\n return block;\n }\n\n void Player::rotate_x(float speed) {\n mrx += speed;\n mrx = std::max(mrx, -((float)M_PI \/ 2.0f));\n mrx = std::min(mrx, ((float)M_PI \/ 2.0f));\n }\n\n void Player::rotate_y(float speed) {\n mry += speed;\n if (mry < 0) {\n mry += (M_PI * 2);\n }\n if (mry >= (M_PI * 2)){\n mry -= (M_PI * 2);\n }\n }\n\n void Player::fly() {\n flying = !flying;\n }\n\n float Player::rx() {\n return mrx;\n }\n\n float Player::ry() {\n return mry;\n }\n\n int Player::collide(const World &world, const BlockData &blocks, const float near_distance) {\n int result = 0;\n float x = position[0];\n float y = position[1];\n float z = position[2];\n int height = 2;\n int p = chunked(x);\n int q = chunked(z);\n int k = chunked(y);\n int nx = roundf(x);\n int ny = roundf(y);\n int nz = roundf(z);\n float px = x - nx;\n float py = y - ny;\n float pz = z - nz;\n float pad = near_distance * 2;\n int r = 1;\n for (int dp = -r; dp <= r; dp++) {\n for (int dq = -r; dq <= r; dq++) {\n for (int dk = -r; dk <= r; dk++) {\n try {\n ChunkData *chunk = world.chunk(Vector3i(p + dp, q + dq, k + dk)).get();\n if (blocks.is_obstacle[chunk->get(Vector3i(nx, ny-1, nz))]) {\n position[1] += 1.0f;\n return 1;\n }\n for (int dy = 0; dy < height; dy++) {\n if (px < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx - 1, ny - dy, nz))]) {\n position[0] = nx - pad;\n }\n if (px > pad && blocks.is_obstacle[chunk->get(Vector3i(nx + 1, ny - dy, nz))]) {\n position[0] = nx + pad;\n }\n if (py < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy - 1, nz))]) {\n position[1] = ny - pad;\n result = 1;\n }\n if (py > (pad - CAMERA_OFFSET) && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy + 1, nz))]) {\n position[1] = ny + pad - CAMERA_OFFSET;\n result = 1;\n }\n if (pz < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy, nz - 1))]) {\n position[2] = nz - pad;\n }\n if (pz > pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy, nz + 1))]) {\n position[2] = nz + pad;\n }\n }\n } catch(std::out_of_range e) {\n continue;\n }\n }\n }\n }\n\n return result;\n }\n};\nFix indentation#include \n#include \"player.h\"\n#include \"matrix.h\"\n#include \"math.h\"\n\nnamespace konstructs {\n\n using namespace Eigen;\n using nonstd::nullopt;\n\n static float CAMERA_OFFSET = 0.5f;\n static Vector3f CAMERA_OFFSET_VECTOR = Vector3f(0, CAMERA_OFFSET, 0);\n\n Player::Player(const int _id, const Vector3f _position, const float _rx,\n const float _ry):\n id(_id), position(_position), mrx(_rx), mry(_ry), flying(false), dy(0) {}\n\n Matrix4f Player::direction() const {\n return (Affine3f(AngleAxisf(mrx, Vector3f::UnitX())) *\n Affine3f(AngleAxisf(mry, Vector3f::UnitY()))).matrix();\n }\n\n Matrix4f Player::translation() const {\n return (Affine3f(Translation3f(position)) *\n Affine3f(AngleAxisf(-mry, Vector3f::UnitY())) *\n Affine3f(AngleAxisf(-mrx, Vector3f::UnitX()))).matrix();\n }\n\n Matrix4f Player::view() const {\n return (Affine3f(AngleAxisf(mrx, Vector3f::UnitX())) *\n Affine3f(AngleAxisf(mry, Vector3f::UnitY())) *\n Affine3f(Translation3f(-camera()))).matrix();\n }\n\n Vector3f Player::camera() const {\n return position + CAMERA_OFFSET_VECTOR;\n }\n\n Vector3f Player::camera_direction() const {\n float m = cosf(mrx);\n Vector3f vec(cosf(mry - (M_PI \/ 2.0f)) * m, -sinf(mrx), sinf(mry - (M_PI \/ 2.0f)) * m);\n vec.normalize();\n return vec;\n }\n\n Vector3f Player::update_position(int sz, int sx, float dt,\n const World &world, const BlockData &blocks,\n const float near_distance, const bool jump) {\n float vx = 0, vy = 0, vz = 0;\n if (!sz && !sx) { \/\/ Not mowing in X or Z\n vx = 0;\n vz = 0;\n } else { \/\/ Moving in X or Z\n\n\n float strafe = atan2f(sz, sx);\n\n if (flying) {\n float m = cosf(mrx);\n float y = sinf(mrx);\n if (sx) {\n if (!sz) {\n y = 0;\n }\n m = 1;\n }\n if (sz < 0) {\n y = -y;\n }\n vx = cosf(mry + strafe) * m;\n vy = y;\n vz = sinf(mry + strafe) * m;\n } else {\n vx = cosf(mry + strafe);\n vy = 0;\n vz = sinf(mry + strafe);\n }\n }\n\n if(jump) {\n if(flying) {\n \/\/ Jump in flight moves upward at constant speed\n vy = 1;\n } else if(dy == 0) {\n \/\/ Jump when walking changes the acceleration upwards to 8\n dy = 8;\n } else {\n \/\/ Get middle of block\n Vector3i iPos((int)(position[0] + 0.5f), (int)(position[1]), (int)(position[2] + 0.5f));\n ChunkData *chunk = world.chunk_at(iPos).get();\n if(blocks.state[chunk->get(iPos)] == STATE_LIQUID) {\n dy = 5.5;\n }\n }\n }\n\n float speed = flying ? 20 : 5;\n int estimate =\n roundf(sqrtf(powf(vx * speed, 2) +\n powf(vy * speed + std::abs(dy) * 2, 2) +\n powf(vz * speed, 2)) * dt * 8);\n int step = std::max(8, estimate);\n float ut = dt \/ step;\n vx = vx * ut * speed;\n vy = vy * ut * speed;\n vz = vz * ut * speed;\n for (int i = 0; i < step; i++) {\n if (flying) {\n \/\/ When flying upwards acceleration is constant i.e. not falling\n dy = 0;\n } else {\n \/\/ Calculate \"gravity\" by decreasing upwards acceleration\n dy -= ut * 25;\n dy = std::max(dy, -250.0f);\n }\n position += Vector3f(vx, vy + dy * ut, vz);\n if (collide(world, blocks, near_distance)) {\n dy = 0;\n }\n }\n if (position[1] < 0) {\n position[1] = 2;\n }\n return position;\n }\n\n optional> Player::looking_at(const World &world,\n const BlockData &blocks) const {\n optional> block(nullopt);\n float best = 0;\n const Vector3f v = camera_direction();\n const Vector3f camera_position = camera();\n int p = chunked(camera_position[0]);\n int q = chunked(camera_position[2]);\n int k = chunked(camera_position[1]);\n const auto &atAndAround = world.atAndAround({p, q, k});\n for (const auto &chunk: atAndAround) {\n const auto &seen = chunk->get(camera_position, v, 8.0f, blocks);\n if (seen) {\n auto h = seen->second;\n float d = sqrtf(powf(h.position[0] - camera_position[0], 2) +\n powf(h.position[1] - camera_position[1], 2) +\n powf(h.position[2] - camera_position[2], 2));\n if (best == 0 || d < best) {\n best = d;\n block = seen;\n }\n }\n }\n return block;\n }\n\n void Player::rotate_x(float speed) {\n mrx += speed;\n mrx = std::max(mrx, -((float)M_PI \/ 2.0f));\n mrx = std::min(mrx, ((float)M_PI \/ 2.0f));\n }\n\n void Player::rotate_y(float speed) {\n mry += speed;\n if (mry < 0) {\n mry += (M_PI * 2);\n }\n if (mry >= (M_PI * 2)){\n mry -= (M_PI * 2);\n }\n }\n\n void Player::fly() {\n flying = !flying;\n }\n\n float Player::rx() {\n return mrx;\n }\n\n float Player::ry() {\n return mry;\n }\n\n int Player::collide(const World &world, const BlockData &blocks, const float near_distance) {\n int result = 0;\n float x = position[0];\n float y = position[1];\n float z = position[2];\n int height = 2;\n int p = chunked(x);\n int q = chunked(z);\n int k = chunked(y);\n int nx = roundf(x);\n int ny = roundf(y);\n int nz = roundf(z);\n float px = x - nx;\n float py = y - ny;\n float pz = z - nz;\n float pad = near_distance * 2;\n int r = 1;\n for (int dp = -r; dp <= r; dp++) {\n for (int dq = -r; dq <= r; dq++) {\n for (int dk = -r; dk <= r; dk++) {\n try {\n ChunkData *chunk = world.chunk(Vector3i(p + dp, q + dq, k + dk)).get();\n if (blocks.is_obstacle[chunk->get(Vector3i(nx, ny-1, nz))]) {\n position[1] += 1.0f;\n return 1;\n }\n for (int dy = 0; dy < height; dy++) {\n if (px < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx - 1, ny - dy, nz))]) {\n position[0] = nx - pad;\n }\n if (px > pad && blocks.is_obstacle[chunk->get(Vector3i(nx + 1, ny - dy, nz))]) {\n position[0] = nx + pad;\n }\n if (py < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy - 1, nz))]) {\n position[1] = ny - pad;\n result = 1;\n }\n if (py > (pad - CAMERA_OFFSET) && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy + 1, nz))]) {\n position[1] = ny + pad - CAMERA_OFFSET;\n result = 1;\n }\n if (pz < -pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy, nz - 1))]) {\n position[2] = nz - pad;\n }\n if (pz > pad && blocks.is_obstacle[chunk->get(Vector3i(nx, ny - dy, nz + 1))]) {\n position[2] = nz + pad;\n }\n }\n } catch(std::out_of_range e) {\n continue;\n }\n }\n }\n }\n\n return result;\n }\n};\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TGSplitter.cxx,v 1.10 2005\/11\/17 19:09:28 rdm Exp $\n\/\/ Author: Fons Rademakers 6\/09\/2000\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGSplitter, TGVSplitter and TGHSplitter \/\/\n\/\/ \/\/\n\/\/ A splitter allows the frames left and right or above and below of \/\/\n\/\/ it to be resized. The frame to be resized must have the kFixedWidth \/\/\n\/\/ or kFixedHeight property set. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGSplitter.h\"\n#include \"TGPicture.h\"\n#include \"Riostream.h\"\n\n\nClassImp(TGSplitter)\nClassImp(TGVSplitter)\nClassImp(TGHSplitter)\n\n\n\/\/______________________________________________________________________________\nTGSplitter::TGSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGFrame(p, w, h, options, back)\n{\n \/\/ Create a splitter.\n\n fDragging = kFALSE;\n fEditDisabled = kTRUE;\n}\n\n\n\/\/______________________________________________________________________________\nTGVSplitter::TGVSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGSplitter(p, w, h, options, back)\n{\n \/\/ Create a vertical splitter.\n\n fSplitCursor = kNone;\n fSplitterPic = fClient->GetPicture(\"splitterv.xpm\");\n\n if (!fSplitterPic)\n Error(\"TGVSplitter\", \"splitterv.xpm not found\");\n\n if (p && !p->InheritsFrom(TGCompositeFrame::Class())) {\n Error(\"TGVSplitter\", \"parent must inherit from a TGCompositeFrame\");\n return;\n }\n if (p && !(((TGCompositeFrame*)p)->GetOptions() & kHorizontalFrame)) {\n Error(\"TGVSplitter\", \"parent must have a horizontal layout manager\");\n return;\n }\n\n fSplitCursor = gVirtualX->CreateCursor(kArrowHor);\n fFrame = 0;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, kNone);\n\n AddInput(kEnterWindowMask | kLeaveWindowMask);\n}\n\n\/\/______________________________________________________________________________\nTGVSplitter::~TGVSplitter()\n{\n \/\/ Delete vertical slider widget.\n\n if (fSplitterPic) fClient->FreePicture(fSplitterPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::SetFrame(TGFrame *frame, Bool_t left)\n{\n \/\/ Set frame to be resized. If frame is on the left of the splitter\n \/\/ set left to true.\n\n fFrame = frame;\n fLeft = left;\n\n if (!(fFrame->GetOptions() & kFixedWidth))\n Error(\"SetFrame\", \"resize frame must have kFixedWidth option set\");\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleButton(Event_t *event)\n{\n \/\/ Handle mouse button event in vertical splitter.\n\n if (fSplitCursor == kNone) return kTRUE;\n\n if (!fFrame) {\n Error(\"HandleButton\", \"frame to be resized not set\");\n return kTRUE;\n }\n\n if (event->fType == kButtonPress) {\n fStartX = event->fXRoot;\n fDragging = kTRUE;\n\n Int_t x, y;\n gVirtualX->GetWindowSize(fFrame->GetId(), x, y, fFrameWidth, fFrameHeight);\n\n \/\/ get fMin and fMax in root coordinates\n Int_t xroot, yroot;\n UInt_t w, h;\n Window_t wdum;\n gVirtualX->GetWindowSize(fParent->GetId(), x, y, w, h);\n gVirtualX->TranslateCoordinates(fParent->GetParent()->GetId(),\n fClient->GetDefaultRoot()->GetId(),\n x, y, xroot, yroot, wdum);\n fMin = xroot;\n fMax = xroot + w - 2;\n\n \/\/ last argument kFALSE forces all specified events to this window\n gVirtualX->GrabPointer(fId, kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, fSplitCursor,\n kTRUE, kFALSE);\n } else {\n fDragging = kFALSE;\n gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE); \/\/ ungrab pointer\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in vertical splitter.\n\n if (fDragging) {\n Int_t xr = event->fXRoot;\n if (xr > fMax) xr = fMax;\n if (xr < fMin) xr = fMin;\n Int_t delta = xr - fStartX;\n Int_t w = (Int_t) fFrameWidth;\n if (fLeft)\n w += delta;\n else\n w -= delta;\n if (w < 0) w = 0;\n fStartX = xr;\n\n if (delta != 0) {\n fFrameWidth = w;\n fFrame->Resize(fFrameWidth, fFrameHeight);\n\n TGCompositeFrame *p = (TGCompositeFrame *) GetParent();\n p->Layout();\n }\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleCrossing(Event_t *event)\n{\n \/\/ Handle mouse motion event in vertical splitter.\n\n if (event->fType == kEnterNotify)\n gVirtualX->SetCursor(fId, fSplitCursor);\n else\n gVirtualX->SetCursor(fId, kNone);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::DrawBorder()\n{\n \/\/ Draw vertical splitter.\n\n if (fSplitterPic) {\n Int_t posx = (fWidth\/2)-(fSplitterPic->GetWidth()\/2);\n Int_t posy = (fHeight\/2)-(fSplitterPic->GetHeight()\/2);\n fSplitterPic->Draw(fId, GetBckgndGC()(), posx, posy);\n }\n}\n\n\n\/\/______________________________________________________________________________\nTGHSplitter::TGHSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGSplitter(p, w, h, options, back)\n{\n \/\/ Create a horizontal splitter.\n\n fSplitCursor = kNone;\n\n fSplitterPic = fClient->GetPicture(\"splitterh.xpm\");\n\n if (!fSplitterPic)\n Error(\"TGVSplitter\", \"splitterh.xpm not found\");\n\n if (p && !p->InheritsFrom(TGCompositeFrame::Class())) {\n Error(\"TGHSplitter\", \"parent must inherit from a TGCompositeFrame\");\n return;\n }\n if (p && !(((TGCompositeFrame*)p)->GetOptions() & kVerticalFrame)) {\n Error(\"TGVSplitter\", \"parent must have a vertical layout manager\");\n return;\n }\n\n fSplitCursor = gVirtualX->CreateCursor(kArrowVer);\n fFrame = 0;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, kNone);\n\n AddInput(kEnterWindowMask | kLeaveWindowMask);\n}\n\n\/\/______________________________________________________________________________\nTGHSplitter::~TGHSplitter()\n{\n \/\/ Delete vertical slider widget.\n\n if (fSplitterPic) fClient->FreePicture(fSplitterPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::SetFrame(TGFrame *frame, Bool_t above)\n{\n \/\/ Set frame to be resized. If frame is above the splitter\n \/\/ set above to true.\n\n fFrame = frame;\n fAbove = above;\n\n if (!(fFrame->GetOptions() & kFixedHeight))\n Error(\"SetFrame\", \"resize frame must have kFixedHeight option set\");\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleButton(Event_t *event)\n{\n \/\/ Handle mouse button event in horizontal splitter.\n\n if (fSplitCursor == kNone) return kTRUE;\n\n if (!fFrame) {\n Error(\"HandleButton\", \"frame to be resized not set\");\n return kTRUE;\n }\n\n if (event->fType == kButtonPress) {\n fStartY = event->fYRoot;\n fDragging = kTRUE;\n\n Int_t x, y;\n gVirtualX->GetWindowSize(fFrame->GetId(), x, y, fFrameWidth, fFrameHeight);\n\n \/\/ get fMin and fMax in root coordinates\n Int_t xroot, yroot;\n UInt_t w, h;\n Window_t wdum;\n gVirtualX->GetWindowSize(fParent->GetId(), x, y, w, h);\n gVirtualX->TranslateCoordinates(fParent->GetParent()->GetId(),\n fClient->GetDefaultRoot()->GetId(),\n x, y, xroot, yroot, wdum);\n fMin = yroot;\n fMax = yroot + h - 2;\n\n \/\/ last argument kFALSE forces all specified events to this window\n gVirtualX->GrabPointer(fId, kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, fSplitCursor,\n kTRUE, kFALSE);\n } else {\n fDragging = kFALSE;\n gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE); \/\/ ungrab pointer\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in horizontal splitter.\n\n if (fDragging) {\n Int_t yr = event->fYRoot;\n if (yr > fMax) yr = fMax;\n if (yr < fMin) yr = fMin;\n Int_t delta = yr - fStartY;\n Int_t h = (Int_t) fFrameHeight;\n if (fAbove)\n h += delta;\n else\n h -= delta;\n if (h < 0) h = 0;\n fStartY = yr;\n\n if (delta != 0) {\n fFrameHeight = h;\n fFrame->Resize(fFrameWidth, fFrameHeight);\n\n TGCompositeFrame *p = (TGCompositeFrame *) GetParent();\n p->Layout();\n }\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleCrossing(Event_t *event)\n{\n \/\/ Handle mouse motion event in horizontal splitter.\n\n if (event->fType == kEnterNotify)\n gVirtualX->SetCursor(fId, fSplitCursor);\n else\n gVirtualX->SetCursor(fId, kNone);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::DrawBorder()\n{\n \/\/ Draw horizontal splitter.\n\n if (fSplitterPic) {\n Int_t posx = (fWidth\/2)-(fSplitterPic->GetWidth()\/2);\n Int_t posy = (fHeight\/2)-(fSplitterPic->GetHeight()\/2);\n fSplitterPic->Draw(fId, GetBckgndGC()(), posx, posy);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a splitter widget as a C++ statement(s) on output stream out.\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n out << \" TGVSplitter *\";\n out << GetName() <<\" = new TGVSplitter(\"<< fParent->GetName()\n << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n out << \" \" << GetName() << \"->SetFrame(\" << GetFrame()->GetName();\n if (GetLeft()) out << \",kTRUE);\" << endl;\n else out << \",kFALSE);\"<< endl;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a splitter widget as a C++ statement(s) on output stream out.\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n out << \" TGHSplitter *\";\n out << GetName() <<\" = new TGHSplitter(\"<< fParent->GetName()\n << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n out << \" \" << GetName() << \"->SetFrame(\" << GetFrame()->GetName();\n if (GetAbove()) out << \",kTRUE);\" << endl;\n else out << \",kFALSE);\"<< endl;\n}\n- print correct class name in Error message\/\/ @(#)root\/gui:$Name: $:$Id: TGSplitter.cxx,v 1.11 2006\/04\/12 11:11:43 rdm Exp $\n\/\/ Author: Fons Rademakers 6\/09\/2000\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGSplitter, TGVSplitter and TGHSplitter \/\/\n\/\/ \/\/\n\/\/ A splitter allows the frames left and right or above and below of \/\/\n\/\/ it to be resized. The frame to be resized must have the kFixedWidth \/\/\n\/\/ or kFixedHeight property set. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGSplitter.h\"\n#include \"TGPicture.h\"\n#include \"Riostream.h\"\n\n\nClassImp(TGSplitter)\nClassImp(TGVSplitter)\nClassImp(TGHSplitter)\n\n\n\/\/______________________________________________________________________________\nTGSplitter::TGSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGFrame(p, w, h, options, back)\n{\n \/\/ Create a splitter.\n\n fDragging = kFALSE;\n fEditDisabled = kTRUE;\n}\n\n\n\/\/______________________________________________________________________________\nTGVSplitter::TGVSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGSplitter(p, w, h, options, back)\n{\n \/\/ Create a vertical splitter.\n\n fSplitCursor = kNone;\n fSplitterPic = fClient->GetPicture(\"splitterv.xpm\");\n\n if (!fSplitterPic)\n Error(\"TGVSplitter\", \"splitterv.xpm not found\");\n\n if (p && !p->InheritsFrom(TGCompositeFrame::Class())) {\n Error(\"TGVSplitter\", \"parent must inherit from a TGCompositeFrame\");\n return;\n }\n if (p && !(((TGCompositeFrame*)p)->GetOptions() & kHorizontalFrame)) {\n Error(\"TGVSplitter\", \"parent must have a horizontal layout manager\");\n return;\n }\n\n fSplitCursor = gVirtualX->CreateCursor(kArrowHor);\n fFrame = 0;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, kNone);\n\n AddInput(kEnterWindowMask | kLeaveWindowMask);\n}\n\n\/\/______________________________________________________________________________\nTGVSplitter::~TGVSplitter()\n{\n \/\/ Delete vertical slider widget.\n\n if (fSplitterPic) fClient->FreePicture(fSplitterPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::SetFrame(TGFrame *frame, Bool_t left)\n{\n \/\/ Set frame to be resized. If frame is on the left of the splitter\n \/\/ set left to true.\n\n fFrame = frame;\n fLeft = left;\n\n if (!(fFrame->GetOptions() & kFixedWidth))\n Error(\"SetFrame\", \"resize frame must have kFixedWidth option set\");\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleButton(Event_t *event)\n{\n \/\/ Handle mouse button event in vertical splitter.\n\n if (fSplitCursor == kNone) return kTRUE;\n\n if (!fFrame) {\n Error(\"HandleButton\", \"frame to be resized not set\");\n return kTRUE;\n }\n\n if (event->fType == kButtonPress) {\n fStartX = event->fXRoot;\n fDragging = kTRUE;\n\n Int_t x, y;\n gVirtualX->GetWindowSize(fFrame->GetId(), x, y, fFrameWidth, fFrameHeight);\n\n \/\/ get fMin and fMax in root coordinates\n Int_t xroot, yroot;\n UInt_t w, h;\n Window_t wdum;\n gVirtualX->GetWindowSize(fParent->GetId(), x, y, w, h);\n gVirtualX->TranslateCoordinates(fParent->GetParent()->GetId(),\n fClient->GetDefaultRoot()->GetId(),\n x, y, xroot, yroot, wdum);\n fMin = xroot;\n fMax = xroot + w - 2;\n\n \/\/ last argument kFALSE forces all specified events to this window\n gVirtualX->GrabPointer(fId, kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, fSplitCursor,\n kTRUE, kFALSE);\n } else {\n fDragging = kFALSE;\n gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE); \/\/ ungrab pointer\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in vertical splitter.\n\n if (fDragging) {\n Int_t xr = event->fXRoot;\n if (xr > fMax) xr = fMax;\n if (xr < fMin) xr = fMin;\n Int_t delta = xr - fStartX;\n Int_t w = (Int_t) fFrameWidth;\n if (fLeft)\n w += delta;\n else\n w -= delta;\n if (w < 0) w = 0;\n fStartX = xr;\n\n if (delta != 0) {\n fFrameWidth = w;\n fFrame->Resize(fFrameWidth, fFrameHeight);\n\n TGCompositeFrame *p = (TGCompositeFrame *) GetParent();\n p->Layout();\n }\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGVSplitter::HandleCrossing(Event_t *event)\n{\n \/\/ Handle mouse motion event in vertical splitter.\n\n if (event->fType == kEnterNotify)\n gVirtualX->SetCursor(fId, fSplitCursor);\n else\n gVirtualX->SetCursor(fId, kNone);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::DrawBorder()\n{\n \/\/ Draw vertical splitter.\n\n if (fSplitterPic) {\n Int_t posx = (fWidth\/2)-(fSplitterPic->GetWidth()\/2);\n Int_t posy = (fHeight\/2)-(fSplitterPic->GetHeight()\/2);\n fSplitterPic->Draw(fId, GetBckgndGC()(), posx, posy);\n }\n}\n\n\n\/\/______________________________________________________________________________\nTGHSplitter::TGHSplitter(const TGWindow *p, UInt_t w, UInt_t h,\n UInt_t options, ULong_t back) : TGSplitter(p, w, h, options, back)\n{\n \/\/ Create a horizontal splitter.\n\n fSplitCursor = kNone;\n\n fSplitterPic = fClient->GetPicture(\"splitterh.xpm\");\n\n if (!fSplitterPic)\n Error(\"TGHSplitter\", \"splitterh.xpm not found\");\n\n if (p && !p->InheritsFrom(TGCompositeFrame::Class())) {\n Error(\"TGHSplitter\", \"parent must inherit from a TGCompositeFrame\");\n return;\n }\n if (p && !(((TGCompositeFrame*)p)->GetOptions() & kVerticalFrame)) {\n Error(\"TGHSplitter\", \"parent must have a vertical layout manager\");\n return;\n }\n\n fSplitCursor = gVirtualX->CreateCursor(kArrowVer);\n fFrame = 0;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, kNone);\n\n AddInput(kEnterWindowMask | kLeaveWindowMask);\n}\n\n\/\/______________________________________________________________________________\nTGHSplitter::~TGHSplitter()\n{\n \/\/ Delete vertical slider widget.\n\n if (fSplitterPic) fClient->FreePicture(fSplitterPic);\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::SetFrame(TGFrame *frame, Bool_t above)\n{\n \/\/ Set frame to be resized. If frame is above the splitter\n \/\/ set above to true.\n\n fFrame = frame;\n fAbove = above;\n\n if (!(fFrame->GetOptions() & kFixedHeight))\n Error(\"SetFrame\", \"resize frame must have kFixedHeight option set\");\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleButton(Event_t *event)\n{\n \/\/ Handle mouse button event in horizontal splitter.\n\n if (fSplitCursor == kNone) return kTRUE;\n\n if (!fFrame) {\n Error(\"HandleButton\", \"frame to be resized not set\");\n return kTRUE;\n }\n\n if (event->fType == kButtonPress) {\n fStartY = event->fYRoot;\n fDragging = kTRUE;\n\n Int_t x, y;\n gVirtualX->GetWindowSize(fFrame->GetId(), x, y, fFrameWidth, fFrameHeight);\n\n \/\/ get fMin and fMax in root coordinates\n Int_t xroot, yroot;\n UInt_t w, h;\n Window_t wdum;\n gVirtualX->GetWindowSize(fParent->GetId(), x, y, w, h);\n gVirtualX->TranslateCoordinates(fParent->GetParent()->GetId(),\n fClient->GetDefaultRoot()->GetId(),\n x, y, xroot, yroot, wdum);\n fMin = yroot;\n fMax = yroot + h - 2;\n\n \/\/ last argument kFALSE forces all specified events to this window\n gVirtualX->GrabPointer(fId, kButtonPressMask | kButtonReleaseMask |\n kPointerMotionMask, kNone, fSplitCursor,\n kTRUE, kFALSE);\n } else {\n fDragging = kFALSE;\n gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE); \/\/ ungrab pointer\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in horizontal splitter.\n\n if (fDragging) {\n Int_t yr = event->fYRoot;\n if (yr > fMax) yr = fMax;\n if (yr < fMin) yr = fMin;\n Int_t delta = yr - fStartY;\n Int_t h = (Int_t) fFrameHeight;\n if (fAbove)\n h += delta;\n else\n h -= delta;\n if (h < 0) h = 0;\n fStartY = yr;\n\n if (delta != 0) {\n fFrameHeight = h;\n fFrame->Resize(fFrameWidth, fFrameHeight);\n\n TGCompositeFrame *p = (TGCompositeFrame *) GetParent();\n p->Layout();\n }\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGHSplitter::HandleCrossing(Event_t *event)\n{\n \/\/ Handle mouse motion event in horizontal splitter.\n\n if (event->fType == kEnterNotify)\n gVirtualX->SetCursor(fId, fSplitCursor);\n else\n gVirtualX->SetCursor(fId, kNone);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::DrawBorder()\n{\n \/\/ Draw horizontal splitter.\n\n if (fSplitterPic) {\n Int_t posx = (fWidth\/2)-(fSplitterPic->GetWidth()\/2);\n Int_t posy = (fHeight\/2)-(fSplitterPic->GetHeight()\/2);\n fSplitterPic->Draw(fId, GetBckgndGC()(), posx, posy);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGVSplitter::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a splitter widget as a C++ statement(s) on output stream out.\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n out << \" TGVSplitter *\";\n out << GetName() <<\" = new TGVSplitter(\"<< fParent->GetName()\n << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n out << \" \" << GetName() << \"->SetFrame(\" << GetFrame()->GetName();\n if (GetLeft()) out << \",kTRUE);\" << endl;\n else out << \",kFALSE);\"<< endl;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHSplitter::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a splitter widget as a C++ statement(s) on output stream out.\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n out << \" TGHSplitter *\";\n out << GetName() <<\" = new TGHSplitter(\"<< fParent->GetName()\n << \",\" << GetWidth() << \",\" << GetHeight();\n\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n out << \" \" << GetName() << \"->SetFrame(\" << GetFrame()->GetName();\n if (GetAbove()) out << \",kTRUE);\" << endl;\n else out << \",kFALSE);\"<< endl;\n}\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#if VSNRAY_COMMON_HAVE_PNG\n#include \n#endif\n\n#include \"cfile.h\"\n#include \"png_image.h\"\n\nnamespace visionaray\n{\n\n#if VSNRAY_COMMON_HAVE_PNG\nstruct png_read_context\n{\n png_structp png;\n png_infop info;\n\n png_read_context()\n : png(0)\n , info(0)\n {\n }\n\n ~png_read_context()\n {\n png_destroy_read_struct(&png, &info, 0);\n }\n};\n\nstruct png_write_context\n{\n png_structp png;\n png_infop info;\n png_bytep row;\n\n png_write_context()\n : png(0)\n , info(0)\n , row(0)\n {\n }\n\n ~png_write_context()\n {\n png_free_data(png, info, PNG_FREE_ALL, -1);\n png_destroy_write_struct(&png, &info);\n\n delete[] row;\n }\n};\n\nstatic void png_error_callback(png_structp png_ptr, png_const_charp msg)\n{\n fprintf(stderr, \"PNG error: \\\"%s\\\"\\n\", msg);\n\n longjmp(png_jmpbuf(png_ptr), 1);\n}\n\n\nstatic void png_warning_callback(png_structp \/*png_ptr*\/, png_const_charp \/*msg*\/)\n{\n \/\/ TODO\n}\n\nstatic int png_num_components(int color_type)\n{\n switch (color_type)\n {\n case PNG_COLOR_TYPE_GRAY:\n return 1;\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n return 2;\n case PNG_COLOR_TYPE_RGB:\n return 3;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n return 4;\n }\n\n return -1;\n}\n#endif\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ png_image\n\/\/\n\npng_image::png_image(int width, int height, pixel_format format, uint8_t const* data)\n : image_base(width, height, format, data)\n{\n}\n\nbool png_image::load(std::string const& filename)\n{\n#if VSNRAY_COMMON_HAVE_PNG\n cfile file(filename.c_str(), \"r\");\n\n if (!file.good())\n {\n return false;\n }\n\n\n png_read_context context;\n\n context.png = png_create_read_struct(\n PNG_LIBPNG_VER_STRING,\n 0 \/*user-data*\/,\n png_error_callback,\n png_warning_callback\n );\n\n if (context.png == 0)\n {\n return false;\n }\n\n context.info = png_create_info_struct(context.png);\n\n if (context.info == 0)\n {\n return false;\n }\n\n\n png_init_io(context.png, file.get());\n\n png_read_info(context.png, context.info);\n\n png_uint_32 w = 0;\n png_uint_32 h = 0;\n int bit_depth = 0;\n int color_type = 0;\n\n png_get_IHDR(context.png, context.info, &w, &h, &bit_depth, &color_type, 0, 0, 0);\n\n\n \/\/ expand paletted images to RGB\n if (color_type == PNG_COLOR_TYPE_PALETTE)\n {\n png_set_expand(context.png);\n }\n\n png_read_update_info(context.png, context.info);\n\n w = png_get_image_width(context.png, context.info);\n h = png_get_image_height(context.png, context.info);\n bit_depth = png_get_bit_depth(context.png, context.info);\n color_type = png_get_color_type(context.png, context.info);\n\n \/\/ Only support 8-bit and 16-bit per pixel images\n if (bit_depth != 8 && bit_depth != 16)\n {\n return false;\n }\n\n auto num_components = png_num_components(color_type);\n\n switch (num_components)\n {\n case 3:\n format_ = bit_depth == 8 ? PF_RGB8 : PF_RGB16UI;\n break;\n\n case 4:\n format_ = bit_depth == 8 ? PF_RGBA8 : PF_RGBA16UI;\n break;\n\n default:\n format_ = PF_UNSPECIFIED;\n return false;\n }\n\n auto pitch = png_get_rowbytes(context.png, context.info);\n\n data_.resize(pitch * h);\n\n for (png_uint_32 y = 0; y < h; ++y)\n {\n png_bytep row = data_.data() + (h - 1) * pitch - y * pitch;\n png_read_rows(context.png, &row, nullptr, 1);\n }\n\n png_read_end(context.png, context.info);\n\n width_ = static_cast(w);\n height_ = static_cast(h);\n\n return true;\n#else\n VSNRAY_UNUSED(filename);\n\n return false;\n#endif\n}\n\nbool png_image::save(std::string const& filename, file_base::save_options const& options)\n{\n#if VSNRAY_COMMON_HAVE_PNG\n cfile file(filename.c_str(), \"wb\");\n\n if (!file.good())\n {\n return false;\n }\n\n\n png_write_context context;\n\n context.png = png_create_write_struct(\n PNG_LIBPNG_VER_STRING,\n 0 \/*user-data*\/,\n png_error_callback,\n png_warning_callback\n );\n\n if (context.png == 0)\n {\n return false;\n }\n\n context.info = png_create_info_struct(context.png);\n\n if (context.info == 0)\n {\n return false;\n }\n\n\n png_init_io(context.png, file.get());\n\n \/\/ TODO: support other formats than RGB8\n png_set_IHDR(\n context.png,\n context.info,\n width_,\n height_,\n 8,\n PNG_COLOR_TYPE_RGB,\n PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_BASE,\n PNG_FILTER_TYPE_BASE\n );\n\n png_write_info(context.png, context.info);\n\n size_t pitch = width_ * 3;\n context.row = new png_byte[pitch];\n\n for (int y = 0; y < height_; ++y)\n {\n for (int x = 0; x < width_; ++x)\n {\n std::memcpy(\n context.row + x * 3,\n data() + (y * width_ + x) * 3,\n 3\n );\n }\n png_write_row(context.png, context.row);\n }\n\n png_write_end(context.png, 0);\n\n return true;\n\n#else\n VSNRAY_UNUSED(filename);\n\n return false;\n#endif\n}\n\n} \/\/ visionaray\nSilence warning\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#if VSNRAY_COMMON_HAVE_PNG\n#include \n#endif\n\n#include \"cfile.h\"\n#include \"png_image.h\"\n\nnamespace visionaray\n{\n\n#if VSNRAY_COMMON_HAVE_PNG\nstruct png_read_context\n{\n png_structp png;\n png_infop info;\n\n png_read_context()\n : png(0)\n , info(0)\n {\n }\n\n ~png_read_context()\n {\n png_destroy_read_struct(&png, &info, 0);\n }\n};\n\nstruct png_write_context\n{\n png_structp png;\n png_infop info;\n png_bytep row;\n\n png_write_context()\n : png(0)\n , info(0)\n , row(0)\n {\n }\n\n ~png_write_context()\n {\n png_free_data(png, info, PNG_FREE_ALL, -1);\n png_destroy_write_struct(&png, &info);\n\n delete[] row;\n }\n};\n\nstatic void png_error_callback(png_structp png_ptr, png_const_charp msg)\n{\n fprintf(stderr, \"PNG error: \\\"%s\\\"\\n\", msg);\n\n longjmp(png_jmpbuf(png_ptr), 1);\n}\n\n\nstatic void png_warning_callback(png_structp \/*png_ptr*\/, png_const_charp \/*msg*\/)\n{\n \/\/ TODO\n}\n\nstatic int png_num_components(int color_type)\n{\n switch (color_type)\n {\n case PNG_COLOR_TYPE_GRAY:\n return 1;\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n return 2;\n case PNG_COLOR_TYPE_RGB:\n return 3;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n return 4;\n }\n\n return -1;\n}\n#endif\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ png_image\n\/\/\n\npng_image::png_image(int width, int height, pixel_format format, uint8_t const* data)\n : image_base(width, height, format, data)\n{\n}\n\nbool png_image::load(std::string const& filename)\n{\n#if VSNRAY_COMMON_HAVE_PNG\n cfile file(filename.c_str(), \"r\");\n\n if (!file.good())\n {\n return false;\n }\n\n\n png_read_context context;\n\n context.png = png_create_read_struct(\n PNG_LIBPNG_VER_STRING,\n 0 \/*user-data*\/,\n png_error_callback,\n png_warning_callback\n );\n\n if (context.png == 0)\n {\n return false;\n }\n\n context.info = png_create_info_struct(context.png);\n\n if (context.info == 0)\n {\n return false;\n }\n\n\n png_init_io(context.png, file.get());\n\n png_read_info(context.png, context.info);\n\n png_uint_32 w = 0;\n png_uint_32 h = 0;\n int bit_depth = 0;\n int color_type = 0;\n\n png_get_IHDR(context.png, context.info, &w, &h, &bit_depth, &color_type, 0, 0, 0);\n\n\n \/\/ expand paletted images to RGB\n if (color_type == PNG_COLOR_TYPE_PALETTE)\n {\n png_set_expand(context.png);\n }\n\n png_read_update_info(context.png, context.info);\n\n w = png_get_image_width(context.png, context.info);\n h = png_get_image_height(context.png, context.info);\n bit_depth = png_get_bit_depth(context.png, context.info);\n color_type = png_get_color_type(context.png, context.info);\n\n \/\/ Only support 8-bit and 16-bit per pixel images\n if (bit_depth != 8 && bit_depth != 16)\n {\n return false;\n }\n\n auto num_components = png_num_components(color_type);\n\n switch (num_components)\n {\n case 3:\n format_ = bit_depth == 8 ? PF_RGB8 : PF_RGB16UI;\n break;\n\n case 4:\n format_ = bit_depth == 8 ? PF_RGBA8 : PF_RGBA16UI;\n break;\n\n default:\n format_ = PF_UNSPECIFIED;\n return false;\n }\n\n auto pitch = png_get_rowbytes(context.png, context.info);\n\n data_.resize(pitch * h);\n\n for (png_uint_32 y = 0; y < h; ++y)\n {\n png_bytep row = data_.data() + (h - 1) * pitch - y * pitch;\n png_read_rows(context.png, &row, nullptr, 1);\n }\n\n png_read_end(context.png, context.info);\n\n width_ = static_cast(w);\n height_ = static_cast(h);\n\n return true;\n#else\n VSNRAY_UNUSED(filename);\n\n return false;\n#endif\n}\n\nbool png_image::save(std::string const& filename, file_base::save_options const& \/*options*\/)\n{\n#if VSNRAY_COMMON_HAVE_PNG\n cfile file(filename.c_str(), \"wb\");\n\n if (!file.good())\n {\n return false;\n }\n\n\n png_write_context context;\n\n context.png = png_create_write_struct(\n PNG_LIBPNG_VER_STRING,\n 0 \/*user-data*\/,\n png_error_callback,\n png_warning_callback\n );\n\n if (context.png == 0)\n {\n return false;\n }\n\n context.info = png_create_info_struct(context.png);\n\n if (context.info == 0)\n {\n return false;\n }\n\n\n png_init_io(context.png, file.get());\n\n \/\/ TODO: support other formats than RGB8\n png_set_IHDR(\n context.png,\n context.info,\n width_,\n height_,\n 8,\n PNG_COLOR_TYPE_RGB,\n PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_BASE,\n PNG_FILTER_TYPE_BASE\n );\n\n png_write_info(context.png, context.info);\n\n size_t pitch = width_ * 3;\n context.row = new png_byte[pitch];\n\n for (int y = 0; y < height_; ++y)\n {\n for (int x = 0; x < width_; ++x)\n {\n std::memcpy(\n context.row + x * 3,\n data() + (y * width_ + x) * 3,\n 3\n );\n }\n png_write_row(context.png, context.row);\n }\n\n png_write_end(context.png, 0);\n\n return true;\n\n#else\n VSNRAY_UNUSED(filename);\n\n return false;\n#endif\n}\n\n} \/\/ visionaray\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \n#include \n\n#ifdef _WINDOWS\n #define NOMINMAX\n #include \n #define handle HMODULE\n #define dlsym GetProcAddress\n #define dlclose FreeLibrary\n #define dlerror GetLastError\n #define MAPNIK_SUPPORTS_DLOPEN\n#else\n #ifdef MAPNIK_HAS_DLCFN\n #include \n #define MAPNIK_SUPPORTS_DLOPEN\n #endif\n #define handle void *\n#endif\n\n\/\/ TODO - handle\/report dlerror\n\nnamespace mapnik\n{\n\nstruct _mapnik_lib_t {\n handle dl;\n};\n\nPluginInfo::PluginInfo(std::string const& filename,\n std::string const& library_name)\n : filename_(filename),\n name_(),\n module_(new mapnik_lib_t)\n {\n#ifdef _WINDOWS\n if (module_) module_->dl = LoadLibraryA(filename.c_str());\n if (module_ && module_->dl)\n {\n name_func name = reinterpret_cast(dlsym(module_->dl, library_name.c_str()));\n if (name) name_ = name();\n }\n#else\n #ifdef MAPNIK_HAS_DLCFN\n if (module_) module_->dl = dlopen(filename.c_str(),RTLD_LAZY);\n if (module_ && module_->dl)\n {\n name_func name = reinterpret_cast(dlsym(module_->dl, library_name.c_str()));\n if (name) name_ = name();\n }\n #else\n throw std::runtime_error(\"no support for loading dynamic objects (Mapnik not compiled with -DMAPNIK_HAS_DLCFN)\");\n #endif\n#endif\n }\n\nPluginInfo::~PluginInfo()\n{\n if (module_)\n {\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n if (module_->dl) dlclose(module_->dl),module_->dl=0;\n#endif\n delete module_;\n }\n}\n\n\nvoid * PluginInfo::get_symbol(std::string const& sym_name) const\n{\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n return static_cast(dlsym(module_->dl, sym_name.c_str()));\n#else\n return NULL;\n#endif\n}\n\nstd::string const& PluginInfo::name() const\n{\n return name_;\n}\n\nbool PluginInfo::valid() const\n{\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n if (module_ && module_->dl && !name_.empty()) return true;\n#endif\n return false;\n}\n\nstd::string PluginInfo::get_error() const\n{\n return std::string(\"could not open: '\") + name_ + \"'\";\n}\n\nvoid PluginInfo::init()\n{\n \/\/ do any initialization needed\n}\n\nvoid PluginInfo::exit()\n{\n \/\/ do any shutdown needed\n}\n\n\n}\ndo not call dlclose on plugins linking libgdal\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \n#include \n\n#ifdef _WINDOWS\n #define NOMINMAX\n #include \n #define handle HMODULE\n #define dlsym GetProcAddress\n #define dlclose FreeLibrary\n #define dlerror GetLastError\n #define MAPNIK_SUPPORTS_DLOPEN\n#else\n #ifdef MAPNIK_HAS_DLCFN\n #include \n #define MAPNIK_SUPPORTS_DLOPEN\n #endif\n #define handle void *\n#endif\n\n\/\/ TODO - handle\/report dlerror\n\nnamespace mapnik\n{\n\nstruct _mapnik_lib_t {\n handle dl;\n};\n\nPluginInfo::PluginInfo(std::string const& filename,\n std::string const& library_name)\n : filename_(filename),\n name_(),\n module_(new mapnik_lib_t)\n {\n#ifdef _WINDOWS\n if (module_) module_->dl = LoadLibraryA(filename.c_str());\n if (module_ && module_->dl)\n {\n name_func name = reinterpret_cast(dlsym(module_->dl, library_name.c_str()));\n if (name) name_ = name();\n }\n#else\n #ifdef MAPNIK_HAS_DLCFN\n if (module_) module_->dl = dlopen(filename.c_str(),RTLD_LAZY);\n if (module_ && module_->dl)\n {\n name_func name = reinterpret_cast(dlsym(module_->dl, library_name.c_str()));\n if (name) name_ = name();\n }\n #else\n throw std::runtime_error(\"no support for loading dynamic objects (Mapnik not compiled with -DMAPNIK_HAS_DLCFN)\");\n #endif\n#endif\n }\n\nPluginInfo::~PluginInfo()\n{\n if (module_)\n {\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n \/*\n We do not call dlclose for plugins that link libgdal.\n This is a terrible hack, but necessary to prevent crashes\n at exit when gdal attempts to shutdown. The problem arises\n when Mapnik is used with another library that uses thread-local\n storage (like libuv). In this case GDAL also tries to cleanup thread\n local storage and leaves things in a state that causes libuv to crash.\n This is partially fixed by http:\/\/trac.osgeo.org\/gdal\/ticket\/5509 but only\n in the case that gdal is linked as a shared library. This workaround therefore\n prevents crashes with gdal 1.11.x and gdal 2.x when using a static libgdal.\n *\/\n if (module_->dl && name_ != \"gdal\" && name_ != \"ogr\")\n {\n dlclose(module_->dl),module_->dl=0;\n }\n#endif\n delete module_;\n }\n}\n\n\nvoid * PluginInfo::get_symbol(std::string const& sym_name) const\n{\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n return static_cast(dlsym(module_->dl, sym_name.c_str()));\n#else\n return NULL;\n#endif\n}\n\nstd::string const& PluginInfo::name() const\n{\n return name_;\n}\n\nbool PluginInfo::valid() const\n{\n#ifdef MAPNIK_SUPPORTS_DLOPEN\n if (module_ && module_->dl && !name_.empty()) return true;\n#endif\n return false;\n}\n\nstd::string PluginInfo::get_error() const\n{\n return std::string(\"could not open: '\") + name_ + \"'\";\n}\n\nvoid PluginInfo::init()\n{\n \/\/ do any initialization needed\n}\n\nvoid PluginInfo::exit()\n{\n \/\/ do any shutdown needed\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#if defined(__linux__)\n# define MQDES_TO_FD(mqdes) (int)(mqdes)\n#elif defined(__FreeBSD__)\n# define MQDES_TO_FD(mqdes) __mq_oshandle(mqdes)\n#endif\n\nusing namespace node;\nusing namespace v8;\n\nstatic Persistent constructor;\nstatic Persistent emit_symbol;\nstatic Persistent read_emit_argv[1];\nstatic Persistent write_emit_argv[1];\nstatic const mqd_t MQDES_INVALID = (mqd_t)-1;\n\nclass PosixMQ : public ObjectWrap {\n public:\n mqd_t mqdes;\n struct mq_attr mqattrs;\n uv_poll_t* mqpollhandle;\n char* mqname;\n Persistent Emit;\n bool canread;\n bool canwrite;\n\n PosixMQ() : mqpollhandle(NULL), mqdes(MQDES_INVALID), mqname(NULL),\n canread(false), canwrite(false) {};\n\n ~PosixMQ() {\n if (mqdes != MQDES_INVALID) {\n close();\n delete mqpollhandle;\n mqpollhandle = NULL;\n }\n if (mqname) {\n free(mqname);\n mqname = NULL;\n }\n Emit.Dispose();\n Emit.Clear();\n }\n\n int close() {\n int r;\n uv_poll_stop(mqpollhandle);\n uv_close((uv_handle_t *)mqpollhandle, on_close);\n r = mq_close(mqdes);\n mqdes = MQDES_INVALID;\n return r;\n }\n\n static void on_close (uv_handle_t *handle) {}\n\n static Handle New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use `new` to create instances of this object.\")));\n }\n\n PosixMQ* obj = new PosixMQ();\n obj->Wrap(args.This());\n\n return args.This();\n }\n\n static Handle Open(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n bool doCreate = false;\n int flags = O_RDWR | O_NONBLOCK;\n mode_t mode;\n const char* name;\n\n if (args.Length() != 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expecting 1 argument\")));\n }\n if (!args[0]->IsObject()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Argument must be an object\")));\n }\n\n Local config = args[0]->ToObject();\n Local val;\n\n if (!(val = config->Get(String::New(\"create\")))->IsUndefined()) {\n if (!val->IsBoolean()) {\n return ThrowException(Exception::TypeError(\n String::New(\"'create' property must be a boolean\")));\n }\n doCreate = val->BooleanValue();\n }\n\n val = config->Get(String::New(\"name\"));\n if (!val->IsString()) {\n return ThrowException(Exception::TypeError(\n String::New(\"'name' property must be a string\")));\n }\n String::AsciiValue namestr(val->ToString());\n name = (const char*)(*namestr);\n\n val = config->Get(String::New(\"mode\"));\n if (doCreate) {\n if (val->IsUint32())\n mode = (mode_t)val->Uint32Value();\n else if (val->IsString()) {\n String::AsciiValue modestr(val->ToString());\n mode = (mode_t)strtoul((const char*)(*modestr), NULL, 8);\n } else {\n return ThrowException(Exception::TypeError(\n String::New(\"'mode' property must be a string or integer\")));\n }\n flags |= O_CREAT;\n\n val = config->Get(String::New(\"exclusive\"));\n if (val->IsBoolean() && val->BooleanValue() == true)\n flags |= O_EXCL;\n\n val = config->Get(String::New(\"maxmsgs\"));\n if (val->IsUint32())\n obj->mqattrs.mq_maxmsg = val->Uint32Value();\n else\n obj->mqattrs.mq_maxmsg = 10;\n val = config->Get(String::New(\"msgsize\"));\n if (val->IsUint32())\n obj->mqattrs.mq_msgsize = val->Uint32Value();\n else\n obj->mqattrs.mq_msgsize = 8192;\n }\n\n if (obj->mqdes != MQDES_INVALID)\n obj->close();\n\n if (doCreate)\n obj->mqdes = mq_open(name, flags, mode, &(obj->mqattrs));\n else\n obj->mqdes = mq_open(name, flags);\n\n if (obj->mqdes == MQDES_INVALID ||\n mq_getattr(obj->mqdes, &(obj->mqattrs)) == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n if (obj->mqname) {\n free(obj->mqname);\n obj->mqname = NULL;\n } else {\n obj->Emit = Persistent::New(Local::Cast(\n obj->handle_->Get(emit_symbol)));\n }\n\n obj->mqname = strdup(name);\n\n obj->canread = !(obj->mqattrs.mq_curmsgs > 0);\n obj->canwrite = !(obj->mqattrs.mq_curmsgs < obj->mqattrs.mq_maxmsg);\n\n if (!obj->mqpollhandle)\n obj->mqpollhandle = new uv_poll_t;\n obj->mqpollhandle->data = obj;\n uv_poll_init(uv_default_loop(), obj->mqpollhandle, MQDES_TO_FD(obj->mqdes));\n uv_poll_start(obj->mqpollhandle, UV_READABLE | UV_WRITABLE, poll_cb);\n\n return Undefined();\n }\n\n static void poll_cb(uv_poll_t *handle, int status, int events) {\n HandleScope scope;\n assert(status == 0);\n\n PosixMQ* obj = (PosixMQ*)handle->data;\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n if ((events & UV_READABLE) && !obj->canread) {\n obj->canread = true;\n\n TryCatch try_catch;\n obj->Emit->Call(obj->handle_, 1, read_emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n } else if (!(events & UV_READABLE))\n obj->canread = false;\n\n if ((events & UV_WRITABLE) && !obj->canwrite) {\n obj->canwrite = true;\n TryCatch try_catch;\n obj->Emit->Call(obj->handle_, 1, write_emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n } else if (!(events & UV_WRITABLE))\n obj->canwrite = false;\n }\n\n static Handle Close(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n\n if (obj->mqdes == MQDES_INVALID) {\n return ThrowException(Exception::Error(\n String::New(\"Queue already closed\")));\n }\n\n int r = obj->close();\n\n if (r == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n return Undefined();\n }\n\n static Handle Unlink(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n\n if (!obj->mqname) {\n return ThrowException(Exception::Error(\n String::New(\"Nothing to unlink\")));\n }\n\n if (mq_unlink((const char*)obj->mqname) == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n if (obj->mqname) {\n free(obj->mqname);\n obj->mqname = NULL;\n }\n\n return Undefined();\n }\n\n static Handle Send(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n uint32_t priority = 0;\n bool ret = true;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expected at least 1 argument\")));\n } else if (!Buffer::HasInstance(args[0])) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a Buffer\")));\n } else if (args.Length() >= 2) {\n if (args[1]->IsUint32() && args[1]->Uint32Value() < 32)\n priority = args[1]->Uint32Value();\n else {\n return ThrowException(Exception::TypeError(\n String::New(\"Second argument must be an integer 0 <= n < 32\")));\n }\n }\n\n if (mq_send(obj->mqdes, Buffer::Data(args[0]->ToObject()),\n Buffer::Length(args[0]->ToObject()), priority) == -1) {\n if (errno != EAGAIN) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n ret = false;\n }\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Boolean::New(ret));\n }\n\n static Handle Receive(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n ssize_t nBytes;\n uint32_t priority;\n bool retTuple = false;\n Local ret;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expected at least 1 argument\")));\n } else if (!Buffer::HasInstance(args[0])) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a Buffer\")));\n } else if (args.Length() > 1)\n retTuple = args[1]->BooleanValue();\n\n Local buf = args[0]->ToObject();\n if ((nBytes = mq_receive(obj->mqdes, Buffer::Data(buf),\n Buffer::Length(buf), &priority)) == -1) {\n if (errno != EAGAIN) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n ret = Local::New(Boolean::New(false));\n } else if (!retTuple)\n ret = Integer::New(nBytes);\n else {\n Local tuple = Array::New(2);\n tuple->Set(0, Integer::New(nBytes));\n tuple->Set(1, Integer::New(priority));\n ret = tuple;\n }\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(ret);\n }\n\n static Handle MsgsizeGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_msgsize));\n }\n\n static Handle MaxmsgsGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_maxmsg));\n }\n\n static Handle CurmsgsGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_curmsgs));\n }\n\n static Handle IsfullGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Boolean::New(obj->mqattrs.mq_curmsgs == obj->mqattrs.mq_maxmsg));\n }\n\n static void Initialize(Handle target) {\n HandleScope scope;\n\n Local tpl = FunctionTemplate::New(New);\n Local name = String::NewSymbol(\"PosixMQ\");\n\n constructor = Persistent::New(tpl);\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(name);\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"open\", Open);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"push\", Send);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"shift\", Receive);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"unlink\", Unlink);\n\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"msgsize\"),\n MsgsizeGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"maxmsgs\"),\n MaxmsgsGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"curmsgs\"),\n CurmsgsGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"isFull\"),\n IsfullGetter);\n emit_symbol = NODE_PSYMBOL(\"emit\");\n read_emit_argv[0] = NODE_PSYMBOL(\"messages\");\n write_emit_argv[0] = NODE_PSYMBOL(\"drain\");\n target->Set(name, constructor->GetFunction());\n }\n};\n\nextern \"C\" {\n void init(Handle target) {\n HandleScope scope;\n PosixMQ::Initialize(target);\n }\n\n NODE_MODULE(posixmq, init);\n}\nprevent excessive polling#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#if defined(__linux__)\n# define MQDES_TO_FD(mqdes) (int)(mqdes)\n#elif defined(__FreeBSD__)\n# define MQDES_TO_FD(mqdes) __mq_oshandle(mqdes)\n#endif\n\nusing namespace node;\nusing namespace v8;\n\nstatic Persistent constructor;\nstatic Persistent emit_symbol;\nstatic Persistent read_emit_argv[1];\nstatic Persistent write_emit_argv[1];\nstatic const mqd_t MQDES_INVALID = (mqd_t)-1;\n\nclass PosixMQ : public ObjectWrap {\n public:\n mqd_t mqdes;\n struct mq_attr mqattrs;\n uv_poll_t* mqpollhandle;\n char* mqname;\n Persistent Emit;\n bool canread;\n bool canwrite;\n int eventmask;\n\n PosixMQ() : mqpollhandle(NULL), mqdes(MQDES_INVALID), mqname(NULL),\n canread(false), canwrite(false), eventmask(0) {};\n\n ~PosixMQ() {\n if (mqdes != MQDES_INVALID) {\n close();\n delete mqpollhandle;\n mqpollhandle = NULL;\n }\n if (mqname) {\n free(mqname);\n mqname = NULL;\n }\n Emit.Dispose();\n Emit.Clear();\n }\n\n int close() {\n int r;\n uv_poll_stop(mqpollhandle);\n uv_close((uv_handle_t *)mqpollhandle, on_close);\n r = mq_close(mqdes);\n mqdes = MQDES_INVALID;\n return r;\n }\n\n static void on_close (uv_handle_t *handle) {}\n\n static Handle New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use `new` to create instances of this object.\")));\n }\n\n PosixMQ* obj = new PosixMQ();\n obj->Wrap(args.This());\n\n return args.This();\n }\n\n static Handle Open(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n bool doCreate = false;\n int flags = O_RDWR | O_NONBLOCK;\n mode_t mode;\n const char* name;\n\n if (args.Length() != 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expecting 1 argument\")));\n }\n if (!args[0]->IsObject()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Argument must be an object\")));\n }\n\n Local config = args[0]->ToObject();\n Local val;\n\n if (!(val = config->Get(String::New(\"create\")))->IsUndefined()) {\n if (!val->IsBoolean()) {\n return ThrowException(Exception::TypeError(\n String::New(\"'create' property must be a boolean\")));\n }\n doCreate = val->BooleanValue();\n }\n\n val = config->Get(String::New(\"name\"));\n if (!val->IsString()) {\n return ThrowException(Exception::TypeError(\n String::New(\"'name' property must be a string\")));\n }\n String::AsciiValue namestr(val->ToString());\n name = (const char*)(*namestr);\n\n val = config->Get(String::New(\"mode\"));\n if (doCreate) {\n if (val->IsUint32())\n mode = (mode_t)val->Uint32Value();\n else if (val->IsString()) {\n String::AsciiValue modestr(val->ToString());\n mode = (mode_t)strtoul((const char*)(*modestr), NULL, 8);\n } else {\n return ThrowException(Exception::TypeError(\n String::New(\"'mode' property must be a string or integer\")));\n }\n flags |= O_CREAT;\n\n val = config->Get(String::New(\"exclusive\"));\n if (val->IsBoolean() && val->BooleanValue() == true)\n flags |= O_EXCL;\n\n val = config->Get(String::New(\"maxmsgs\"));\n if (val->IsUint32())\n obj->mqattrs.mq_maxmsg = val->Uint32Value();\n else\n obj->mqattrs.mq_maxmsg = 10;\n val = config->Get(String::New(\"msgsize\"));\n if (val->IsUint32())\n obj->mqattrs.mq_msgsize = val->Uint32Value();\n else\n obj->mqattrs.mq_msgsize = 8192;\n }\n\n if (obj->mqdes != MQDES_INVALID)\n obj->close();\n\n if (doCreate)\n obj->mqdes = mq_open(name, flags, mode, &(obj->mqattrs));\n else\n obj->mqdes = mq_open(name, flags);\n\n if (obj->mqdes == MQDES_INVALID ||\n mq_getattr(obj->mqdes, &(obj->mqattrs)) == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n if (obj->mqname) {\n free(obj->mqname);\n obj->mqname = NULL;\n } else {\n obj->Emit = Persistent::New(Local::Cast(\n obj->handle_->Get(emit_symbol)));\n }\n\n obj->mqname = strdup(name);\n\n obj->canread = !(obj->mqattrs.mq_curmsgs > 0);\n obj->canwrite = !(obj->mqattrs.mq_curmsgs < obj->mqattrs.mq_maxmsg);\n\n if (!obj->mqpollhandle)\n obj->mqpollhandle = new uv_poll_t;\n obj->mqpollhandle->data = obj;\n obj->eventmask = UV_READABLE | UV_WRITABLE;\n uv_poll_init(uv_default_loop(), obj->mqpollhandle, MQDES_TO_FD(obj->mqdes));\n uv_poll_start(obj->mqpollhandle, obj->eventmask, poll_cb);\n\n return Undefined();\n }\n\n static void poll_cb(uv_poll_t *handle, int status, int events) {\n HandleScope scope;\n assert(status == 0);\n\n PosixMQ* obj = (PosixMQ*)handle->data;\n\n \/\/mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n if ((events & UV_READABLE) && !obj->canread) {\n obj->eventmask &= ~UV_READABLE;\n obj->canread = true;\n\n TryCatch try_catch;\n obj->Emit->Call(obj->handle_, 1, read_emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n } else if (!(events & UV_READABLE)) {\n obj->eventmask |= UV_READABLE;\n obj->canread = false;\n }\n\n if ((events & UV_WRITABLE) && !obj->canwrite) {\n obj->eventmask &= ~UV_WRITABLE;\n obj->canwrite = true;\n\n TryCatch try_catch;\n obj->Emit->Call(obj->handle_, 1, write_emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n } else if (!(events & UV_WRITABLE)) {\n obj->eventmask |= UV_WRITABLE;\n obj->canwrite = false;\n }\n\n if (obj->mqdes != MQDES_INVALID)\n uv_poll_start(obj->mqpollhandle, obj->eventmask, poll_cb);\n }\n\n static Handle Close(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n\n if (obj->mqdes == MQDES_INVALID) {\n return ThrowException(Exception::Error(\n String::New(\"Queue already closed\")));\n }\n\n int r = obj->close();\n\n if (r == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n return Undefined();\n }\n\n static Handle Unlink(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n\n if (!obj->mqname) {\n return ThrowException(Exception::Error(\n String::New(\"Nothing to unlink\")));\n }\n\n if (mq_unlink((const char*)obj->mqname) == -1) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n\n if (obj->mqname) {\n free(obj->mqname);\n obj->mqname = NULL;\n }\n\n return Undefined();\n }\n\n static Handle Send(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n uint32_t priority = 0;\n bool ret = true;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expected at least 1 argument\")));\n } else if (!Buffer::HasInstance(args[0])) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a Buffer\")));\n } else if (args.Length() >= 2) {\n if (args[1]->IsUint32() && args[1]->Uint32Value() < 32)\n priority = args[1]->Uint32Value();\n else {\n return ThrowException(Exception::TypeError(\n String::New(\"Second argument must be an integer 0 <= n < 32\")));\n }\n }\n\n if (mq_send(obj->mqdes, Buffer::Data(args[0]->ToObject()),\n Buffer::Length(args[0]->ToObject()), priority) == -1) {\n if (errno != EAGAIN) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n ret = false;\n }\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Boolean::New(ret));\n }\n\n static Handle Receive(const Arguments& args) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(args.This());\n ssize_t nBytes;\n uint32_t priority;\n bool retTuple = false;\n Local ret;\n\n if (args.Length() < 1) {\n return ThrowException(Exception::TypeError(\n String::New(\"Expected at least 1 argument\")));\n } else if (!Buffer::HasInstance(args[0])) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a Buffer\")));\n } else if (args.Length() > 1)\n retTuple = args[1]->BooleanValue();\n\n Local buf = args[0]->ToObject();\n if ((nBytes = mq_receive(obj->mqdes, Buffer::Data(buf),\n Buffer::Length(buf), &priority)) == -1) {\n if (errno != EAGAIN) {\n return ThrowException(Exception::Error(\n String::New(uv_strerror(uv_last_error(uv_default_loop())))));\n }\n ret = Local::New(Boolean::New(false));\n } else if (!retTuple)\n ret = Integer::New(nBytes);\n else {\n Local tuple = Array::New(2);\n tuple->Set(0, Integer::New(nBytes));\n tuple->Set(1, Integer::New(priority));\n ret = tuple;\n }\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(ret);\n }\n\n static Handle MsgsizeGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_msgsize));\n }\n\n static Handle MaxmsgsGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_maxmsg));\n }\n\n static Handle CurmsgsGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Integer::New(obj->mqattrs.mq_curmsgs));\n }\n\n static Handle IsfullGetter (Local property, const AccessorInfo& info) {\n HandleScope scope;\n PosixMQ* obj = ObjectWrap::Unwrap(info.This());\n\n mq_getattr(obj->mqdes, &(obj->mqattrs));\n\n return scope.Close(Boolean::New(obj->mqattrs.mq_curmsgs == obj->mqattrs.mq_maxmsg));\n }\n\n static void Initialize(Handle target) {\n HandleScope scope;\n\n Local tpl = FunctionTemplate::New(New);\n Local name = String::NewSymbol(\"PosixMQ\");\n\n constructor = Persistent::New(tpl);\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(name);\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"open\", Open);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"push\", Send);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"shift\", Receive);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"unlink\", Unlink);\n\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"msgsize\"),\n MsgsizeGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"maxmsgs\"),\n MaxmsgsGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"curmsgs\"),\n CurmsgsGetter);\n constructor->PrototypeTemplate()->SetAccessor(String::New(\"isFull\"),\n IsfullGetter);\n emit_symbol = NODE_PSYMBOL(\"emit\");\n read_emit_argv[0] = NODE_PSYMBOL(\"messages\");\n write_emit_argv[0] = NODE_PSYMBOL(\"drain\");\n target->Set(name, constructor->GetFunction());\n }\n};\n\nextern \"C\" {\n void init(Handle target) {\n HandleScope scope;\n PosixMQ::Initialize(target);\n }\n\n NODE_MODULE(posixmq, init);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"cvrp.h\"\n#include \"tsplib_format.h\"\n\nnamespace VrpSolver {\n\n unsigned int Cvrp::demand(unsigned int node_id) const {\n if ((1 > node_id) || (node_id > dimension_))\n throw std::out_of_range(\"error: in Cvrp::demand\");\n return demands_[node_id];\n }\n\n int Cvrp::distance(unsigned int from, unsigned int to) const {\n if ((1 > from) || (from > dimension_) ||\n (1 > to) || (to > dimension_))\n throw std::out_of_range(\"error: in Cvrp::distance\");\n\n const int index = (to > from) ? ((to-2)*(to-1)\/2+(from-1)) :\n ((from-2)*(from-1)\/2+(to-1));\n return distances_[index];\n }\n\n \/\/ 文字列strからtrim_char文字列に含まれている文字を削除\n void trim(std::string& str, const std::string& trim_char) {\n size_t pos;\n while ((pos = str.find_first_of(trim_char)) != std::string::npos)\n str.erase(pos, 1);\n }\n\n \/\/ セミコロン以後の文字列(空白の直前まで)を読み取る\n std::string get_parameter(std::ifstream& ifs) {\n std::string param;\n ifs >> param;\n while (param == \":\") ifs >> param; \/\/ \":\"は読み飛ばす\n return param;\n }\n\n enum TsplibKeyword {\n NAME=100, TYPE, COMMENT, DIMENSION, CAPACITY,\n EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,\n NODE_COORD_TYPE, DISPLAY_DATA_TYPE,\n NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,\n EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,\n END_OF_FILE\n };\n\n std::map keyword_map = {\n { \"NAME\", NAME },\n { \"TYPE\", TYPE },\n { \"COMMENT\", COMMENT },\n { \"DIMENSION\", DIMENSION },\n { \"CAPACITY\", CAPACITY },\n { \"EDGE_WEIGHT_TYPE\", EDGE_WEIGHT_TYPE },\n { \"EDGE_WEIGHT_FORMAT\", EDGE_WEIGHT_FORMAT },\n { \"EDGE_DATA_FORMAT\", EDGE_DATA_FORMAT },\n { \"NODE_COORD_TYPE\", NODE_COORD_TYPE },\n { \"DISPLAY_DATA_TYPE\", DISPLAY_DATA_TYPE },\n { \"NODE_COORD_SECTION\", NODE_COORD_SECTION },\n { \"DEPOT_SECTION\", DEPOT_SECTION },\n { \"DEMAND_SECTION\", DEMAND_SECTION },\n { \"EDGE_DATA_SECTION\", EDGE_DATA_SECTION },\n { \"EDGE_WEIGHT_SECTION\", EDGE_WEIGHT_SECTION },\n { \"EOF\", END_OF_FILE }\n };\n\n\n \/\/ infileから情報を読み取りCvrpクラスをセットアップする\n void read_vrp(Cvrp& cvrp, const std::string &infile) {\n std::ifstream ifs(infile.c_str());\n if (!ifs)\n throw std::runtime_error(\"error: can't open file \" + infile);\n\n std::string edge_weight_type,\n edge_weight_format,\n display_data_type;\n\n while (ifs) {\n std::string tsp_keyword;\n ifs >> tsp_keyword;\n if (ifs.eof()) break;\n trim(tsp_keyword, \" :\");\n switch (keyword_map[tsp_keyword]) {\n\n \/\/ The specification part\n case NAME :\n cvrp.name_ = get_parameter(ifs);\n break;\n case TYPE :\n {\n std::string not_use;\n getline(ifs, not_use);\n }\n break;\n case COMMENT :\n {\n std::string not_use;\n getline(ifs, not_use);\n }\n break;\n case DIMENSION :\n cvrp.dimension_ = stoi(get_parameter(ifs));\n break;\n case CAPACITY :\n cvrp.capacity_ = stoi(get_parameter(ifs));\n break;\n case EDGE_WEIGHT_TYPE :\n edge_weight_type = get_parameter(ifs);\n break;\n case EDGE_WEIGHT_FORMAT :\n edge_weight_format = get_parameter(ifs);\n break;\n case EDGE_DATA_FORMAT :\n {\n std::string not_use;\n getline(ifs, not_use);\n break;\n }\n case NODE_COORD_TYPE :\n {\n std::string not_use;\n getline(ifs, not_use);\n break;\n }\n case DISPLAY_DATA_TYPE :\n display_data_type = get_parameter(ifs);\n break;\n\n \/\/ The data part\n case NODE_COORD_SECTION :\n {\n int n=0, m, x, y; \/\/ m do not use\n for (int i=0; i != cvrp.dimension_; i++) {\n ifs >> m >> x >> y;\n std::pair c(x,y);\n cvrp.coords_.push_back(c);\n }\n break;\n }\n case DEPOT_SECTION :\n {\n cvrp.depot_ = stoi(get_parameter(ifs));\n if (stoi(get_parameter(ifs)) != -1)\n throw std::runtime_error(\"error:\"\n \"can't handle multiple depots\");\n break;\n }\n case DEMAND_SECTION :\n {\n cvrp.demands_.push_back(0); \/\/ 0要素目は0にしておく\n for (int i=1; i <= cvrp.dimension_; i++) {\n unsigned int node_id, demand;\n ifs >> node_id >> demand;\n if (node_id != i)\n throw std::runtime_error(\"error:\"\n \"DEMAND_SECTION format may be different\");\n cvrp.demands_.push_back(demand);\n }\n break;\n }\n case EDGE_DATA_SECTION :\n throw std::runtime_error(\"Sorry, can not handle 'EDGE_DATA_SECTION'\");\n break;\n case EDGE_WEIGHT_SECTION :\n {\n if (edge_weight_format != \"LOWER_ROW\")\n throw std::runtime_error(\"Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW\");\n for (int i=0; i < cvrp.dimension_; i++) {\n for (int j=0; j < i; j++) {\n int distance;\n ifs >> distance;\n cvrp.distances_.push_back(distance);\n }\n }\n break;\n }\n case END_OF_FILE :\n \/\/ do nothing\n break;\n default :\n throw std::runtime_error(\"error: unknown keyword '\" + tsp_keyword + \"'\");\n break;\n }\n }\n\n \/\/ distancesの設定\n if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) {\n auto& distances = cvrp.distances_;\n auto& coords = cvrp.coords_;\n for (int i=0; i < cvrp.dimension_; i++) {\n for (int j=0; j < i; j++) {\n int dx = coords[j].first - coords[i].first;\n int dy = coords[j].second - coords[i].second;\n distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));\n }\n }\n }\n }\n} \/\/ namespace VrpSolver\nヘッダーの順序をアルファベット順に治した#include \n#include \n#include \n#include \n#include \n\n#include \"cvrp.h\"\n#include \"tsplib_format.h\"\n\nnamespace VrpSolver {\n\n unsigned int Cvrp::demand(unsigned int node_id) const {\n if ((1 > node_id) || (node_id > dimension_))\n throw std::out_of_range(\"error: in Cvrp::demand\");\n return demands_[node_id];\n }\n\n int Cvrp::distance(unsigned int from, unsigned int to) const {\n if ((1 > from) || (from > dimension_) ||\n (1 > to) || (to > dimension_))\n throw std::out_of_range(\"error: in Cvrp::distance\");\n\n const int index = (to > from) ? ((to-2)*(to-1)\/2+(from-1)) :\n ((from-2)*(from-1)\/2+(to-1));\n return distances_[index];\n }\n\n \/\/ 文字列strからtrim_char文字列に含まれている文字を削除\n void trim(std::string& str, const std::string& trim_char) {\n size_t pos;\n while ((pos = str.find_first_of(trim_char)) != std::string::npos)\n str.erase(pos, 1);\n }\n\n \/\/ セミコロン以後の文字列(空白の直前まで)を読み取る\n std::string get_parameter(std::ifstream& ifs) {\n std::string param;\n ifs >> param;\n while (param == \":\") ifs >> param; \/\/ \":\"は読み飛ばす\n return param;\n }\n\n enum TsplibKeyword {\n NAME, TYPE, COMMENT, DIMENSION, CAPACITY,\n EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,\n NODE_COORD_TYPE, DISPLAY_DATA_TYPE,\n NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,\n EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,\n END_OF_FILE\n };\n\n std::map keyword_map = {\n { \"NAME\", NAME },\n { \"TYPE\", TYPE },\n { \"COMMENT\", COMMENT },\n { \"DIMENSION\", DIMENSION },\n { \"CAPACITY\", CAPACITY },\n { \"EDGE_WEIGHT_TYPE\", EDGE_WEIGHT_TYPE },\n { \"EDGE_WEIGHT_FORMAT\", EDGE_WEIGHT_FORMAT },\n { \"EDGE_DATA_FORMAT\", EDGE_DATA_FORMAT },\n { \"NODE_COORD_TYPE\", NODE_COORD_TYPE },\n { \"DISPLAY_DATA_TYPE\", DISPLAY_DATA_TYPE },\n { \"NODE_COORD_SECTION\", NODE_COORD_SECTION },\n { \"DEPOT_SECTION\", DEPOT_SECTION },\n { \"DEMAND_SECTION\", DEMAND_SECTION },\n { \"EDGE_DATA_SECTION\", EDGE_DATA_SECTION },\n { \"EDGE_WEIGHT_SECTION\", EDGE_WEIGHT_SECTION },\n { \"EOF\", END_OF_FILE }\n };\n\n\n \/\/ infileから情報を読み取りCvrpクラスをセットアップする\n void read_vrp(Cvrp& cvrp, const std::string &infile) {\n std::ifstream ifs(infile.c_str());\n if (!ifs)\n throw std::runtime_error(\"error: can't open file \" + infile);\n\n std::string edge_weight_type,\n edge_weight_format,\n display_data_type;\n\n while (ifs) {\n std::string tsp_keyword;\n ifs >> tsp_keyword;\n if (ifs.eof()) break;\n trim(tsp_keyword, \" :\");\n switch (keyword_map[tsp_keyword]) {\n\n \/\/ The specification part\n case NAME :\n cvrp.name_ = get_parameter(ifs);\n break;\n case TYPE :\n {\n std::string not_use;\n getline(ifs, not_use);\n }\n break;\n case COMMENT :\n {\n std::string not_use;\n getline(ifs, not_use);\n }\n break;\n case DIMENSION :\n cvrp.dimension_ = stoi(get_parameter(ifs));\n break;\n case CAPACITY :\n cvrp.capacity_ = stoi(get_parameter(ifs));\n break;\n case EDGE_WEIGHT_TYPE :\n edge_weight_type = get_parameter(ifs);\n break;\n case EDGE_WEIGHT_FORMAT :\n edge_weight_format = get_parameter(ifs);\n break;\n case EDGE_DATA_FORMAT :\n {\n std::string not_use;\n getline(ifs, not_use);\n break;\n }\n case NODE_COORD_TYPE :\n {\n std::string not_use;\n getline(ifs, not_use);\n break;\n }\n case DISPLAY_DATA_TYPE :\n display_data_type = get_parameter(ifs);\n break;\n\n \/\/ The data part\n case NODE_COORD_SECTION :\n {\n int n=0, m, x, y; \/\/ m do not use\n for (int i=0; i != cvrp.dimension_; i++) {\n ifs >> m >> x >> y;\n std::pair c(x,y);\n cvrp.coords_.push_back(c);\n }\n break;\n }\n case DEPOT_SECTION :\n {\n cvrp.depot_ = stoi(get_parameter(ifs));\n if (stoi(get_parameter(ifs)) != -1)\n throw std::runtime_error(\"error:\"\n \"can't handle multiple depots\");\n break;\n }\n case DEMAND_SECTION :\n {\n cvrp.demands_.push_back(0); \/\/ 0要素目は0にしておく\n for (int i=1; i <= cvrp.dimension_; i++) {\n unsigned int node_id, demand;\n ifs >> node_id >> demand;\n if (node_id != i)\n throw std::runtime_error(\"error:\"\n \"DEMAND_SECTION format may be different\");\n cvrp.demands_.push_back(demand);\n }\n break;\n }\n case EDGE_DATA_SECTION :\n throw std::runtime_error(\"Sorry, can not handle 'EDGE_DATA_SECTION'\");\n break;\n case EDGE_WEIGHT_SECTION :\n {\n if (edge_weight_format != \"LOWER_ROW\")\n throw std::runtime_error(\"Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW\");\n for (int i=0; i < cvrp.dimension_; i++) {\n for (int j=0; j < i; j++) {\n int distance;\n ifs >> distance;\n cvrp.distances_.push_back(distance);\n }\n }\n break;\n }\n case END_OF_FILE :\n \/\/ do nothing\n break;\n default :\n throw std::runtime_error(\"error: unknown keyword '\" + tsp_keyword + \"'\");\n break;\n }\n }\n\n \/\/ distancesの設定\n if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) {\n auto& distances = cvrp.distances_;\n auto& coords = cvrp.coords_;\n for (int i=0; i < cvrp.dimension_; i++) {\n for (int j=0; j < i; j++) {\n int dx = coords[j].first - coords[i].first;\n int dy = coords[j].second - coords[i].second;\n distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));\n }\n }\n }\n }\n\n} \/\/ namespace VrpSolver\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include \n# include \n# include \n# include \"D3D11SwapChain.hpp\"\n# include \n# include \n\nnamespace s3d\n{\n\tnamespace detail\n\t{\n\t\t[[nodiscard]]\n\t\tstatic double GetPerformanceFrequency()\n\t\t{\n\t\t\t::LARGE_INTEGER frequency;\n\t\t\t::QueryPerformanceFrequency(&frequency);\n\t\t\treturn static_cast(frequency.QuadPart);\n\t\t}\n\n\t\t[[nodiscard]]\n\t\tstatic double ToMillisec(const uint64 count)\n\t\t{\n\t\t\tstatic const double scale = 1'000 \/ GetPerformanceFrequency();\n\t\t\treturn count * scale;\n\t\t}\n\n\t\t[[nodiscard]]\n\t\tstatic double GetDisplayRefreshPeriodMillisec()\n\t\t{\n\t\t\tDWM_TIMING_INFO timingInfo = {};\n\t\t\ttimingInfo.cbSize = sizeof(DWM_TIMING_INFO);\n\t\t\t::DwmGetCompositionTimingInfo(nullptr, &timingInfo);\n\t\t\treturn ToMillisec(timingInfo.qpcRefreshPeriod);\n\t\t}\n\t}\n\n\tD3D11SwapChain::D3D11SwapChain(const D3D11Device& device, HWND hWnd, const Size& frameBufferSize)\n\t\t: m_hWnd(hWnd)\n\t\t, m_device(device.getDevice())\n\t\t, m_context(device.getContext())\n\t{\n\t\tLOG_SCOPED_TRACE(U\"D3D11SwapChain::D3D11SwapChain()\");\n\n\t\tm_desc.Width\t\t= frameBufferSize.x;\n\t\tm_desc.Height\t\t= frameBufferSize.y;\n\t\tm_desc.Format\t\t= DXGI_FORMAT_R8G8B8A8_UNORM;\n\t\tm_desc.Stereo\t\t= FALSE;\n\t\tm_desc.SampleDesc\t= { 1, 0 };\n\t\tm_desc.BufferUsage\t= DXGI_USAGE_RENDER_TARGET_OUTPUT;\n\t\tm_desc.BufferCount\t= 3;\n\t\tm_desc.Scaling\t\t= DXGI_SCALING_STRETCH;\n\t\tm_desc.SwapEffect\t= (IsWindows10OrGreater() ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD);\n\t\tm_desc.AlphaMode\t= DXGI_ALPHA_MODE_IGNORE;\n\t\tm_desc.Flags\t\t= 0;\n\n\t\t\/\/ Swap chain を作成\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIFactory2::CreateSwapChainForHwnd()\");\n\t\t\tif (FAILED(device.getDXGIFactory2()->CreateSwapChainForHwnd(\n\t\t\t\tm_device,\n\t\t\t\thWnd,\n\t\t\t\t&m_desc,\n\t\t\t\tnullptr,\n\t\t\t\tnullptr,\n\t\t\t\t&m_swapChain1)))\n\t\t\t{\n\t\t\t\tthrow EngineError(U\"IDXGIFactory2::CreateSwapChainForHwnd() failed\");\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIFactory1::MakeWindowAssociation()\");\n\n\t\t\tconstexpr uint32 flags = (DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);\n\n\t\t\tif (FAILED(device.getDXGIFactory2()->MakeWindowAssociation(hWnd, flags)))\n\t\t\t{\n\t\t\t\tthrow EngineError(U\"IDXGIFactory2::MakeWindowAssociation() failed\");\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIDevice2::SetMaximumFrameLatency()\");\n\n\t\t\tif (ComPtr pDXGIDevice;\n\t\t\t\tSUCCEEDED(device.getDeiviceComPtr().As(&pDXGIDevice)))\n\t\t\t{\n\t\t\t\tpDXGIDevice->SetMaximumFrameLatency(2);\n\t\t\t}\n\t\t}\n\n\t\tupdateDisplayInfo();\n\t\tm_previousWindowBounds = Window::GetState().bounds;\n\t}\n\n\tD3D11SwapChain::~D3D11SwapChain()\n\t{\n\n\t}\n\n\tbool D3D11SwapChain::present(const bool vSync)\n\t{\n\t\tif (const Rect windowBounds = Window::GetState().bounds;\n\t\t\twindowBounds != m_previousWindowBounds)\n\t\t{\n\t\t\tupdateDisplayInfo();\n\n\t\t\tm_previousWindowBounds = windowBounds;\n\t\t}\n\n\t\t\/\/const bool vSync = (not m_targetFrameRateHz.has_value())\n\t\t\/\/\t|| ((30.0 <= m_targetFrameRateHz) && (AbsDiff(m_targetFrameRateHz.value(), m_displayFrequency) <= 3.0));\n\n\t\treturn vSync ? presentVSync() : presentNonVSync();\n\t}\n\n\tdouble D3D11SwapChain::getDisplayFrequency() const noexcept\n\t{\n\t\treturn m_displayFrequency;\n\t}\n\n\t\/\/void D3D11SwapChain::setTargetFrameRateHz(const Optional& targetFrameRateHz)\n\t\/\/{\n\t\/\/\tm_targetFrameRateHz = targetFrameRateHz;\n\t\/\/}\n\n\t\/\/const Optional& D3D11SwapChain::getTargetFrameRateHz() const noexcept\n\t\/\/{\n\t\/\/\treturn m_targetFrameRateHz;\n\t\/\/}\n\n\tIDXGISwapChain1* D3D11SwapChain::getSwapChain1() const noexcept\n\t{\n\t\treturn m_swapChain1.Get();\n\t}\n\n\tOptional D3D11SwapChain::getFullscreenRect()\n\t{\n\t\tLOG_TRACE(U\"D3D11SwapChain::getFullscreenRect()\");\n\n\t\tComPtr pOutput;\n\t\tif (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))\n\t\t{\n\t\t\treturn none;\n\t\t}\n\n\t\tDXGI_OUTPUT_DESC desc;\n\t\tif (FAILED(pOutput->GetDesc(&desc)))\n\t\t{\n\t\t\treturn none;\n\t\t}\n\n\t\treturn Rect(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top,\n\t\t\t(desc.DesktopCoordinates.right - desc.DesktopCoordinates.left),\n\t\t\t(desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top));\n\t}\n\n\tvoid D3D11SwapChain::updateDisplayInfo()\n\t{\n\t\tComPtr pOutput;\n\t\tif (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t{\n\t\t\tdouble displayFrequency;\n\n\t\t\tDXGI_OUTPUT_DESC desc;\n\t\t\tif (SUCCEEDED(pOutput->GetDesc(&desc)))\n\t\t\t{\n\t\t\t\tDEVMODE devMode = {};\n\t\t\t\tdevMode.dmSize = sizeof(DEVMODE);\n\t\t\t\t::EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &devMode);\n\t\t\t\tdisplayFrequency = devMode.dmDisplayFrequency;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdisplayFrequency = detail::GetDisplayRefreshPeriodMillisec();\n\t\t\t}\n\n\t\t\tif (displayFrequency != m_displayFrequency)\n\t\t\t{\n\t\t\t\tm_displayFrequency = displayFrequency;\n\t\t\t\tLOG_INFO(U\"Display refresh rate: {:.1f} Hz\"_fmt(m_displayFrequency));\n\t\t\t}\n\t\t}\n\t}\n\n\tbool D3D11SwapChain::presentVSync()\n\t{\n\t\tconst HRESULT hr = m_swapChain1->Present(1, 0);\n\n\t\tif (hr == DXGI_STATUS_OCCLUDED)\n\t\t{\n\t\t\t::Sleep(static_cast((1000 \/ m_displayFrequency) * 0.9));\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_RESET)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_RESET)\");\n\t\t\treturn false;\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_REMOVED)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_REMOVED)\");\n\t\t\treturn false;\n\t\t}\n\n\t\tLARGE_INTEGER counter;\n\t\t::QueryPerformanceCounter(&counter);\n\t\tm_lastPresentTime = counter.QuadPart;\n\n\t\treturn true;\n\t}\n\n\tbool D3D11SwapChain::presentNonVSync()\n\t{\n\t\t\/*\n\t\tconst double targetRefreshRateHz = m_targetFrameRateHz.value();\n\t\tconst double targetRefreshPeriodMillisec = (1000.0 \/ targetRefreshRateHz);\n\t\tconst double displayRefreshPeriodMillisec = detail::GetDisplayRefreshPeriodMillisec();\n\n\t\tLARGE_INTEGER counter;\n\t\t::QueryPerformanceCounter(&counter);\n\n\t\t{\n\t\t\tm_context->Flush();\n\n\t\t\tdouble timeToSleepMillisec = 0.0;\n\t\t\t::timeBeginPeriod(1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\t::QueryPerformanceCounter(&counter);\n\t\t\t\tconst double timeSinceFlipMillisec = detail::ToMillisec(counter.QuadPart - m_lastPresentTime);\n\n\t\t\t\ttimeToSleepMillisec = (targetRefreshPeriodMillisec - timeSinceFlipMillisec);\n\n\t\t\t\tif (timeToSleepMillisec > 0.0)\n\t\t\t\t{\n\t\t\t\t\t::Sleep(static_cast(timeToSleepMillisec));\n\t\t\t\t}\n\t\t\t} while (timeToSleepMillisec > 0.5);\n\n\t\t\t::timeEndPeriod(1);\n\t\t}\n\t\t*\/\n\n\t\tconst HRESULT hr = m_swapChain1->Present(0, 0);\n\n\t\tif (hr == DXGI_STATUS_OCCLUDED)\n\t\t{\n\t\t\t::Sleep(static_cast((1000 \/ m_displayFrequency) * 0.9));\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_RESET)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_RESET)\");\n\t\t\treturn false;\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_REMOVED)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_REMOVED)\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/m_lastPresentTime = counter.QuadPart;\n\n\t\treturn true;\n\t}\n}\n[D3D11] fix #652\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include \n# include \n# include \n# include \"D3D11SwapChain.hpp\"\n# include \n# include \n\nnamespace s3d\n{\n\tnamespace detail\n\t{\n\t\t[[nodiscard]]\n\t\tstatic double GetPerformanceFrequency()\n\t\t{\n\t\t\t::LARGE_INTEGER frequency;\n\t\t\t::QueryPerformanceFrequency(&frequency);\n\t\t\treturn static_cast(frequency.QuadPart);\n\t\t}\n\n\t\t[[nodiscard]]\n\t\tstatic double ToMillisec(const uint64 count)\n\t\t{\n\t\t\tstatic const double scale = 1'000 \/ GetPerformanceFrequency();\n\t\t\treturn count * scale;\n\t\t}\n\n\t\t[[nodiscard]]\n\t\tstatic double GetDisplayRefreshPeriodMillisec()\n\t\t{\n\t\t\tDWM_TIMING_INFO timingInfo = {};\n\t\t\ttimingInfo.cbSize = sizeof(DWM_TIMING_INFO);\n\t\t\t::DwmGetCompositionTimingInfo(nullptr, &timingInfo);\n\t\t\treturn ToMillisec(timingInfo.qpcRefreshPeriod);\n\t\t}\n\t}\n\n\tD3D11SwapChain::D3D11SwapChain(const D3D11Device& device, HWND hWnd, const Size& frameBufferSize)\n\t\t: m_hWnd(hWnd)\n\t\t, m_device(device.getDevice())\n\t\t, m_context(device.getContext())\n\t{\n\t\tLOG_SCOPED_TRACE(U\"D3D11SwapChain::D3D11SwapChain()\");\n\n\t\tm_desc.Width\t\t= frameBufferSize.x;\n\t\tm_desc.Height\t\t= frameBufferSize.y;\n\t\tm_desc.Format\t\t= DXGI_FORMAT_R8G8B8A8_UNORM;\n\t\tm_desc.Stereo\t\t= FALSE;\n\t\tm_desc.SampleDesc\t= { 1, 0 };\n\t\tm_desc.BufferUsage\t= DXGI_USAGE_RENDER_TARGET_OUTPUT;\n\t\tm_desc.BufferCount\t= 3;\n\t\tm_desc.Scaling\t\t= DXGI_SCALING_STRETCH;\n\t\tm_desc.SwapEffect\t= (device.getDXGIFactory5() ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD);\n\t\tm_desc.AlphaMode\t= DXGI_ALPHA_MODE_IGNORE;\n\t\tm_desc.Flags\t\t= 0;\n\n\t\t\/\/ Swap chain を作成\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIFactory2::CreateSwapChainForHwnd()\");\n\t\t\tif (FAILED(device.getDXGIFactory2()->CreateSwapChainForHwnd(\n\t\t\t\tm_device,\n\t\t\t\thWnd,\n\t\t\t\t&m_desc,\n\t\t\t\tnullptr,\n\t\t\t\tnullptr,\n\t\t\t\t&m_swapChain1)))\n\t\t\t{\n\t\t\t\tthrow EngineError(U\"IDXGIFactory2::CreateSwapChainForHwnd() failed\");\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIFactory1::MakeWindowAssociation()\");\n\n\t\t\tconstexpr uint32 flags = (DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);\n\n\t\t\tif (FAILED(device.getDXGIFactory2()->MakeWindowAssociation(hWnd, flags)))\n\t\t\t{\n\t\t\t\tthrow EngineError(U\"IDXGIFactory2::MakeWindowAssociation() failed\");\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tLOG_TRACE(U\"IDXGIDevice2::SetMaximumFrameLatency()\");\n\n\t\t\tif (ComPtr pDXGIDevice;\n\t\t\t\tSUCCEEDED(device.getDeiviceComPtr().As(&pDXGIDevice)))\n\t\t\t{\n\t\t\t\tpDXGIDevice->SetMaximumFrameLatency(2);\n\t\t\t}\n\t\t}\n\n\t\tupdateDisplayInfo();\n\t\tm_previousWindowBounds = Window::GetState().bounds;\n\t}\n\n\tD3D11SwapChain::~D3D11SwapChain()\n\t{\n\n\t}\n\n\tbool D3D11SwapChain::present(const bool vSync)\n\t{\n\t\tif (const Rect windowBounds = Window::GetState().bounds;\n\t\t\twindowBounds != m_previousWindowBounds)\n\t\t{\n\t\t\tupdateDisplayInfo();\n\n\t\t\tm_previousWindowBounds = windowBounds;\n\t\t}\n\n\t\t\/\/const bool vSync = (not m_targetFrameRateHz.has_value())\n\t\t\/\/\t|| ((30.0 <= m_targetFrameRateHz) && (AbsDiff(m_targetFrameRateHz.value(), m_displayFrequency) <= 3.0));\n\n\t\treturn vSync ? presentVSync() : presentNonVSync();\n\t}\n\n\tdouble D3D11SwapChain::getDisplayFrequency() const noexcept\n\t{\n\t\treturn m_displayFrequency;\n\t}\n\n\t\/\/void D3D11SwapChain::setTargetFrameRateHz(const Optional& targetFrameRateHz)\n\t\/\/{\n\t\/\/\tm_targetFrameRateHz = targetFrameRateHz;\n\t\/\/}\n\n\t\/\/const Optional& D3D11SwapChain::getTargetFrameRateHz() const noexcept\n\t\/\/{\n\t\/\/\treturn m_targetFrameRateHz;\n\t\/\/}\n\n\tIDXGISwapChain1* D3D11SwapChain::getSwapChain1() const noexcept\n\t{\n\t\treturn m_swapChain1.Get();\n\t}\n\n\tOptional D3D11SwapChain::getFullscreenRect()\n\t{\n\t\tLOG_TRACE(U\"D3D11SwapChain::getFullscreenRect()\");\n\n\t\tComPtr pOutput;\n\t\tif (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))\n\t\t{\n\t\t\treturn none;\n\t\t}\n\n\t\tDXGI_OUTPUT_DESC desc;\n\t\tif (FAILED(pOutput->GetDesc(&desc)))\n\t\t{\n\t\t\treturn none;\n\t\t}\n\n\t\treturn Rect(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top,\n\t\t\t(desc.DesktopCoordinates.right - desc.DesktopCoordinates.left),\n\t\t\t(desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top));\n\t}\n\n\tvoid D3D11SwapChain::updateDisplayInfo()\n\t{\n\t\tComPtr pOutput;\n\t\tif (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t{\n\t\t\tdouble displayFrequency;\n\n\t\t\tDXGI_OUTPUT_DESC desc;\n\t\t\tif (SUCCEEDED(pOutput->GetDesc(&desc)))\n\t\t\t{\n\t\t\t\tDEVMODE devMode = {};\n\t\t\t\tdevMode.dmSize = sizeof(DEVMODE);\n\t\t\t\t::EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &devMode);\n\t\t\t\tdisplayFrequency = devMode.dmDisplayFrequency;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdisplayFrequency = detail::GetDisplayRefreshPeriodMillisec();\n\t\t\t}\n\n\t\t\tif (displayFrequency != m_displayFrequency)\n\t\t\t{\n\t\t\t\tm_displayFrequency = displayFrequency;\n\t\t\t\tLOG_INFO(U\"Display refresh rate: {:.1f} Hz\"_fmt(m_displayFrequency));\n\t\t\t}\n\t\t}\n\t}\n\n\tbool D3D11SwapChain::presentVSync()\n\t{\n\t\tconst HRESULT hr = m_swapChain1->Present(1, 0);\n\n\t\tif (hr == DXGI_STATUS_OCCLUDED)\n\t\t{\n\t\t\t::Sleep(static_cast((1000 \/ m_displayFrequency) * 0.9));\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_RESET)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_RESET)\");\n\t\t\treturn false;\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_REMOVED)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_REMOVED)\");\n\t\t\treturn false;\n\t\t}\n\n\t\tLARGE_INTEGER counter;\n\t\t::QueryPerformanceCounter(&counter);\n\t\tm_lastPresentTime = counter.QuadPart;\n\n\t\treturn true;\n\t}\n\n\tbool D3D11SwapChain::presentNonVSync()\n\t{\n\t\t\/*\n\t\tconst double targetRefreshRateHz = m_targetFrameRateHz.value();\n\t\tconst double targetRefreshPeriodMillisec = (1000.0 \/ targetRefreshRateHz);\n\t\tconst double displayRefreshPeriodMillisec = detail::GetDisplayRefreshPeriodMillisec();\n\n\t\tLARGE_INTEGER counter;\n\t\t::QueryPerformanceCounter(&counter);\n\n\t\t{\n\t\t\tm_context->Flush();\n\n\t\t\tdouble timeToSleepMillisec = 0.0;\n\t\t\t::timeBeginPeriod(1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\t::QueryPerformanceCounter(&counter);\n\t\t\t\tconst double timeSinceFlipMillisec = detail::ToMillisec(counter.QuadPart - m_lastPresentTime);\n\n\t\t\t\ttimeToSleepMillisec = (targetRefreshPeriodMillisec - timeSinceFlipMillisec);\n\n\t\t\t\tif (timeToSleepMillisec > 0.0)\n\t\t\t\t{\n\t\t\t\t\t::Sleep(static_cast(timeToSleepMillisec));\n\t\t\t\t}\n\t\t\t} while (timeToSleepMillisec > 0.5);\n\n\t\t\t::timeEndPeriod(1);\n\t\t}\n\t\t*\/\n\n\t\tconst HRESULT hr = m_swapChain1->Present(0, 0);\n\n\t\tif (hr == DXGI_STATUS_OCCLUDED)\n\t\t{\n\t\t\t::Sleep(static_cast((1000 \/ m_displayFrequency) * 0.9));\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_RESET)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_RESET)\");\n\t\t\treturn false;\n\t\t}\n\t\telse if (hr == DXGI_ERROR_DEVICE_REMOVED)\n\t\t{\n\t\t\tLOG_FAIL(U\"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_REMOVED)\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/m_lastPresentTime = counter.QuadPart;\n\n\t\treturn true;\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"camera.hpp\"\n\nstatic const int WIDTH = 640;\nstatic const int HEIGHT = 480;\nstatic const int FPS = 6;\nstatic const int DEVICE = 0;\nstatic const std::string DIRECTORY_PATH = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\nstatic const std::string FILE_EXTENTION = \".jpg\";\/\/拡張子\n\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\nCamera::Camera()\n{\n\tif(!capture.open(DEVICE))\n\t{\n\t\tstd::cout<<\"capture is not opened 1\"<>frame;\n\t} while(frame.empty());\n\tinput = frame;\n\timwrite(timePath+FILE_EXTENTION,input);\n\treturn 0;\n}\n\n\/\/時間を元にtimePathを作る\nint Camera::makeTimePath(void)\n{\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\tchar buffer[80];\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(buffer, sizeof(buffer), \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\tstd::string str(buffer);\n\ttimePath = DIRECTORY_PATH+str;\n return 0;\n}\n\n\/\/ノイズ除去\ncv::Mat Camera::rmNoise(cv::Mat src)\n{\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);\/\/縮小処理\n\tcv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);\/\/膨張処理\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);\/\/縮小処理\n\treturn src;\n}\n\nint Camera::binarize()\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(input, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\toutput = rmNoise(hsv);\n\timwrite(timePath+\"BINARY\"+FILE_EXTENTION,output);\n\treturn 0;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble Camera::countArea()\n{\n\n\tdouble Area = output.rows*output.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(output);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tstd::cout<<\"面積のPercentageは\"<Update camera.cpp#include \n#include \n#include \n#include \"camera.hpp\"\n\nstatic const int WIDTH = 640;\nstatic const int HEIGHT = 480;\nstatic const int FPS = 6;\nstatic const int DEVICE = 0;\nstatic const std::string DIRECTORY_PATH = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\nstatic const std::string FILE_EXTENTION = \".jpg\";\/\/拡張子\n\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\nCamera::Camera()\n{\n\tif(!capture.open(DEVICE))\n\t{\n\t\tstd::cout<<\"capture is not opened 1\"<>frame;\n\t} while(frame.empty());\n\tinput = frame;\n\timwrite(timePath+FILE_EXTENTION,input);\n\treturn 0;\n}\n\n\/\/時間を元にtimePathを作る\nint Camera::makeTimePath(void)\n{\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\tchar buffer[80];\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(buffer, sizeof(buffer), \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\tstd::string str(buffer);\n\ttimePath = DIRECTORY_PATH+str;\n return 0;\n}\n\n\/\/ノイズ除去\ncv::Mat Camera::rmNoise(cv::Mat src, int a)\n{\n\tstd::vector > contours; cv::findContours(src, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n \tstd::vector > contours_subset;\n \tfor (int i = 0; ia)   \n\t\t{   \n\t\t\tcontours_subset.push_back(contours.at(i));  \n\t\t} \n\t}\n\tcv::Mat mask = cv::Mat::zeros(src.rows, src.cols, CV_8UC1); \n\tcv::drawContours(mask, contours_subset, -1, cv::Scalar(255), -1);\n \treturn mask;\n}\n\nint Camera::binarize()\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(input, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\toutput = rmNoise(hsv, 1);\n\timwrite(timePath+\"BINARY\"+FILE_EXTENTION,output);\n\treturn 0;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble Camera::countArea()\n{\n\n\tdouble Area = output.rows*output.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(output);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tstd::cout<<\"面積のPercentageは\"<"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"camera.hpp\"\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\n\n\/\/時間を元にStringを作る\nchar* makeTimeString(void)\n{\n\tstatic char timeString[N];\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(timeString, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\treturn timeString;\n}\n\nchar* makeBinaryString(char *timeString)\n{\n\tstatic char binaryString[N];\n\tsprintf(binaryString, \"%s%s\",timeString,\"Binary\");\n}\n\n\/\/full_pathを作る\nchar* makePath(char* name)\n{\n\tstatic char full_path[N];\/\/NOTE 自動変数をreturn するために使った. smartなやり方か?\n\tchar directry_path[] = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\tsprintf(full_path, \"%s%s%s\",directry_path,name, file_extention);\n\treturn full_path;\n}\n\/\/写真をとる\nint takePhoto(char* name)\n{\n\tchar full_command[N];\n\tchar front_command[] = \"raspistill -o \";\/\/command\n\tsprintf(full_command, \"%s%s\", front_command, makePath(name));\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\tprintf(\"%s\\n\",full_command);\n\t\/\/NOTE system関数以外を使うべきか?\n\treturn 0;\n}\n\n\/\/二値化画像を作成\ncv::Mat binarize(cv::Mat src)\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(src, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\treturn hsv;\n}\n\/\/ノイズ除去\ncv::Mat rmNoize(cv::Mat src)\n{\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);\/\/縮小処理\n\tcv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);\/\/膨張処理\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);\/\/縮小処理\n\treturn src;\n}\n\nint saveBinary(cv::Mat src,char* path)\n{\n\tcv::Mat binary_img;\n\tcv::resize(src,binary_img,cv::Size(),0.25,0.25);\n\treturn 0;\n}\n\n\/\/写真を撮り画像処理する\ncv::Mat Mred(void)\n{\n\tchar* stime = makeTimeString();\n\tchar* sbtime = makeBinaryString(btime);\n\tchar* path = makePath(stime);\n\tchar* bpath = makePath(sbtime);\n\ttakePhoto(path);\n \tcv::Mat src = cv::imread(path);\/\/画像の読み込み\n\tcv::Mat hsv;\n\thsv = rmNoize(binarize(src));\n\tsaveBinary(hsv,bpath);\n\treturn hsv;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble countArea(cv::Mat src)\n{\n\n\tdouble Area = src.rows*src.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(src);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tprintf(\"面積のPercentageは%f\\n\", percentage);\n\treturn percentage;\n}\n\n\/\/二値化画像のcenterを角度で返す\ndouble getCenter(cv::Mat src)\n{\n\tcv::Moments mu = cv::moments(src, false);\/\/重心の計算結果をmuに代入\n\tdouble mc = mu.m10 \/ mu.m00;\/\/重心のx座標\n\tdouble center = (mc - src.cols \/ 2) * AOV \/ src.cols;\/\/正規化\n\tprintf(\"重心の位置は%f\\n\",center);\n\treturn center;\n}\ndbeug#include \n#include \n#include \n#include \n#include \n#include \"camera.hpp\"\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\n\n\/\/時間を元にStringを作る\nchar* makeTimeString(void)\n{\n\tstatic char timeString[N];\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(timeString, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\treturn timeString;\n}\n\nchar* makeBinaryString(char *timeString)\n{\n\tstatic char binaryString[N];\n\tsprintf(binaryString, \"%s%s\",timeString,\"Binary\");\n}\n\n\/\/full_pathを作る\nchar* makePath(char* name)\n{\n\tstatic char full_path[N];\/\/NOTE 自動変数をreturn するために使った. smartなやり方か?\n\tchar directry_path[] = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\tsprintf(full_path, \"%s%s%s\",directry_path,name, file_extention);\n\treturn full_path;\n}\n\/\/写真をとる\nint takePhoto(char* name)\n{\n\tchar full_command[N];\n\tchar front_command[] = \"raspistill -o \";\/\/command\n\tsprintf(full_command, \"%s%s\", front_command, makePath(name));\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\tprintf(\"%s\\n\",full_command);\n\t\/\/NOTE system関数以外を使うべきか?\n\treturn 0;\n}\n\n\/\/二値化画像を作成\ncv::Mat binarize(cv::Mat src)\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(src, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\treturn hsv;\n}\n\/\/ノイズ除去\ncv::Mat rmNoize(cv::Mat src)\n{\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);\/\/縮小処理\n\tcv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);\/\/膨張処理\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);\/\/縮小処理\n\treturn src;\n}\n\nint saveBinary(cv::Mat src,char* path)\n{\n\tcv::Mat binary_img;\n\tcv::resize(src,binary_img,cv::Size(),0.25,0.25);\n\treturn 0;\n}\n\n\/\/写真を撮り画像処理する\ncv::Mat Mred(void)\n{\n\tchar* stime = makeTimeString();\n\tchar* sbtime = makeBinaryString(stime);\n\tchar* path = makePath(stime);\n\tchar* bpath = makePath(sbtime);\n\ttakePhoto(path);\n \tcv::Mat src = cv::imread(path);\/\/画像の読み込み\n\tcv::Mat hsv;\n\thsv = rmNoize(binarize(src));\n\tsaveBinary(hsv,bpath);\n\treturn hsv;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble countArea(cv::Mat src)\n{\n\n\tdouble Area = src.rows*src.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(src);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tprintf(\"面積のPercentageは%f\\n\", percentage);\n\treturn percentage;\n}\n\n\/\/二値化画像のcenterを角度で返す\ndouble getCenter(cv::Mat src)\n{\n\tcv::Moments mu = cv::moments(src, false);\/\/重心の計算結果をmuに代入\n\tdouble mc = mu.m10 \/ mu.m00;\/\/重心のx座標\n\tdouble center = (mc - src.cols \/ 2) * AOV \/ src.cols;\/\/正規化\n\tprintf(\"重心の位置は%f\\n\",center);\n\treturn center;\n}\n<|endoftext|>"} {"text":"#define _USE_MATH_DEFINES\n#include \n#include \"Neuralnetwork.h\"\nusing namespace std;\n\nint main () {\n\t\/* xor example:*\/\n\t\/*\n\tvector init{2, 3, 1};\n\tvector> inputs(2);\n\tvector> outputs(1);\n\tinputs[0] = vector{ 0, 0, 1, 1};\n\tinputs[1] = vector{ 0, 1, 0, 1};\n\toutputs[0] = vector{0, 1, 1, 0};\n\tNeural_network nn{init, 0.1};\n\tnn(inputs, outputs, 10000);\n\n\tNeural_network::test(nn, vector{1, 1}, vector{0});\n\tNeural_network::test(nn, vector{1., 0}, vector{1});\n\tNeural_network::test(nn, vector{0, 1.}, vector{1});\n\tNeural_network::test(nn, vector{0, 0}, vector{0});\n\t\/**\/\n\n\t\/*sine example:*\/\n\n\tvector init{1, 2, 1};\n\tvector> inputs(1);\n\tvector> outputs(1);\n\tNeural_network nn{init, 0.1};\n\n\tinputs[0] = vector(50);\n\toutputs[0] = vector(50);\n\tfor (size_t i=0; i < inputs[0].size(); i++) {\n\t\tinputs[0][i] = i*M_PI*2.\/double(inputs[0].size());\n\t\toutputs[0][i] = sin(inputs[0][i]);\n\t}\n\tnn(inputs, outputs, 10000);\n\n\tNeural_network::test(nn, vector{0.}, vector{sin(0.)});\n\tNeural_network::test(nn, vector{0.5}, vector{sin(0.5)});\n\tNeural_network::test(nn, vector{1.5}, vector{sin(1.5)});\n\tNeural_network::test(nn, vector{3.1}, vector{sin(3.1)});\n\tNeural_network::test(nn, vector{4.}, vector{sin(4.)});\n\tNeural_network::test(nn, vector{4.5}, vector{sin(4.5)});\n\t\/**\/\n\n\treturn 0;\n}\nnegative codomain of sine is not calculated correctly.#define _USE_MATH_DEFINES\n#include \n#include \"Neuralnetwork.h\"\nusing namespace std;\n\nint main () {\n\t\/* xor example:*\/\n\t\/*\n\tvector init{2, 3, 1};\n\tvector> inputs(2);\n\tvector> outputs(1);\n\tinputs[0] = vector{ 0, 0, 1, 1};\n\tinputs[1] = vector{ 0, 1, 0, 1};\n\toutputs[0] = vector{0, 1, 1, 0};\n\tNeural_network nn{init, 0.1};\n\tnn(inputs, outputs, 10000);\n\n\tNeural_network::test(nn, vector{1, 1}, vector{0});\n\tNeural_network::test(nn, vector{1., 0}, vector{1});\n\tNeural_network::test(nn, vector{0, 1.}, vector{1});\n\tNeural_network::test(nn, vector{0, 0}, vector{0});\n\t\/**\/\n\n\t\/*sine example:*\/\n\n\tvector init{1, 3, 1};\n\tvector> inputs(1);\n\tvector> outputs(1);\n\tNeural_network nn{init, 0.1};\n\n\tinputs[0] = vector(30);\n\toutputs[0] = vector(30);\n\tfor (size_t i=0; i < inputs[0].size(); i++) {\n\t\tinputs[0][i] = i*M_PI*2.\/double(inputs[0].size());\n\t\toutputs[0][i] = sin(inputs[0][i]);\n\t}\n\tnn(inputs, outputs, 20000);\n\n\tNeural_network::test(nn, vector{0.}, vector{sin(0.)});\n\tNeural_network::test(nn, vector{0.5}, vector{sin(0.5)});\n\tNeural_network::test(nn, vector{1.5}, vector{sin(1.5)});\n\tNeural_network::test(nn, vector{3.1}, vector{sin(3.1)});\n\tNeural_network::test(nn, vector{4.}, vector{sin(4.)});\n\tNeural_network::test(nn, vector{4.5}, vector{sin(4.5)});\n\tNeural_network::test(nn, vector{5.}, vector{sin(5)});\n\tNeural_network::test(nn, vector{6.}, vector{sin(6)});\n\t\/**\/\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"message.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ tmp\n#include \"Utils\/Debug.hpp\"\n\nAGE_NOT_OPTIMIZED_BLOCK_BEGIN\n\nnamespace TMQ\n{\n\tclass ReleasableQueue;\n\tclass Dispatcher;\n\tclass Messsage;\n\tclass ImmediateQueue;\n\tclass HybridQueue;\n\n\tclass PtrQueue\n\t{\n\tpublic:\n\t\tPtrQueue(const TMQ::PtrQueue &o);\n\t\tPtrQueue& operator=(const TMQ::PtrQueue &o);\n\t\tPtrQueue(std::size_t chunkSize = 1024);\n\t\tPtrQueue& operator=(TMQ::PtrQueue &&o);\n\t\tPtrQueue(TMQ::PtrQueue &&o);\n\t\t~PtrQueue();\n\t\tvoid pop();\n\t\tMessageBase *front();\n\t\tstd::size_t getFrontSize();\n\t\tvoid clear();\n\t\tvoid eraseAll();\n\t\tbool empty();\n\tprivate:\n\t\tstd::size_t _chunkSize;\n\t\tstruct Chunk\n\t\t{\n\t\t\tchar *_data;\n\t\t\tstd::size_t _cursor;\n\t\t\tstd::size_t _size;\n\t\t\tstd::size_t _to;\n\n\t\t\tChunk() = delete;\n\t\t\tChunk(const Chunk &o) = delete;\n\t\t\tChunk& operator=(const Chunk &o) = delete;\n\t\t\tChunk(std::size_t chunkSize);\n\t\t\tChunk& operator=(Chunk &&o);\n\t\t\tChunk(Chunk &&o);\n\t\t\t~Chunk();\n\t\t\tvoid pop();\n\t\t\tMessageBase *front();\n\t\t\tstd::size_t getFrontSize();\n\t\t\tvoid clear();\n\t\t\tvoid eraseAll();\n\t\t\tvoid release();\n\t\t\tbool empty();\n\n\t\t\ttemplate \n\t\t\tT* push(const T& e)\n\t\t\t{\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tassert(s < _chunkSize + sizeOfInt);\n\t\t\t\t\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(e);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tT* push(T&& e)\n\t\t\t{\n\t\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(std::move(e));\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\n\t\t\tbool move(MessageBase *e, std::size_t size)\n\t\t\t{\n\t\t\t\tstd::size_t s = size;\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\te->clone(tmp);\n\t\t\t\tauto test = (MessageBase*)(tmp);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tT* emplace(Args ...args)\n\t\t\t{\n\t\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(args...);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\t\t};\n\t\tstd::list _list;\n\t\tstd::list::iterator _listReader;\n\t\tstd::list::iterator _listWriter;\n\n\t\ttemplate \n\t\tT* push(const T& e)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->push(e);\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn push(e);\n\t\t\t}\n\t\t}\n\n\t\ttemplate \n\t\tT* push(T&& e)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->push(std::move(e));\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn push(e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tbool move(MessageBase *e, std::size_t size)\n\t\t{\n\t\t\tstd::size_t s = size;\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tif ((*_listWriter)->move(std::move(e), size))\n\t\t\t\treturn true;\n\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t{\n\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t}\n\t\t\telse\n\t\t\t\t++_listWriter;\n\t\t\treturn (*_listWriter)->move(std::move(e), size);\n\t\t}\n\n\t\ttemplate \n\t\tT* emplace(Args ...args)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->emplace(args...);\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn emplace(args...);\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t\tfriend class ReleasableQueue;\n\t\tfriend class ImmediateQueue;\n\t\tfriend class HybridQueue;\n\t};\n\n\tclass HybridQueue\n\t{\n\t\tstatic std::queue _sharedQueue;\n\t\tstd::queue _individualQueue;\n\t\tstatic std::mutex _mutex;\n\t\tstatic std::condition_variable _condition;\n\tpublic:\n\t\tHybridQueue();\n\n\t\tHybridQueue(const HybridQueue&) = delete;\n\t\tHybridQueue &operator=(const HybridQueue&) = delete;\n\t\tHybridQueue(HybridQueue &&) = delete;\n\t\tHybridQueue &operator=(HybridQueue &&) = delete;\n\n\t\tvoid getTask(MessageBase *& task);\n\t\tvoid tryToGetTask(MessageBase *& task, std::size_t microSeconds);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/ TASKS\n\n\t\ttemplate \n\t\tvoid pushTask(const T& e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(new Message(e));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tvoid emplaceTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(new Message(args...));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstd::future pushFutureTask(const T &e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tauto tmp = new Message(e);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\tstd::future < F > f;\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t\ttemplate \n\t\tstd::future emplaceFutureTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future< F > f;\n\t\t\tauto tmp = new Message(args...);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\n\t\t\/\/\/\/\/\/\/\n\t\t\/\/ SHARED\n\n\t\ttemplate \n\t\tstatic void pushSharedTask(const T& e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(new Message(e));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstatic void emplaceSharedTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(new Message(args...));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstatic std::future pushSharedFutureTask(const T &e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future < F > f;\n\t\t\tauto tmp = new Message(e);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t\ttemplate \n\t\tstatic std::future emplaceSharedFutureTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future< F > f;\n\t\t\tauto tmp = new Message(args...);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t};\n\n}\nAGE_NOT_OPTIMIZED_BLOCK_END\nQueue optimized#pragma once\n\n#include \"message.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ tmp\n#include \"Utils\/Debug.hpp\"\n\nnamespace TMQ\n{\n\tclass ReleasableQueue;\n\tclass Dispatcher;\n\tclass Messsage;\n\tclass ImmediateQueue;\n\tclass HybridQueue;\n\n\tclass PtrQueue\n\t{\n\tpublic:\n\t\tPtrQueue(const TMQ::PtrQueue &o);\n\t\tPtrQueue& operator=(const TMQ::PtrQueue &o);\n\t\tPtrQueue(std::size_t chunkSize = 1024);\n\t\tPtrQueue& operator=(TMQ::PtrQueue &&o);\n\t\tPtrQueue(TMQ::PtrQueue &&o);\n\t\t~PtrQueue();\n\t\tvoid pop();\n\t\tMessageBase *front();\n\t\tstd::size_t getFrontSize();\n\t\tvoid clear();\n\t\tvoid eraseAll();\n\t\tbool empty();\n\tprivate:\n\t\tstd::size_t _chunkSize;\n\t\tstruct Chunk\n\t\t{\n\t\t\tchar *_data;\n\t\t\tstd::size_t _cursor;\n\t\t\tstd::size_t _size;\n\t\t\tstd::size_t _to;\n\n\t\t\tChunk() = delete;\n\t\t\tChunk(const Chunk &o) = delete;\n\t\t\tChunk& operator=(const Chunk &o) = delete;\n\t\t\tChunk(std::size_t chunkSize);\n\t\t\tChunk& operator=(Chunk &&o);\n\t\t\tChunk(Chunk &&o);\n\t\t\t~Chunk();\n\t\t\tvoid pop();\n\t\t\tMessageBase *front();\n\t\t\tstd::size_t getFrontSize();\n\t\t\tvoid clear();\n\t\t\tvoid eraseAll();\n\t\t\tvoid release();\n\t\t\tbool empty();\n\n\t\t\ttemplate \n\t\t\tT* push(const T& e)\n\t\t\t{\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tassert(s < _chunkSize + sizeOfInt);\n\t\t\t\t\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(e);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tT* push(T&& e)\n\t\t\t{\n\t\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(std::move(e));\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\n\t\t\tbool move(MessageBase *e, std::size_t size)\n\t\t\t{\n\t\t\t\tstd::size_t s = size;\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\te->clone(tmp);\n\t\t\t\tauto test = (MessageBase*)(tmp);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tT* emplace(Args ...args)\n\t\t\t{\n\t\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\t\tstd::size_t s = sizeof(Message);\n\t\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\n\t\t\t\tif (_size - _to < s + sizeOfInt)\n\t\t\t\t{\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tchar *tmp = _data;\n\t\t\t\ttmp += _to;\n\t\t\t\tmemcpy(tmp, &s, sizeOfInt);\n\t\t\t\ttmp += sizeOfInt;\n\t\t\t\tMessage* res = new(tmp)Message(args...);\n\t\t\t\t_to += sizeOfInt + s;\n\t\t\t\treturn &res->_data;\n\t\t\t}\n\t\t};\n\t\tstd::list _list;\n\t\tstd::list::iterator _listReader;\n\t\tstd::list::iterator _listWriter;\n\n\t\ttemplate \n\t\tT* push(const T& e)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->push(e);\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn push(e);\n\t\t\t}\n\t\t}\n\n\t\ttemplate \n\t\tT* push(T&& e)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->push(std::move(e));\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn push(e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tbool move(MessageBase *e, std::size_t size)\n\t\t{\n\t\t\tstd::size_t s = size;\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tif ((*_listWriter)->move(std::move(e), size))\n\t\t\t\treturn true;\n\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t{\n\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t}\n\t\t\telse\n\t\t\t\t++_listWriter;\n\t\t\treturn (*_listWriter)->move(std::move(e), size);\n\t\t}\n\n\t\ttemplate \n\t\tT* emplace(Args ...args)\n\t\t{\n\t\t\tassert(sizeof(T) % 4 == 0);\n\t\t\tstd::size_t s = sizeof(Message);\n\t\t\tstd::size_t sizeOfInt = sizeof(std::size_t);\n\t\t\tassert(s + sizeOfInt < _chunkSize);\n\n\t\t\tauto res = (*_listWriter)->emplace(args...);\n\t\t\tif (!res)\n\t\t\t{\n\t\t\t\tif (_listWriter == --std::end(_list))\n\t\t\t\t{\n\t\t\t\t\t_list.push_back(new Chunk(_chunkSize));\n\t\t\t\t\t_listWriter = --std::end(_list);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t++_listWriter;\n\t\t\t\treturn emplace(args...);\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t\tfriend class ReleasableQueue;\n\t\tfriend class ImmediateQueue;\n\t\tfriend class HybridQueue;\n\t};\n\n\tclass HybridQueue\n\t{\n\t\tstatic std::queue _sharedQueue;\n\t\tstd::queue _individualQueue;\n\t\tstatic std::mutex _mutex;\n\t\tstatic std::condition_variable _condition;\n\tpublic:\n\t\tHybridQueue();\n\n\t\tHybridQueue(const HybridQueue&) = delete;\n\t\tHybridQueue &operator=(const HybridQueue&) = delete;\n\t\tHybridQueue(HybridQueue &&) = delete;\n\t\tHybridQueue &operator=(HybridQueue &&) = delete;\n\n\t\tvoid getTask(MessageBase *& task);\n\t\tvoid tryToGetTask(MessageBase *& task, std::size_t microSeconds);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/ TASKS\n\n\t\ttemplate \n\t\tvoid pushTask(const T& e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(new Message(e));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tvoid emplaceTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(new Message(args...));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstd::future pushFutureTask(const T &e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tauto tmp = new Message(e);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\tstd::future < F > f;\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t\ttemplate \n\t\tstd::future emplaceFutureTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future< F > f;\n\t\t\tauto tmp = new Message(args...);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_individualQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\n\t\t\/\/\/\/\/\/\/\n\t\t\/\/ SHARED\n\n\t\ttemplate \n\t\tstatic void pushSharedTask(const T& e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(new Message(e));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstatic void emplaceSharedTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(new Message(args...));\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t}\n\n\t\ttemplate \n\t\tstatic std::future pushSharedFutureTask(const T &e)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future < F > f;\n\t\t\tauto tmp = new Message(e);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t\ttemplate \n\t\tstatic std::future emplaceSharedFutureTask(Args ...args)\n\t\t{\n\t\t\tSCOPE_profile_cpu_function(\"TMQ\");\n\t\t\tstd::future< F > f;\n\t\t\tauto tmp = new Message(args...);\n\t\t\tf = tmp->getData().getFuture();\n\t\t\t{\n\t\t\t\tstd::lock_guard lock(_mutex);\n\t\t\t\t_sharedQueue.push(tmp);\n\t\t\t}\n\t\t\t_condition.notify_all();\n\t\t\treturn f;\n\t\t}\n\n\t};\n\n}\n<|endoftext|>"} {"text":"\/\/ Minimal usage example: prints a hash. Tested on x86, ppc, arm.\n\n#include \"highwayhash\/highwayhash.h\"\n\n#include \n#include \n\nusing namespace highwayhash;\n\nint main(int argc, char* argv[]) {\n \/\/ Please use a different key to ensure your hashes aren't identical.\n const HHKey key HH_ALIGNAS(32) = {1, 2, 3, 4};\n \/\/ Aligning inputs to 32 bytes may help but is not required.\n const char in[] = \"bytes_to_hash\";\n \/\/ Type determines the hash size; can also be HHResult128 or HHResult256.\n HHResult64 result;\n \/\/ HH_TARGET_PREFERRED expands to the best specialization available for the\n \/\/ CPU detected via compiler flags (e.g. AVX2 #ifdef __AVX2__).\n HHStateT state(key);\n \/\/ Using argc prevents the compiler from eliding the hash computations.\n const size_t size = std::min(sizeof(in), static_cast(argc));\n HighwayHashT(&state, in, size, &result);\n std::cout << \"Hash : \" << result << std::endl;\n\n HighwayHashCatT cat(key);\n cat.Append(in, size);\n cat.Finalize(&result);\n std::cout << \"HashCat: \" << result << std::endl;\n return 0;\n}\nSimplified example, thanks Lode Vandevenne\/\/ Minimal usage example: prints a hash. Tested on x86, ppc, arm.\n\n#include \"highwayhash\/highwayhash.h\"\n\n#include \n#include \n\nusing namespace highwayhash;\n\nint main(int argc, char* argv[]) {\n \/\/ We read from the args on purpose, to ensure a compile time constant will\n \/\/ not be used, for verifying assembly on the supported platforms.\n if (argc != 2) {\n std::cout << \"Please provide 1 argument with a text to hash\" << std::endl;\n return 1;\n }\n\n \/\/ Please use a different key to ensure your hashes aren't identical.\n const HHKey key HH_ALIGNAS(32) = {1, 2, 3, 4};\n\n \/\/ Aligning inputs to 32 bytes may help but is not required.\n const char* in = argv[1];\n const size_t size = strlen(in);\n\n \/\/ Type determines the hash size; can also be HHResult128 or HHResult256.\n HHResult64 result;\n\n \/\/ HH_TARGET_PREFERRED expands to the best specialization available for the\n \/\/ CPU detected via compiler flags (e.g. AVX2 #ifdef __AVX2__).\n HHStateT state(key);\n HighwayHashT(&state, in, size, &result);\n std::cout << \"Hash : \" << result << std::endl;\n\n HighwayHashCatT cat(key);\n cat.Append(in, size);\n cat.Finalize(&result);\n std::cout << \"HashCat: \" << result << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Convert file supported by xylib to ascii format\n\/\/ Licence: Lesser GNU Public License 2.1 (LGPL)\n\/\/ $Id$\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"xylib\/xylib.h\"\n\nusing namespace std;\n\nvoid print_usage()\n{\n cout <<\n\"Usage:\\n\"\n\"\\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\\n\"\n\"\\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\\n\"\n\"\\txyconv -i FILETYPE\\n\"\n\"\\txyconv -g INPUT_FILE ...\\n\"\n\"\\txyconv [-l|-v|-h]\\n\"\n\" Converts INPUT_FILE to ascii OUTPUT_FILE\\n\"\n\" -t specify filetype of input file\\n\"\n\" -m convert one or multiple files; output files have the same name\\n\"\n\" as input, but with extension changed to .xy\\n\"\n\" -l list all supported file types\\n\"\n\" -v output version information and exit\\n\"\n\" -h show this help message and exit\\n\"\n\" -i show information about filetype\\n\"\n\" -s do not output metadata\\n\"\n\" -g guess filetype of file \\n\";\n}\n\n\/\/ Print version of the library. This program is too small to have own version.\nvoid print_version()\n{\n cout << XYLIB_VERSION \/ 10000 << \".\"\n << XYLIB_VERSION \/ 100 % 100 << \".\"\n << XYLIB_VERSION % 100 << endl;\n}\n\nvoid list_supported_formats()\n{\n const xylibFormat* format = NULL;\n for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i)\n cout << setw(20) << left << format->name << \": \"\n << format->desc << endl;\n}\n\nint print_guessed_filetype(int n, char** paths)\n{\n bool ok = true;\n for (int i = 0; i < n; ++i) {\n const char* path = paths[i];\n if (n > 1)\n cout << path << \": \";\n try {\n ifstream is(path);\n if (!is) {\n cout << \"Error: can't open input file: \" << path;\n ok = false;\n }\n xylib::FormatInfo const* fi = xylib::guess_filetype(path, is);\n if (fi)\n cout << fi->name << \": \" << fi->desc << endl;\n else\n cout << \"Format of the file was not detected\\n\";\n } catch (runtime_error const& e) {\n cout << \"Error: \" << e.what() << endl;\n ok = false;\n }\n }\n return ok ? 0 : -1;\n}\n\nvoid print_filetype_info(string const& filetype)\n{\n xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str());\n if (fi) {\n cout << \"Name: \" << fi->name << endl;\n cout << \"Description: \" << fi->desc << endl;\n bool has_exts = (strlen(fi->exts) != 0);\n cout << \"Possible extensions: \"\n << (has_exts ? fi->exts : \"(not specified)\") << endl;\n cout << \"Other flags: \"\n << (fi->binary ? \"binary-file\" : \"text-file\") << \" \"\n << (fi->multiblock ? \"multi-block\" : \"single-block\") << endl;\n }\n else\n cout << \"Unknown file format.\" << endl;\n}\n\nvoid export_metadata(ostream &of, xylib::MetaData const& meta)\n{\n for (size_t i = 0; i != meta.size(); ++i) {\n const string& key = meta.get_key(i);\n const string& value = meta.get(key);\n of << \"# \" << key << \": \";\n \/\/ value can be multiline\n for (string::const_iterator j = value.begin(); j != value.end(); ++j) {\n of << *j;\n if (*j == '\\n')\n of << \"# \" << key << \": \";\n }\n of << endl;\n }\n}\n\nvoid export_plain_text(xylib::DataSet const *d, string const &fname,\n bool with_metadata)\n{\n int range_num = d->get_block_count();\n ofstream of(fname.c_str());\n if (!of)\n throw xylib::RunTimeError(\"can't create file: \" + fname);\n\n \/\/ output the file-level meta-info\n of << \"# exported by xylib from a \" << d->fi->name << \" file\" << endl;\n if (with_metadata) {\n export_metadata(of, d->meta);\n of << endl;\n }\n\n for (int i = 0; i < range_num; ++i) {\n const xylib::Block *block = d->get_block(i);\n if (range_num > 1 || !block->get_name().empty())\n of << \"\\n### block #\" << i << \" \" << block->get_name() << endl;\n if (with_metadata)\n export_metadata(of, block->meta);\n\n int ncol = block->get_column_count();\n of << \"# \";\n \/\/ column 0 is pseudo-column with point indices, we skip it\n for (int k = 1; k <= ncol; ++k) {\n string const& name = block->get_column(k).get_name();\n if (k > 1)\n of << \"\\t\";\n if (name.empty())\n of << \"column_\" << k;\n else\n of << name;\n }\n of << endl;\n\n int nrow = block->get_point_count();\n\n for (int j = 0; j < nrow; ++j) {\n for (int k = 1; k <= ncol; ++k) {\n if (k > 1)\n of << \"\\t\";\n of << setfill(' ') << setiosflags(ios::fixed)\n << setprecision(6) << setw(8)\n << block->get_column(k).get_value(j);\n }\n of << endl;\n }\n }\n}\n\n\nint convert_file(string const& input, string const& output,\n string const& filetype, bool with_metadata)\n{\n try {\n xylib::DataSet *d = xylib::load_file(input, filetype);\n export_plain_text(d, output, with_metadata);\n delete d;\n } catch (runtime_error const& e) {\n cerr << \"Error. \" << e.what() << endl;\n return -1;\n }\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n \/\/ options -l -h -i -g -v are not combined with other options\n\n if (argc == 2 && strcmp(argv[1], \"-l\") == 0) {\n list_supported_formats();\n return 0;\n }\n else if (argc == 2 &&\n (strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0)) {\n print_usage();\n return 0;\n }\n else if (argc == 2 &&\n (strcmp(argv[1], \"-v\") == 0 || strcmp(argv[1], \"--version\") == 0)) {\n print_version();\n return 0;\n }\n else if (argc == 3 && strcmp(argv[1], \"-i\") == 0) {\n print_filetype_info(argv[2]);\n return 0;\n }\n else if (argc >= 3 && strcmp(argv[1], \"-g\") == 0)\n return print_guessed_filetype(argc - 2, argv + 2);\n else if (argc < 3) {\n print_usage();\n return -1;\n }\n\n string filetype;\n bool option_m = false;\n bool option_s = false;\n int n = 1;\n while (n < argc - 1) {\n if (strcmp(argv[n], \"-m\") == 0) {\n option_m = true;\n ++n;\n }\n else if (strcmp(argv[n], \"-s\") == 0) {\n option_s = true;\n ++n;\n }\n else if (strcmp(argv[n], \"-t\") == 0 && n+1 < argc - 1) {\n filetype = argv[n+1];\n n += 2;\n }\n else\n break;\n }\n if (!option_m && n != argc - 2) {\n print_usage();\n return -1;\n }\n if (option_m) {\n for ( ; n < argc; ++n) {\n string out = argv[n];\n size_t p = out.rfind('.');\n if (p != string::npos)\n out.erase(p);\n out += \".xy\";\n cout << \"converting \" << argv[n] << \" to \" << out << endl;\n convert_file(argv[n], out, filetype, !option_s);\n }\n return 0;\n }\n else\n return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s);\n}\n\ncosmetic tweaks in xyconv\/\/ Convert file supported by xylib to ascii format\n\/\/ Licence: Lesser GNU Public License 2.1 (LGPL)\n\/\/ $Id$\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"xylib\/xylib.h\"\n\nusing namespace std;\n\nvoid print_usage()\n{\n cout <<\n\"Usage:\\n\"\n\"\\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\\n\"\n\"\\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\\n\"\n\"\\txyconv -i FILETYPE\\n\"\n\"\\txyconv -g INPUT_FILE ...\\n\"\n\"\\txyconv [-l|-v|-h]\\n\"\n\" Converts INPUT_FILE to ascii OUTPUT_FILE\\n\"\n\" -t specify filetype of input file\\n\"\n\" -m convert one or multiple files; output files have the same name\\n\"\n\" as input, but with extension changed to .xy\\n\"\n\" -l list all supported file types\\n\"\n\" -v output version information and exit\\n\"\n\" -h show this help message and exit\\n\"\n\" -i show information about filetype\\n\"\n\" -s do not output metadata\\n\"\n\" -g guess filetype of file \\n\";\n}\n\n\/\/ Print version of the library. This program is too small to have own version.\nvoid print_version()\n{\n cout << XYLIB_VERSION \/ 10000 << \".\"\n << XYLIB_VERSION \/ 100 % 100 << \".\"\n << XYLIB_VERSION % 100 << endl;\n}\n\nvoid list_supported_formats()\n{\n const xylibFormat* format = NULL;\n for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i)\n cout << setw(20) << left << format->name << \": \"\n << format->desc << endl;\n}\n\nint print_guessed_filetype(int n, char** paths)\n{\n bool ok = true;\n for (int i = 0; i < n; ++i) {\n const char* path = paths[i];\n if (n > 1)\n cout << path << \": \";\n try {\n ifstream is(path);\n if (!is) {\n cout << \"Error: can't open input file: \" << path << endl;\n ok = false;\n continue;\n }\n xylib::FormatInfo const* fi = xylib::guess_filetype(path, is);\n if (fi)\n cout << fi->name << \": \" << fi->desc << endl;\n else\n cout << \"Format of the file was not detected\\n\";\n } catch (runtime_error const& e) {\n cout << \"Error: \" << e.what() << endl;\n ok = false;\n }\n }\n return ok ? 0 : -1;\n}\n\nvoid print_filetype_info(string const& filetype)\n{\n xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str());\n if (fi) {\n cout << \"Name: \" << fi->name << endl;\n cout << \"Description: \" << fi->desc << endl;\n bool has_exts = (strlen(fi->exts) != 0);\n cout << \"Possible extensions: \"\n << (has_exts ? fi->exts : \"(not specified)\") << endl;\n cout << \"Other flags: \"\n << (fi->binary ? \"binary-file\" : \"text-file\") << \" \"\n << (fi->multiblock ? \"multi-block\" : \"single-block\") << endl;\n }\n else\n cout << \"Unknown file format.\" << endl;\n}\n\nvoid export_metadata(ostream &of, xylib::MetaData const& meta)\n{\n for (size_t i = 0; i != meta.size(); ++i) {\n const string& key = meta.get_key(i);\n const string& value = meta.get(key);\n of << \"# \" << key << \": \";\n \/\/ value can be multiline\n for (string::const_iterator j = value.begin(); j != value.end(); ++j) {\n of << *j;\n if (*j == '\\n')\n of << \"# \" << key << \": \";\n }\n of << endl;\n }\n}\n\nvoid export_plain_text(xylib::DataSet const *d, string const &fname,\n bool with_metadata)\n{\n int range_num = d->get_block_count();\n ofstream of(fname.c_str());\n if (!of)\n throw xylib::RunTimeError(\"can't create file: \" + fname);\n\n \/\/ output the file-level meta-info\n of << \"# exported by xylib from a \" << d->fi->name << \" file\" << endl;\n if (with_metadata) {\n export_metadata(of, d->meta);\n of << endl;\n }\n\n for (int i = 0; i < range_num; ++i) {\n const xylib::Block *block = d->get_block(i);\n if (range_num > 1 || !block->get_name().empty())\n of << \"\\n### block #\" << i << \" \" << block->get_name() << endl;\n if (with_metadata)\n export_metadata(of, block->meta);\n\n int ncol = block->get_column_count();\n of << \"# \";\n \/\/ column 0 is pseudo-column with point indices, we skip it\n for (int k = 1; k <= ncol; ++k) {\n string const& name = block->get_column(k).get_name();\n if (k > 1)\n of << \"\\t\";\n if (name.empty())\n of << \"column_\" << k;\n else\n of << name;\n }\n of << endl;\n\n int nrow = block->get_point_count();\n\n for (int j = 0; j < nrow; ++j) {\n for (int k = 1; k <= ncol; ++k) {\n if (k > 1)\n of << \"\\t\";\n of << setfill(' ') << setiosflags(ios::fixed)\n << setprecision(6) << setw(8)\n << block->get_column(k).get_value(j);\n }\n of << endl;\n }\n }\n}\n\n\nint convert_file(string const& input, string const& output,\n string const& filetype, bool with_metadata)\n{\n try {\n xylib::DataSet *d = xylib::load_file(input, filetype);\n export_plain_text(d, output, with_metadata);\n delete d;\n } catch (runtime_error const& e) {\n cerr << \"Error. \" << e.what() << endl;\n return -1;\n }\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n \/\/ options -l -h -i -g -v are not combined with other options\n\n if (argc == 2 && strcmp(argv[1], \"-l\") == 0) {\n list_supported_formats();\n return 0;\n }\n else if (argc == 2 &&\n (strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0)) {\n print_usage();\n return 0;\n }\n else if (argc == 2 &&\n (strcmp(argv[1], \"-v\") == 0 || strcmp(argv[1], \"--version\") == 0)) {\n print_version();\n return 0;\n }\n else if (argc == 3 && strcmp(argv[1], \"-i\") == 0) {\n print_filetype_info(argv[2]);\n return 0;\n }\n else if (argc >= 3 && strcmp(argv[1], \"-g\") == 0)\n return print_guessed_filetype(argc - 2, argv + 2);\n else if (argc < 3) {\n print_usage();\n return -1;\n }\n\n string filetype;\n bool option_m = false;\n bool option_s = false;\n int n = 1;\n while (n < argc - 1) {\n if (strcmp(argv[n], \"-m\") == 0) {\n option_m = true;\n ++n;\n }\n else if (strcmp(argv[n], \"-s\") == 0) {\n option_s = true;\n ++n;\n }\n else if (strcmp(argv[n], \"-t\") == 0 && n+1 < argc - 1) {\n filetype = argv[n+1];\n n += 2;\n }\n else\n break;\n }\n if (!option_m && n != argc - 2) {\n print_usage();\n return -1;\n }\n if (option_m) {\n for ( ; n < argc; ++n) {\n string out = argv[n];\n size_t p = out.rfind('.');\n if (p != string::npos)\n out.erase(p);\n out += \".xy\";\n cout << \"converting \" << argv[n] << \" to \" << out << endl;\n convert_file(argv[n], out, filetype, !option_s);\n }\n return 0;\n }\n else\n return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s);\n}\n\n<|endoftext|>"} {"text":"ada0f03c-2e4c-11e5-9284-b827eb9e62beada5e4b6-2e4c-11e5-9284-b827eb9e62beada5e4b6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"be26f238-2e4e-11e5-9284-b827eb9e62bebe2c0480-2e4e-11e5-9284-b827eb9e62bebe2c0480-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"32a18d32-2e4d-11e5-9284-b827eb9e62be32a6aec0-2e4d-11e5-9284-b827eb9e62be32a6aec0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ab829188-2e4d-11e5-9284-b827eb9e62beab87993a-2e4d-11e5-9284-b827eb9e62beab87993a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c8481596-2e4c-11e5-9284-b827eb9e62bec84d0272-2e4c-11e5-9284-b827eb9e62bec84d0272-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c57ef9be-2e4d-11e5-9284-b827eb9e62bec58424ac-2e4d-11e5-9284-b827eb9e62bec58424ac-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ec8a5a3e-2e4e-11e5-9284-b827eb9e62beec8f585e-2e4e-11e5-9284-b827eb9e62beec8f585e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c49e9ebe-2e4d-11e5-9284-b827eb9e62bec4a398e2-2e4d-11e5-9284-b827eb9e62bec4a398e2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0db630ac-2e4f-11e5-9284-b827eb9e62be0dbb42b8-2e4f-11e5-9284-b827eb9e62be0dbb42b8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5be03d6a-2e4d-11e5-9284-b827eb9e62be5be53d88-2e4d-11e5-9284-b827eb9e62be5be53d88-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"aaddc668-2e4c-11e5-9284-b827eb9e62beaae2b4c0-2e4c-11e5-9284-b827eb9e62beaae2b4c0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ee893780-2e4c-11e5-9284-b827eb9e62beee8e1f70-2e4c-11e5-9284-b827eb9e62beee8e1f70-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ddff7ece-2e4c-11e5-9284-b827eb9e62bede0473d4-2e4c-11e5-9284-b827eb9e62bede0473d4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f2ac662a-2e4c-11e5-9284-b827eb9e62bef2b17098-2e4c-11e5-9284-b827eb9e62bef2b17098-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"6dbc5fe6-2e4d-11e5-9284-b827eb9e62be6dc16b58-2e4d-11e5-9284-b827eb9e62be6dc16b58-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c141db9a-2e4e-11e5-9284-b827eb9e62bec146dae6-2e4e-11e5-9284-b827eb9e62bec146dae6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5bcca0e2-2e4e-11e5-9284-b827eb9e62be5bd1a830-2e4e-11e5-9284-b827eb9e62be5bd1a830-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e44956f0-2e4d-11e5-9284-b827eb9e62bee44e6744-2e4d-11e5-9284-b827eb9e62bee44e6744-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"25034d7c-2e4e-11e5-9284-b827eb9e62be2508629e-2e4e-11e5-9284-b827eb9e62be2508629e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ab9476d8-2e4c-11e5-9284-b827eb9e62beab996b5c-2e4c-11e5-9284-b827eb9e62beab996b5c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3ad080f8-2e4d-11e5-9284-b827eb9e62be3ad584f4-2e4d-11e5-9284-b827eb9e62be3ad584f4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b300ccc2-2e4d-11e5-9284-b827eb9e62beb305c268-2e4d-11e5-9284-b827eb9e62beb305c268-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"94876058-2e4d-11e5-9284-b827eb9e62be948c644a-2e4d-11e5-9284-b827eb9e62be948c644a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"10af8494-2e4e-11e5-9284-b827eb9e62be10b47cd8-2e4e-11e5-9284-b827eb9e62be10b47cd8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9466e746-2e4e-11e5-9284-b827eb9e62be946be02a-2e4e-11e5-9284-b827eb9e62be946be02a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0f700496-2e4e-11e5-9284-b827eb9e62be0f75b562-2e4e-11e5-9284-b827eb9e62be0f75b562-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4cecebfe-2e4e-11e5-9284-b827eb9e62be4cf1f9b4-2e4e-11e5-9284-b827eb9e62be4cf1f9b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5658165a-2e4e-11e5-9284-b827eb9e62be565d24a6-2e4e-11e5-9284-b827eb9e62be565d24a6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dd49387e-2e4e-11e5-9284-b827eb9e62bedd4e2dca-2e4e-11e5-9284-b827eb9e62bedd4e2dca-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"78a9d798-2e4e-11e5-9284-b827eb9e62be78aef548-2e4e-11e5-9284-b827eb9e62be78aef548-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dadd4b40-2e4c-11e5-9284-b827eb9e62bedae245a0-2e4c-11e5-9284-b827eb9e62bedae245a0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ae318b96-2e4d-11e5-9284-b827eb9e62beae368100-2e4d-11e5-9284-b827eb9e62beae368100-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"644bb62c-2e4e-11e5-9284-b827eb9e62be6450c2e8-2e4e-11e5-9284-b827eb9e62be6450c2e8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"13391fc8-2e4d-11e5-9284-b827eb9e62be133e40b6-2e4d-11e5-9284-b827eb9e62be133e40b6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"04217e5e-2e4d-11e5-9284-b827eb9e62be04268d4a-2e4d-11e5-9284-b827eb9e62be04268d4a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"08e4efde-2e4d-11e5-9284-b827eb9e62be08e9ff38-2e4d-11e5-9284-b827eb9e62be08e9ff38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2c2e1e10-2e4e-11e5-9284-b827eb9e62be2c33336e-2e4e-11e5-9284-b827eb9e62be2c33336e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ee77bed6-2e4e-11e5-9284-b827eb9e62beee7cb3f0-2e4e-11e5-9284-b827eb9e62beee7cb3f0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2274098e-2e4e-11e5-9284-b827eb9e62be22791244-2e4e-11e5-9284-b827eb9e62be22791244-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3595d8ae-2e4d-11e5-9284-b827eb9e62be359ae326-2e4d-11e5-9284-b827eb9e62be359ae326-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"32b4ccec-2e4f-11e5-9284-b827eb9e62be32b9c3be-2e4f-11e5-9284-b827eb9e62be32b9c3be-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4315ef40-2e4e-11e5-9284-b827eb9e62be431af698-2e4e-11e5-9284-b827eb9e62be431af698-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fb4fccda-2e4d-11e5-9284-b827eb9e62befb54c2c6-2e4d-11e5-9284-b827eb9e62befb54c2c6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c167b578-2e4d-11e5-9284-b827eb9e62bec16cbaaa-2e4d-11e5-9284-b827eb9e62bec16cbaaa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b40e5e40-2e4d-11e5-9284-b827eb9e62beb4135940-2e4d-11e5-9284-b827eb9e62beb4135940-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"35f17f42-2e4d-11e5-9284-b827eb9e62be35f68bb8-2e4d-11e5-9284-b827eb9e62be35f68bb8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"37a6504a-2e4f-11e5-9284-b827eb9e62be37ab4834-2e4f-11e5-9284-b827eb9e62be37ab4834-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d397508c-2e4d-11e5-9284-b827eb9e62bed39c53d4-2e4d-11e5-9284-b827eb9e62bed39c53d4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"766d0cb2-2e4d-11e5-9284-b827eb9e62be7672035c-2e4d-11e5-9284-b827eb9e62be7672035c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c4b53f9c-2e4e-11e5-9284-b827eb9e62bec4ba3524-2e4e-11e5-9284-b827eb9e62bec4ba3524-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"273d05a6-2e4e-11e5-9284-b827eb9e62be2742103c-2e4e-11e5-9284-b827eb9e62be2742103c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0e7e9382-2e4d-11e5-9284-b827eb9e62be0e838a9a-2e4d-11e5-9284-b827eb9e62be0e838a9a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cce705f6-2e4e-11e5-9284-b827eb9e62beccec0128-2e4e-11e5-9284-b827eb9e62beccec0128-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"618ef2ba-2e4d-11e5-9284-b827eb9e62be6193fe40-2e4d-11e5-9284-b827eb9e62be6193fe40-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1af67486-2e4d-11e5-9284-b827eb9e62be1afb834a-2e4d-11e5-9284-b827eb9e62be1afb834a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"92fdbf42-2e4e-11e5-9284-b827eb9e62be9302d82e-2e4e-11e5-9284-b827eb9e62be9302d82e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"20eb9f54-2e4f-11e5-9284-b827eb9e62be20f0f936-2e4f-11e5-9284-b827eb9e62be20f0f936-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d3e234ea-2e4c-11e5-9284-b827eb9e62bed3e7b05a-2e4c-11e5-9284-b827eb9e62bed3e7b05a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cb6a3104-2e4d-11e5-9284-b827eb9e62becb6f26dc-2e4d-11e5-9284-b827eb9e62becb6f26dc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"35a643a4-2e4f-11e5-9284-b827eb9e62be35ab4516-2e4f-11e5-9284-b827eb9e62be35ab4516-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f12f8da8-2e4d-11e5-9284-b827eb9e62bef1349d7a-2e4d-11e5-9284-b827eb9e62bef1349d7a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"022b0f3c-2e4f-11e5-9284-b827eb9e62be023017d4-2e4f-11e5-9284-b827eb9e62be023017d4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"257325ac-2e4e-11e5-9284-b827eb9e62be257836a0-2e4e-11e5-9284-b827eb9e62be257836a0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"be4c15ce-2e4c-11e5-9284-b827eb9e62bebe510fde-2e4c-11e5-9284-b827eb9e62bebe510fde-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ce5e2618-2e4d-11e5-9284-b827eb9e62bece631f42-2e4d-11e5-9284-b827eb9e62bece631f42-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"69b1976c-2e4e-11e5-9284-b827eb9e62be69b69654-2e4e-11e5-9284-b827eb9e62be69b69654-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dd1fcf6c-2e4d-11e5-9284-b827eb9e62bedd24de26-2e4d-11e5-9284-b827eb9e62bedd24de26-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ce728d00-2e4e-11e5-9284-b827eb9e62bece779dcc-2e4e-11e5-9284-b827eb9e62bece779dcc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"534590e6-2e4e-11e5-9284-b827eb9e62be534acf98-2e4e-11e5-9284-b827eb9e62be534acf98-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f8c137c0-2e4c-11e5-9284-b827eb9e62bef8c62a78-2e4c-11e5-9284-b827eb9e62bef8c62a78-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7461a202-2e4d-11e5-9284-b827eb9e62be74669e56-2e4d-11e5-9284-b827eb9e62be74669e56-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ff6ee08e-2e4e-11e5-9284-b827eb9e62beff73d9fe-2e4e-11e5-9284-b827eb9e62beff73d9fe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9916db98-2e4e-11e5-9284-b827eb9e62be991c0b22-2e4e-11e5-9284-b827eb9e62be991c0b22-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d56c79cc-2e4e-11e5-9284-b827eb9e62bed571c418-2e4e-11e5-9284-b827eb9e62bed571c418-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"85fb8b80-2e4e-11e5-9284-b827eb9e62be860094d6-2e4e-11e5-9284-b827eb9e62be860094d6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"13b0c1ae-2e4d-11e5-9284-b827eb9e62be13b5eecc-2e4d-11e5-9284-b827eb9e62be13b5eecc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b3665bb8-2e4e-11e5-9284-b827eb9e62beb36b51c2-2e4e-11e5-9284-b827eb9e62beb36b51c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a21f1732-2e4e-11e5-9284-b827eb9e62bea2244f90-2e4e-11e5-9284-b827eb9e62bea2244f90-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ac4412ea-2e4d-11e5-9284-b827eb9e62beac490cfa-2e4d-11e5-9284-b827eb9e62beac490cfa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2ff9490c-2e4e-11e5-9284-b827eb9e62be2ffe484e-2e4e-11e5-9284-b827eb9e62be2ffe484e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7a54fbe0-2e4e-11e5-9284-b827eb9e62be7a5a08e2-2e4e-11e5-9284-b827eb9e62be7a5a08e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a44ab59e-2e4d-11e5-9284-b827eb9e62bea44fb0e4-2e4d-11e5-9284-b827eb9e62bea44fb0e4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"aeb7df16-2e4d-11e5-9284-b827eb9e62beaebcd6e2-2e4d-11e5-9284-b827eb9e62beaebcd6e2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c936f670-2e4c-11e5-9284-b827eb9e62bec93c4bb6-2e4c-11e5-9284-b827eb9e62bec93c4bb6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e381cb8a-2e4d-11e5-9284-b827eb9e62bee386d4fe-2e4d-11e5-9284-b827eb9e62bee386d4fe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d5a8af6e-2e4e-11e5-9284-b827eb9e62bed5adb2b6-2e4e-11e5-9284-b827eb9e62bed5adb2b6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ed92b512-2e4d-11e5-9284-b827eb9e62beed97aa86-2e4d-11e5-9284-b827eb9e62beed97aa86-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ae3abf78-2e4c-11e5-9284-b827eb9e62beae3fb60e-2e4c-11e5-9284-b827eb9e62beae3fb60e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"24a5f37e-2e4f-11e5-9284-b827eb9e62be24aaf40a-2e4f-11e5-9284-b827eb9e62be24aaf40a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7b14633c-2e4d-11e5-9284-b827eb9e62be7b195a18-2e4d-11e5-9284-b827eb9e62be7b195a18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"54e8b8b0-2e4e-11e5-9284-b827eb9e62be54ede66e-2e4e-11e5-9284-b827eb9e62be54ede66e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"27a7c102-2e4e-11e5-9284-b827eb9e62be27acfbfe-2e4e-11e5-9284-b827eb9e62be27acfbfe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5a22e108-2e4d-11e5-9284-b827eb9e62be5a27efea-2e4d-11e5-9284-b827eb9e62be5a27efea-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c1aeb202-2e4d-11e5-9284-b827eb9e62bec1b3bea0-2e4d-11e5-9284-b827eb9e62bec1b3bea0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dce31ffa-2e4c-11e5-9284-b827eb9e62bedce81320-2e4c-11e5-9284-b827eb9e62bedce81320-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f5c4c99a-2e4e-11e5-9284-b827eb9e62bef5c9ccba-2e4e-11e5-9284-b827eb9e62bef5c9ccba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2b5964c8-2e4d-11e5-9284-b827eb9e62be2b5e56ae-2e4d-11e5-9284-b827eb9e62be2b5e56ae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dbd381d6-2e4c-11e5-9284-b827eb9e62bedbd87506-2e4c-11e5-9284-b827eb9e62bedbd87506-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9a3285f0-2e4d-11e5-9284-b827eb9e62be9a3776fa-2e4d-11e5-9284-b827eb9e62be9a3776fa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1d62c656-2e4e-11e5-9284-b827eb9e62be1d6ebdd0-2e4e-11e5-9284-b827eb9e62be1d6ebdd0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e1c4a812-2e4d-11e5-9284-b827eb9e62bee1c9dda0-2e4d-11e5-9284-b827eb9e62bee1c9dda0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b26e37a4-2e4d-11e5-9284-b827eb9e62beb27330ba-2e4d-11e5-9284-b827eb9e62beb27330ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b68160ba-2e4c-11e5-9284-b827eb9e62beb6869440-2e4c-11e5-9284-b827eb9e62beb6869440-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fcc3b210-2e4e-11e5-9284-b827eb9e62befcc8ffc2-2e4e-11e5-9284-b827eb9e62befcc8ffc2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7ab94772-2e4d-11e5-9284-b827eb9e62be7abe387c-2e4d-11e5-9284-b827eb9e62be7abe387c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n#include \n#include \n#include \n\n#include \n#include \"math.h\"\n\n\/\/velocity of the robot\ndouble linear_x;\ndouble angular_z;\n\n\/\/pose of the robot\ndouble px;\ndouble py;\ndouble theta;\n\nvoid StageOdom_callback(nav_msgs::Odometry msg)\n{\n\t\/\/This is the call back function to process odometry messages coming from Stage. \t\t\n\t\n\tpx = 5 + msg.pose.pose.position.x;\n\tpy =10 + msg.pose.pose.position.y;\n\t\/\/printf(\"%f\",px);\n\t\n\t\/\/ If the current position is the same the previous position, then the robot is stuck and needs to move around\n\tif ((px == prevpx) && (py == prevpy)) {\n\t\t\/\/msg.pose.pose.position.x = 5;\n\t\t\/\/ROS_INFO(\"Prevpx: %f\",prevpx);\n\n\t\t\/\/ Note the negative linear_x\t\t\n\t\tlinear_x=-0.2;\n\t\tangular_z=1;\n\n\t\t\/\/theta=10;\n\t\t\/\/px = 5;\n\t\t\/\/py= 5;\n\t\t\/\/printf(\"Robot stuck\");\n\t} else {\n\t\t\/\/ One the robot becomes unstuck, then it moves around again normally\n\t\tlinear_x = 0.2;\n\t\tangular_z = 0.2;\n\t}\n\tROS_INFO(\"Current x position is: %f\", px);\n\tROS_INFO(\"Current y position is: %f\", py);\n\tprevpx = px;\n\tprevpy = py;\n}\n\n\nvoid StageLaser_callback(sensor_msgs::LaserScan msg)\n{\n\t\/\/This is the callback function to process laser scan messages\n\t\/\/you can access the range data from msg.ranges[i]. i = sample number\n\t\n}\n\nint main(int argc, char **argv)\n{\n\n \/\/initialize robot parameters\n\t\/\/Initial pose. This is same as the pose that you used in the world file to set\tthe robot pose.\n\ttheta = M_PI\/2.0;\n\tpx = 5;\n\tpy = 10;\n\tprevpx=0;\n\tprevpy=0;\n\t\n\t\/\/Initial velocity\n\tlinear_x = 0.2;\n\tangular_z = 0.2;\n\t\n\/\/You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node\nros::init(argc, argv, \"RobotNode1\");\n\n\/\/NodeHandle is the main access point to communicate with ros.\nros::NodeHandle n;\n\n\/\/advertise() function will tell ROS that you want to publish on a given topic_\n\/\/to stage\nros::Publisher RobotNode_stage_pub = n.advertise(\"robot_1\/cmd_vel\",1000); \n\n\/\/subscribe to listen to messages coming from stage\nros::Subscriber StageOdo_sub = n.subscribe(\"robot_1\/odom\",1000, StageOdom_callback);\nros::Subscriber StageLaser_sub = n.subscribe(\"robot_1\/base_scan\",1000,StageLaser_callback);\n\nros::Rate loop_rate(10);\n\n\/\/a count of howmany messages we have sent\nint count = 0;\n\n\/\/\/\/messages\n\/\/velocity of this RobotNode\ngeometry_msgs::Twist RobotNode_cmdvel;\n\nwhile (ros::ok())\n{\n\t\/\/messages to stage\n\tRobotNode_cmdvel.linear.x = linear_x;\n\tRobotNode_cmdvel.angular.z = angular_z;\n \n\t\/\/publish the message\n\tRobotNode_stage_pub.publish(RobotNode_cmdvel);\n\t\n\tros::spinOnce();\n\n\tloop_rate.sleep();\n\t++count;\n}\n\nreturn 0;\n\n}\n\nadded initialisation of prevpx & prevpy#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n#include \n#include \n#include \n\n#include \n#include \"math.h\"\n\n\/\/velocity of the robot\ndouble linear_x;\ndouble angular_z;\n\n\/\/pose of the robot\ndouble px;\ndouble py;\ndouble prevpx;\ndouble prevpy;\ndouble theta;\n\nvoid StageOdom_callback(nav_msgs::Odometry msg)\n{\n\t\/\/This is the call back function to process odometry messages coming from Stage. \t\t\n\t\n\tpx = 5 + msg.pose.pose.position.x;\n\tpy =10 + msg.pose.pose.position.y;\n\t\/\/printf(\"%f\",px);\n\t\n\t\/\/ If the current position is the same the previous position, then the robot is stuck and needs to move around\n\tif ((px == prevpx) && (py == prevpy)) {\n\t\t\/\/msg.pose.pose.position.x = 5;\n\t\t\/\/ROS_INFO(\"Prevpx: %f\",prevpx);\n\n\t\t\/\/ Note the negative linear_x\t\t\n\t\tlinear_x=-0.2;\n\t\tangular_z=1;\n\n\t\t\/\/theta=10;\n\t\t\/\/px = 5;\n\t\t\/\/py= 5;\n\t\t\/\/printf(\"Robot stuck\");\n\t} else {\n\t\t\/\/ One the robot becomes unstuck, then it moves around again normally\n\t\tlinear_x = 0.2;\n\t\tangular_z = 0.2;\n\t}\n\tROS_INFO(\"Current x position is: %f\", px);\n\tROS_INFO(\"Current y position is: %f\", py);\n\tprevpx = px;\n\tprevpy = py;\n}\n\n\nvoid StageLaser_callback(sensor_msgs::LaserScan msg)\n{\n\t\/\/This is the callback function to process laser scan messages\n\t\/\/you can access the range data from msg.ranges[i]. i = sample number\n\t\n}\n\nint main(int argc, char **argv)\n{\n\n \/\/initialize robot parameters\n\t\/\/Initial pose. This is same as the pose that you used in the world file to set\tthe robot pose.\n\ttheta = M_PI\/2.0;\n\tpx = 5;\n\tpy = 10;\n\tprevpx=0;\n\tprevpy=0;\n\t\n\t\/\/Initial velocity\n\tlinear_x = 0.2;\n\tangular_z = 0.2;\n\t\n\/\/You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node\nros::init(argc, argv, \"RobotNode1\");\n\n\/\/NodeHandle is the main access point to communicate with ros.\nros::NodeHandle n;\n\n\/\/advertise() function will tell ROS that you want to publish on a given topic_\n\/\/to stage\nros::Publisher RobotNode_stage_pub = n.advertise(\"robot_1\/cmd_vel\",1000); \n\n\/\/subscribe to listen to messages coming from stage\nros::Subscriber StageOdo_sub = n.subscribe(\"robot_1\/odom\",1000, StageOdom_callback);\nros::Subscriber StageLaser_sub = n.subscribe(\"robot_1\/base_scan\",1000,StageLaser_callback);\n\nros::Rate loop_rate(10);\n\n\/\/a count of howmany messages we have sent\nint count = 0;\n\n\/\/\/\/messages\n\/\/velocity of this RobotNode\ngeometry_msgs::Twist RobotNode_cmdvel;\n\nwhile (ros::ok())\n{\n\t\/\/messages to stage\n\tRobotNode_cmdvel.linear.x = linear_x;\n\tRobotNode_cmdvel.angular.z = angular_z;\n \n\t\/\/publish the message\n\tRobotNode_stage_pub.publish(RobotNode_cmdvel);\n\t\n\tros::spinOnce();\n\n\tloop_rate.sleep();\n\t++count;\n}\n\nreturn 0;\n\n}\n\n<|endoftext|>"} {"text":"8ff9eff6-2e4d-11e5-9284-b827eb9e62be8ffef88e-2e4d-11e5-9284-b827eb9e62be8ffef88e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"de2bf11a-2e4d-11e5-9284-b827eb9e62bede31081c-2e4d-11e5-9284-b827eb9e62bede31081c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9d6f9d7e-2e4e-11e5-9284-b827eb9e62be9d749766-2e4e-11e5-9284-b827eb9e62be9d749766-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"global.h\"\n#include \"snippet.h\"\n#include \"expr.h\"\n\nuint32_t Expr::var_index_ = 0;\nExpr::VariableMap Expr::variables_;\nExpr::BreakListStack Expr::end_;\nExpr::ContinueListStack Expr::start_;\nExpr::UintListStack Expr::scope_;\n\nExpr::Expr(void)\n : left_(ExprPtr(nullptr))\n , right_(ExprPtr(nullptr)) {\n}\n\nExpr::~Expr(void) {\n}\n\nvoid Expr::PushResolve(void) {\n end_.push(std::list());\n start_.push(std::list());\n scope_.push(std::list());\n}\n\nvoid Expr::Resolve(FilePtr& out, uint32_t start_addr, uint32_t end_addr) {\n for (auto c : start_.top())\n c->Resolve(out, start_addr);\n start_.pop();\n\n for (auto b : end_.top())\n b->Resolve(out, end_addr);\n end_.pop();\n\n uint8_t cmd = static_cast(OpCode::OPCODE_DEL);\n for (auto i : scope_.top()) {\n }\n scope_.pop();\n}\n\nOpCode Expr::GetType(const std::string& token) {\n OpCode code = OpCode::OPCODE_INVAL;\n\n if (token == \"true\" || token == \"false\")\n return OpCode::OPCODE_BOOL;\n else if (token.empty())\n return OpCode::OPCODE_STRING;\n\n for (auto c : token) {\n if (!isdigit(c) && '.' != c) {\n code = OpCode::OPCODE_STRING;\n break;\n }\n else if (code != OpCode::OPCODE_REAL) {\n code = OpCode::OPCODE_INT;\n }\n\n if ('.' == c)\n code = OpCode::OPCODE_REAL;\n }\n\n return code;\n}\n\nvoid Expr::Reset(void) {\n var_index_ = 0;\n variables_.clear();\n\n while (!end_.empty())\n end_.pop();\n\n while (!start_.empty())\n start_.pop();\n\n while (!scope_.empty())\n scope_.pop();\n}\n\nvoid Expr::EvalChildren(FilePtr& out) {\n if (left_)\n left_->Execute(out);\n\n if (right_)\n right_->Execute(out);\n}\nimplementation of BlockExpr\/\/ Copyright (c) 2014 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"global.h\"\n#include \"snippet.h\"\n#include \"expr.h\"\n\nuint32_t Expr::var_index_ = 0;\nExpr::VariableMap Expr::variables_;\nExpr::BreakListStack Expr::end_;\nExpr::ContinueListStack Expr::start_;\nExpr::UintListStack Expr::scope_;\n\nExpr::Expr(void)\n : left_(ExprPtr(nullptr))\n , right_(ExprPtr(nullptr)) {\n}\n\nExpr::~Expr(void) {\n}\n\nvoid Expr::PushResolve(void) {\n end_.push(std::list());\n start_.push(std::list());\n scope_.push(std::list());\n}\n\nvoid Expr::Resolve(FilePtr& out, uint32_t start_addr, uint32_t end_addr) {\n for (auto c : start_.top())\n c->Resolve(out, start_addr);\n start_.pop();\n\n for (auto b : end_.top())\n b->Resolve(out, end_addr);\n end_.pop();\n\n uint8_t cmd = static_cast(OpCode::OPCODE_DEL);\n for (auto i : scope_.top()) {\n }\n scope_.pop();\n}\n\nOpCode Expr::GetType(const std::string& token) {\n OpCode code = OpCode::OPCODE_INVAL;\n\n if (token == \"true\" || token == \"false\")\n return OpCode::OPCODE_BOOL;\n else if (token.empty())\n return OpCode::OPCODE_STRING;\n\n for (auto c : token) {\n if (!isdigit(c) && '.' != c) {\n code = OpCode::OPCODE_STRING;\n break;\n }\n else if (code != OpCode::OPCODE_REAL) {\n code = OpCode::OPCODE_INT;\n }\n\n if ('.' == c)\n code = OpCode::OPCODE_REAL;\n }\n\n return code;\n}\n\nvoid Expr::Reset(void) {\n var_index_ = 0;\n variables_.clear();\n\n while (!end_.empty())\n end_.pop();\n\n while (!start_.empty())\n start_.pop();\n\n while (!scope_.empty())\n scope_.pop();\n}\n\nvoid Expr::EvalChildren(FilePtr& out) {\n if (left_)\n left_->Execute(out);\n\n if (right_)\n right_->Execute(out);\n}\n\nBlockExpr::~BlockExpr(void) {\n blocks_.clear();\n}\n\nvoid BlockExpr::Execute(FilePtr& out) {\n for (auto expr : blocks_)\n expr->Execute(out);\n}\n\nvoid ValueExpr::Execute(FilePtr& out) {\n EvalChildren(out);\n\n OpCode code = GetType(value_);\n switch (code) {\n case OpCode::OPCODE_BOOL:\n {\n bool v = false;\n if (value_ == \"true\")\n v = true;\n } break;\n case OpCode::OPCODE_INT:\n {\n int v = atoi(value_.c_str());\n } break;\n case OpCode::OPCODE_REAL:\n {\n float v = static_cast(atof(value_.c_str()));\n } break;\n case OpCode::OPCODE_STRING:\n break;\n default:\n break;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"configuration.hh\"\n#include \"contents.hh\"\n#include \"hooks.hh\"\n#include \"file_contents.hh\"\n#include \"visual.hh\"\n#include \"show_message.hh\"\n\nstatic contents cont;\n\nvoid init(std::vector vec) {\n cont = contents(vec);\n print_contents(cont);\n}\n\ncontents& get_contents() { return cont; }\n\nvoid print_contents(contents& contents) {\n if(contents.y - contents.y_offset >= contents.max_y - 1) {\n contents.y_offset = contents.y - contents.y_offset + 1;\n show_message(\"hi\");\n }\n if(contents.y < contents.y_offset) {\n contents.y_offset = contents.y;\n show_message(\"bye\");\n }\n\n clear();\n int y = 0;\n\n int fin_y,fin_x; \/\/ if none set then random!\n\n for(unsigned int i = contents.y_offset;\n i < contents.cont.size()\n && i < contents.max_y - 1 + contents.y_offset; i++) {\n\n unsigned int x = 0;\n const std::string& line = contents.cont[i];\n int til = 0;\n\n if(line.begin() == line.end()) {\n if(contents.y == i && contents.x == 0) {\n fin_y = y;\n fin_x = x;\n }\n } else {\n for(std::string::const_iterator it = line.begin(); it < line.end(); it++) {\n if(*it == '\\t') {\n x += TAB_SIZE - til - 1;\n if(x >= contents.max_x) {\n x = -1;\n y++;\n }\n move(y,x);\n til = 0;\n } else {\n addch(*it);\n til++;\n til %= TAB_SIZE;\n }\n if(x == contents.max_x) {\n til = 0;\n move(++y, x = 0);\n addch(*it);\n }\n if(contents.y == i && contents.x == it - line.begin()) {\n fin_y = y;\n fin_x = x;\n }\n x++;\n move(y,x);\n }\n if(contents.y == i && contents.x >= line.size()) {\n fin_y = y;\n fin_x = x + (contents.is_inserting ? 0 : -1);\n }\n }\n move(++y,0);\n }\n \/\/contents.y, to_visual(contents.cont[contents.y],contents.x)\n move(fin_y,fin_x);\n proc_hook(Hook::REFRESH);\n}\nUse auto for iterator type deduction#include \n#include \n#include \n\n#include \"configuration.hh\"\n#include \"contents.hh\"\n#include \"hooks.hh\"\n#include \"file_contents.hh\"\n#include \"visual.hh\"\n#include \"show_message.hh\"\n\nstatic contents cont;\n\nvoid init(std::vector vec) {\n cont = contents(vec);\n print_contents(cont);\n}\n\ncontents& get_contents() { return cont; }\n\nvoid print_contents(contents& contents) {\n if(contents.y - contents.y_offset >= contents.max_y - 1) {\n contents.y_offset = contents.y - contents.y_offset + 1;\n show_message(\"hi\");\n }\n if(contents.y < contents.y_offset) {\n contents.y_offset = contents.y;\n show_message(\"bye\");\n }\n\n clear();\n int y = 0;\n\n int fin_y,fin_x; \/\/ if none set then random!\n\n for(unsigned int i = contents.y_offset;\n i < contents.cont.size()\n && i < contents.max_y - 1 + contents.y_offset; i++) {\n\n unsigned int x = 0;\n const std::string& line = contents.cont[i];\n int til = 0;\n\n if(line.begin() == line.end()) {\n if(contents.y == i && contents.x == 0) {\n fin_y = y;\n fin_x = x;\n }\n } else {\n for(auto it = line.begin(); it < line.end(); it++) {\n if(*it == '\\t') {\n x += TAB_SIZE - til - 1;\n if(x >= contents.max_x) {\n x = -1;\n y++;\n }\n move(y,x);\n til = 0;\n } else {\n addch(*it);\n til++;\n til %= TAB_SIZE;\n }\n if(x == contents.max_x) {\n til = 0;\n move(++y, x = 0);\n addch(*it);\n }\n if(contents.y == i && contents.x == it - line.begin()) {\n fin_y = y;\n fin_x = x;\n }\n x++;\n move(y,x);\n }\n if(contents.y == i && contents.x >= line.size()) {\n fin_y = y;\n fin_x = x + (contents.is_inserting ? 0 : -1);\n }\n }\n move(++y,0);\n }\n \/\/contents.y, to_visual(contents.cont[contents.y],contents.x)\n move(fin_y,fin_x);\n proc_hook(Hook::REFRESH);\n}\n<|endoftext|>"} {"text":"2569ce90-2e4d-11e5-9284-b827eb9e62be256ec6a2-2e4d-11e5-9284-b827eb9e62be256ec6a2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2caf135c-2e4f-11e5-9284-b827eb9e62be2cb4632a-2e4f-11e5-9284-b827eb9e62be2cb4632a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"libDroneVideo\/FrameGrabber.hpp\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace ghost\n{\nnamespace libDroneVideo\n{\n\nFrameGrabber::FrameGrabber() : mDroneVerticalFrame({ 0 })\n{\n}\n\nint FrameGrabber::getVerticalFrameWidth()\n{\n return libDroneVideoSharing::CameraDefinition::mVerticalImgWidth;\n}\n\nint FrameGrabber::getVerticalFrameHeight()\n{\n return libDroneVideoSharing::CameraDefinition::mVerticalImgHeight;\n}\n\nFrameGrabber::DroneVerticalFrame& FrameGrabber::getNextVerticalFrame()\n{\n\n int query = 0;\n int failThreshold = 5;\n\n do {\n \/\/ Check if the frame is ready\n if (access(CAMV_READY, F_OK) != -1) {\n int fd = open(CAMV_BUFFER, O_RDONLY);\n\n \/\/ Get the frame\n read(fd,\n &mDroneVerticalFrame[0],\n libDroneVideoSharing::CameraDefinition::mVerticalImgSize);\n close(fd);\n remove(CAMV_READY);\n\n break;\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(25));\n } while (++query != failThreshold);\n\n if (query == failThreshold) {\n BOOST_LOG_TRIVIAL(warning) << \"Vertical camera buffer unaivalable\";\n }\n\n return std::ref(mDroneVerticalFrame);\n}\n\n} \/* libDroneVideo namespace *\/\n} \/* ghost namespace *\/\n[libDroneVideo] Change FrameGrabber timeout timing\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"libDroneVideo\/FrameGrabber.hpp\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace ghost\n{\nnamespace libDroneVideo\n{\n\nFrameGrabber::FrameGrabber() : mDroneVerticalFrame({ 0 })\n{\n}\n\nint FrameGrabber::getVerticalFrameWidth()\n{\n return libDroneVideoSharing::CameraDefinition::mVerticalImgWidth;\n}\n\nint FrameGrabber::getVerticalFrameHeight()\n{\n return libDroneVideoSharing::CameraDefinition::mVerticalImgHeight;\n}\n\nFrameGrabber::DroneVerticalFrame& FrameGrabber::getNextVerticalFrame()\n{\n\n int query = 0;\n int failThreshold = 20;\n\n do {\n \/\/ Check if the frame is ready\n if (access(CAMV_READY, F_OK) != -1) {\n int fd = open(CAMV_BUFFER, O_RDONLY);\n\n \/\/ Get the frame\n read(fd,\n &mDroneVerticalFrame[0],\n libDroneVideoSharing::CameraDefinition::mVerticalImgSize);\n close(fd);\n remove(CAMV_READY);\n\n break;\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(5));\n } while (++query != failThreshold);\n\n if (query == failThreshold) {\n BOOST_LOG_TRIVIAL(warning) << \"Vertical camera buffer unaivalable\";\n }\n\n return std::ref(mDroneVerticalFrame);\n}\n\n} \/* libDroneVideo namespace *\/\n} \/* ghost namespace *\/\n<|endoftext|>"} {"text":"\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n\nnamespace pangolin\n{\n\nVideoSplitter::VideoSplitter(VideoInterface *videoin, const std::vector& streams)\n : videoin(videoin), streams(streams)\n{\n if(videoin->Streams().size() != 1)\n throw VideoException(\"VideoSplitter input must have exactly one stream\");\n}\n\nVideoSplitter::~VideoSplitter()\n{\n delete videoin;\n}\n\nsize_t VideoSplitter::SizeBytes() const\n{\n return videoin->SizeBytes();\n}\n\nconst std::vector& VideoSplitter::Streams() const\n{\n return streams;\n}\n\nvoid VideoSplitter::Start()\n{\n videoin->Start();\n}\n\nvoid VideoSplitter::Stop()\n{\n videoin->Stop();\n}\n\nbool VideoSplitter::GrabNext( unsigned char* image, bool wait )\n{\n return videoin->GrabNext(image, wait);\n}\n\nbool VideoSplitter::GrabNewest( unsigned char* image, bool wait )\n{\n return videoin->GrabNewest(image, wait);\n}\n\n\n\n}\nAdd memory bounds checks for stream splits.\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n\nnamespace pangolin\n{\n\nVideoSplitter::VideoSplitter(VideoInterface *videoin, const std::vector& streams)\n : videoin(videoin), streams(streams)\n{\n if(videoin->Streams().size() != 1)\n throw VideoException(\"VideoSplitter input must have exactly one stream\");\n\n \/\/ Make sure no stream over-runs input stream\n for(unsigned int i=0; i < streams.size(); ++i) {\n if(videoin->Streams()[0].SizeBytes() < (size_t)streams[i].Offset() + streams[i].SizeBytes() )\n throw VideoException(\"VideoSplitter: stream extends past end of input\");\n }\n}\n\nVideoSplitter::~VideoSplitter()\n{\n delete videoin;\n}\n\nsize_t VideoSplitter::SizeBytes() const\n{\n return videoin->SizeBytes();\n}\n\nconst std::vector& VideoSplitter::Streams() const\n{\n return streams;\n}\n\nvoid VideoSplitter::Start()\n{\n videoin->Start();\n}\n\nvoid VideoSplitter::Stop()\n{\n videoin->Stop();\n}\n\nbool VideoSplitter::GrabNext( unsigned char* image, bool wait )\n{\n return videoin->GrabNext(image, wait);\n}\n\nbool VideoSplitter::GrabNewest( unsigned char* image, bool wait )\n{\n return videoin->GrabNewest(image, wait);\n}\n\n\n\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2011-2012 - Tőkés Attila\n Copyright (C) 2015 Daniel Nicoletti \n\nx\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n See the LICENSE file for more details.\n*\/\n\n#include \"mimemessage_p.h\"\n\n#include \n#include \"quotedprintable.h\"\n#include \n\n#include \n#include \n\nQ_LOGGING_CATEGORY(SIMPLEMAIL_MIMEMSG, \"simplemail.mimemessage\")\n\nusing namespace SimpleMail;\n\nMimeMessage::MimeMessage(bool createAutoMimeContent) : d(new MimeMessagePrivate)\n{\n if (createAutoMimeContent) {\n d->content = new MimeMultiPart();\n }\n\n d->autoMimeContentCreated = createAutoMimeContent;\n}\n\nMimeMessage::MimeMessage(const MimeMessage &other) : d(other.d)\n{\n\n}\n\nMimeMessage::~MimeMessage()\n{\n\n}\n\nMimeMessage &MimeMessage::operator=(const MimeMessage &other)\n{\n d = other.d;\n return *this;\n}\n\nMimePart& MimeMessage::getContent()\n{\n return *d->content;\n}\n\nvoid MimeMessage::setContent(MimePart *content)\n{\n if (d->autoMimeContentCreated) {\n d->autoMimeContentCreated = false;\n delete d->content;\n }\n d->content = content;\n}\n\nbool MimeMessage::write(QIODevice *device) const\n{\n \/\/ Headers\n QByteArray data;\n\n if (!d->listExtraHeaders.isEmpty()) {\n const auto listExtraHeaders = d->listExtraHeaders;\n for (const QByteArray &header : listExtraHeaders) {\n data += MimeMessagePrivate::encodeData(d->encoding, QString::fromLatin1(header), true) + QByteArrayLiteral(\"\\r\\n\");\n }\n if (device->write(data) != data.size()) {\n return false;\n }\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"From: \"), QList() << d->sender, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n if (d->replyTo.address().isEmpty() == false) {\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"Reply-To: \"), QList() << d->replyTo, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"To: \"), d->recipientsTo, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"Cc: \"), d->recipientsCc, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"Date: \") + QDateTime::currentDateTime().toString(Qt::RFC2822Date).toLatin1() + QByteArrayLiteral(\"\\r\\n\");\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"Subject: \") + MimeMessagePrivate::encodeData(d->encoding, d->subject, true);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"\\r\\nMIME-Version: 1.0\\r\\n\");\n if (device->write(data) != data.size()) {\n return false;\n }\n\n if (!d->content->write(device)) {\n return false;\n }\n\n \/\/ Send \\r\\n.\\r\\n to end the mail data\n device->write(QByteArrayLiteral(\"\\r\\n.\\r\\n\"));\n\n return true;\n}\n\nvoid MimeMessage::setSender(const EmailAddress &sender)\n{\n d->sender = sender;\n}\n\nvoid MimeMessage::setToRecipients(const QList &toList)\n{\n d->recipientsTo = toList;\n}\n\nQList MimeMessage::toRecipients() const\n{\n return d->recipientsTo;\n}\n\nvoid MimeMessage::addTo(const EmailAddress &rcpt)\n{\n d->recipientsTo.append(rcpt);\n}\n\nvoid MimeMessage::setCcRecipients(const QList &ccList)\n{\n d->recipientsCc = ccList;\n}\n\nvoid MimeMessage::addCc(const EmailAddress &rcpt)\n{\n d->recipientsCc.append(rcpt);\n}\n\nQList MimeMessage::ccRecipients() const\n{\n return d->recipientsCc;\n}\n\nvoid MimeMessage::setBccRecipients(const QList &bccList)\n{\n d->recipientsBcc = bccList;\n}\n\nQList MimeMessage::bccRecipients() const\n{\n return d->recipientsBcc;\n}\n\nvoid MimeMessage::addBcc(const EmailAddress &rcpt)\n{\n d->recipientsBcc.append(rcpt);\n}\n\nvoid MimeMessage::setSubject(const QString &subject)\n{\n d->subject = subject;\n}\n\nvoid MimeMessage::addPart(MimePart *part)\n{\n auto content = d->content;\n if (typeid(*content) == typeid(MimeMultiPart)) {\n static_cast(d->content)->addPart(part);\n }\n}\n\nvoid MimeMessage::setHeaderEncoding(MimePart::Encoding hEnc)\n{\n d->encoding = hEnc;\n}\n\nvoid MimeMessage::addHeader(const QByteArray &headerName, const QByteArray &headerValue)\n{\n d->listExtraHeaders.append(headerName + \":\" + headerValue);\n}\n\nQList MimeMessage::getHeaders() const\n{\n return d->listExtraHeaders;\n}\n\nEmailAddress MimeMessage::sender() const\n{\n return d->sender;\n}\n\nvoid MimeMessage::setReplyto(const EmailAddress &replyTo)\n{\n d->replyTo = replyTo;\n}\n\nQString MimeMessage::subject() const\n{\n return d->subject;\n}\n\nQList MimeMessage::parts() const\n{\n QList ret;\n auto content = d->content;\n if (typeid(*content) == typeid(MimeMultiPart)) {\n ret = static_cast(d->content)->parts();\n } else {\n ret.append(d->content);\n }\n\n return ret;\n}\n\nMimeMessagePrivate::~MimeMessagePrivate()\n{\n delete content;\n}\n\nQByteArray MimeMessagePrivate::encode(const QByteArray &addressKind, const QList &emails, MimePart::Encoding codec)\n{\n if (emails.isEmpty()) {\n return QByteArray();\n }\n\n QByteArray mime = addressKind;\n bool first = true;\n for (const EmailAddress &email : emails) {\n if (!first) {\n mime.append(',');\n } else {\n first = false;\n }\n\n const QString name = email.name();\n if (!name.isEmpty()) {\n mime.append(MimeMessagePrivate::encodeData(codec, name, true));\n mime.append(\" <\" + email.address().toLatin1() + '>');\n } else {\n mime.append('<' + email.address().toLatin1() + '>');\n }\n }\n mime.append(QByteArrayLiteral(\"\\r\\n\"));\n\n return mime;\n}\n\nQByteArray MimeMessagePrivate::encodeData(MimePart::Encoding codec, const QString &data, bool autoencoding)\n{\n const QString simpleData = data.simplified();\n const QByteArray simple = simpleData.toUtf8();\n if (autoencoding) {\n if (simpleData.toLatin1() == simple) {\n return simple;\n }\n\n int printable = 0;\n int encoded = 0;\n const QByteArray result = QuotedPrintable::encode(simple, true, &printable, &encoded);\n int sum = printable + encoded;\n qCDebug(SIMPLEMAIL_MIMEMSG) << data << result << printable << encoded << sum << (double(printable)\/sum) << (encoded\/sum);\n if (sum != 0 && (double(printable)\/sum) >= 0.8) {\n return \" =?utf-8?Q?\" + result + \"?=\";\n } else {\n return \" =?utf-8?B?\" + data.toUtf8().toBase64() + \"?=\";\n }\n } else {\n switch (codec) {\n case MimePart::Base64:\n return \" =?utf-8?B?\" + simple.toBase64() + \"?=\";\n case MimePart::QuotedPrintable:\n return \" =?utf-8?Q?\" + QuotedPrintable::encode(simple, true) + \"?=\";\n default:\n return ' ' + data.toLatin1();\n }\n }\n}\nsome safe checking\/*\n Copyright (c) 2011-2012 - Tőkés Attila\n Copyright (C) 2015 Daniel Nicoletti \n\nx\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n See the LICENSE file for more details.\n*\/\n\n#include \"mimemessage_p.h\"\n\n#include \n#include \"quotedprintable.h\"\n#include \n\n#include \n#include \n\nQ_LOGGING_CATEGORY(SIMPLEMAIL_MIMEMSG, \"simplemail.mimemessage\")\n\nusing namespace SimpleMail;\n\nMimeMessage::MimeMessage(bool createAutoMimeContent) : d(new MimeMessagePrivate)\n{\n if (createAutoMimeContent) {\n d->content = new MimeMultiPart();\n }\n\n d->autoMimeContentCreated = createAutoMimeContent;\n}\n\nMimeMessage::MimeMessage(const MimeMessage &other) : d(other.d)\n{\n\n}\n\nMimeMessage::~MimeMessage()\n{\n\n}\n\nMimeMessage &MimeMessage::operator=(const MimeMessage &other)\n{\n d = other.d;\n return *this;\n}\n\nMimePart& MimeMessage::getContent()\n{\n return *d->content;\n}\n\nvoid MimeMessage::setContent(MimePart *content)\n{\n if (d->autoMimeContentCreated) {\n d->autoMimeContentCreated = false;\n delete d->content;\n }\n d->content = content;\n}\n\nbool MimeMessage::write(QIODevice *device) const\n{\n \/\/ Headers\n QByteArray data;\n\n if (!d->listExtraHeaders.isEmpty()) {\n const auto listExtraHeaders = d->listExtraHeaders;\n for (const QByteArray &header : listExtraHeaders) {\n data += MimeMessagePrivate::encodeData(d->encoding, QString::fromLatin1(header), true) + QByteArrayLiteral(\"\\r\\n\");\n }\n if (device->write(data) != data.size()) {\n return false;\n }\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"From: \"), QList() << d->sender, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n if (d->replyTo.address().isEmpty() == false) {\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"Reply-To: \"), QList() << d->replyTo, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"To: \"), d->recipientsTo, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = MimeMessagePrivate::encode(QByteArrayLiteral(\"Cc: \"), d->recipientsCc, d->encoding);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"Date: \") + QDateTime::currentDateTime().toString(Qt::RFC2822Date).toLatin1() + QByteArrayLiteral(\"\\r\\n\");\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"Subject: \") + MimeMessagePrivate::encodeData(d->encoding, d->subject, true);\n if (device->write(data) != data.size()) {\n return false;\n }\n\n data = QByteArrayLiteral(\"\\r\\nMIME-Version: 1.0\\r\\n\");\n if (device->write(data) != data.size()) {\n return false;\n }\n\n if (!d->content->write(device)) {\n qCWarning(SIMPLEMAIL_MIMEMSG) << \"Failed to write MIME content\";\n return false;\n }\n\n \/\/ Send \\r\\n.\\r\\n to end the mail data\n return device->write(QByteArrayLiteral(\"\\r\\n.\\r\\n\")) == 5;\n}\n\nvoid MimeMessage::setSender(const EmailAddress &sender)\n{\n d->sender = sender;\n}\n\nvoid MimeMessage::setToRecipients(const QList &toList)\n{\n d->recipientsTo = toList;\n}\n\nQList MimeMessage::toRecipients() const\n{\n return d->recipientsTo;\n}\n\nvoid MimeMessage::addTo(const EmailAddress &rcpt)\n{\n d->recipientsTo.append(rcpt);\n}\n\nvoid MimeMessage::setCcRecipients(const QList &ccList)\n{\n d->recipientsCc = ccList;\n}\n\nvoid MimeMessage::addCc(const EmailAddress &rcpt)\n{\n d->recipientsCc.append(rcpt);\n}\n\nQList MimeMessage::ccRecipients() const\n{\n return d->recipientsCc;\n}\n\nvoid MimeMessage::setBccRecipients(const QList &bccList)\n{\n d->recipientsBcc = bccList;\n}\n\nQList MimeMessage::bccRecipients() const\n{\n return d->recipientsBcc;\n}\n\nvoid MimeMessage::addBcc(const EmailAddress &rcpt)\n{\n d->recipientsBcc.append(rcpt);\n}\n\nvoid MimeMessage::setSubject(const QString &subject)\n{\n d->subject = subject;\n}\n\nvoid MimeMessage::addPart(MimePart *part)\n{\n auto content = d->content;\n if (typeid(*content) == typeid(MimeMultiPart)) {\n static_cast(d->content)->addPart(part);\n }\n}\n\nvoid MimeMessage::setHeaderEncoding(MimePart::Encoding hEnc)\n{\n d->encoding = hEnc;\n}\n\nvoid MimeMessage::addHeader(const QByteArray &headerName, const QByteArray &headerValue)\n{\n d->listExtraHeaders.append(headerName + \":\" + headerValue);\n}\n\nQList MimeMessage::getHeaders() const\n{\n return d->listExtraHeaders;\n}\n\nEmailAddress MimeMessage::sender() const\n{\n return d->sender;\n}\n\nvoid MimeMessage::setReplyto(const EmailAddress &replyTo)\n{\n d->replyTo = replyTo;\n}\n\nQString MimeMessage::subject() const\n{\n return d->subject;\n}\n\nQList MimeMessage::parts() const\n{\n QList ret;\n auto content = d->content;\n if (typeid(*content) == typeid(MimeMultiPart)) {\n ret = static_cast(d->content)->parts();\n } else {\n ret.append(d->content);\n }\n\n return ret;\n}\n\nMimeMessagePrivate::~MimeMessagePrivate()\n{\n delete content;\n}\n\nQByteArray MimeMessagePrivate::encode(const QByteArray &addressKind, const QList &emails, MimePart::Encoding codec)\n{\n if (emails.isEmpty()) {\n return QByteArray();\n }\n\n QByteArray mime = addressKind;\n bool first = true;\n for (const EmailAddress &email : emails) {\n if (!first) {\n mime.append(',');\n } else {\n first = false;\n }\n\n const QString name = email.name();\n if (!name.isEmpty()) {\n mime.append(MimeMessagePrivate::encodeData(codec, name, true));\n mime.append(\" <\" + email.address().toLatin1() + '>');\n } else {\n mime.append('<' + email.address().toLatin1() + '>');\n }\n }\n mime.append(QByteArrayLiteral(\"\\r\\n\"));\n\n return mime;\n}\n\nQByteArray MimeMessagePrivate::encodeData(MimePart::Encoding codec, const QString &data, bool autoencoding)\n{\n const QString simpleData = data.simplified();\n const QByteArray simple = simpleData.toUtf8();\n if (autoencoding) {\n if (simpleData.toLatin1() == simple) {\n return simple;\n }\n\n int printable = 0;\n int encoded = 0;\n const QByteArray result = QuotedPrintable::encode(simple, true, &printable, &encoded);\n int sum = printable + encoded;\n qCDebug(SIMPLEMAIL_MIMEMSG) << data << result << printable << encoded << sum << (double(printable)\/sum) << (encoded\/sum);\n if (sum != 0 && (double(printable)\/sum) >= 0.8) {\n return \" =?utf-8?Q?\" + result + \"?=\";\n } else {\n return \" =?utf-8?B?\" + data.toUtf8().toBase64() + \"?=\";\n }\n } else {\n switch (codec) {\n case MimePart::Base64:\n return \" =?utf-8?B?\" + simple.toBase64() + \"?=\";\n case MimePart::QuotedPrintable:\n return \" =?utf-8?Q?\" + QuotedPrintable::encode(simple, true) + \"?=\";\n default:\n return ' ' + data.toLatin1();\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ [WriteFile Name=ServiceFeatureTableCache, Category=Features]\n\/\/ [Legal]\n\/\/ Copyright 2016 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"ServiceFeatureTableCache.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"FeatureLayer.h\"\n#include \"Basemap.h\"\n#include \"SpatialReference.h\"\n#include \"ServiceFeatureTable.h\"\n#include \"Viewpoint.h\"\n#include \"Envelope.h\"\n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nServiceFeatureTableCache::ServiceFeatureTableCache(QQuickItem* parent) :\n QQuickItem(parent),\n m_map(nullptr),\n m_mapView(nullptr),\n m_featureLayer(nullptr),\n m_featureTable(nullptr)\n{\n}\n\nServiceFeatureTableCache::~ServiceFeatureTableCache()\n{\n}\n\nvoid ServiceFeatureTableCache::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ find QML MapView component\n m_mapView = findChild(\"mapView\");\n m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);\n\n \/\/ Create a map using the light gray canvas basemap\n m_map = new Map(Basemap::lightGrayCanvas(this), this);\n m_map->setInitialViewpoint(Viewpoint(Envelope(-13075816.4047166, 4014771.46954516, -13073005.6797177, 4016869.78617381, SpatialReference(102100))));\n\n \/\/ Set map to map view\n m_mapView->setMap(m_map);\n\n \/\/ create the feature table\n ServiceFeatureTable* m_featureTable = new ServiceFeatureTable(QUrl(\"http:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/PoolPermits\/FeatureServer\/0\"), this);\n\n \/\/ create the feature layer using the feature table\n m_featureLayer = new FeatureLayer(m_featureTable, this);\n\n \/\/ add the feature layer to the map\n m_map->operationalLayers()->append(m_featureLayer);\n}\nremoved re-declaration of the member variable and use the member instead.\/\/ [WriteFile Name=ServiceFeatureTableCache, Category=Features]\n\/\/ [Legal]\n\/\/ Copyright 2016 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"ServiceFeatureTableCache.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"FeatureLayer.h\"\n#include \"Basemap.h\"\n#include \"SpatialReference.h\"\n#include \"ServiceFeatureTable.h\"\n#include \"Viewpoint.h\"\n#include \"Envelope.h\"\n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nServiceFeatureTableCache::ServiceFeatureTableCache(QQuickItem* parent) :\n QQuickItem(parent),\n m_map(nullptr),\n m_mapView(nullptr),\n m_featureLayer(nullptr),\n m_featureTable(nullptr)\n{\n}\n\nServiceFeatureTableCache::~ServiceFeatureTableCache()\n{\n}\n\nvoid ServiceFeatureTableCache::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ find QML MapView component\n m_mapView = findChild(\"mapView\");\n m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);\n\n \/\/ Create a map using the light gray canvas basemap\n m_map = new Map(Basemap::lightGrayCanvas(this), this);\n m_map->setInitialViewpoint(Viewpoint(Envelope(-13075816.4047166, 4014771.46954516, -13073005.6797177, 4016869.78617381, SpatialReference(102100))));\n\n \/\/ Set map to map view\n m_mapView->setMap(m_map);\n\n \/\/ create the feature table\n m_featureTable = new ServiceFeatureTable(QUrl(\"http:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/PoolPermits\/FeatureServer\/0\"), this);\n\n \/\/ create the feature layer using the feature table\n m_featureLayer = new FeatureLayer(m_featureTable, this);\n\n \/\/ add the feature layer to the map\n m_map->operationalLayers()->append(m_featureLayer);\n}\n<|endoftext|>"} {"text":"#include \"client.h\"\n#include \"tests\/test.h\"\n#include \"webrequester.h\"\n#include \"ping.h\"\n#include \"connectiontester.h\"\n#include \"discovery.h\"\n#include \"network\/requests\/requests.h\"\n\n#include \"qtquick2applicationviewer.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_ANDROID\n#include \"statusbarhelper.h\"\n#include \"androidimageprovider.h\"\n#include \"androidprocessmodel.h\"\n#else\n#include \n#include \"desktopstatusbarhelper.h\"\n#endif \/\/ Q_OS_ANDROID\n\nclass Time : public QObject\n{\n Q_OBJECT\n\npublic:\n Time(QObject* parent = 0) : QObject(parent) {\n }\n\n Q_INVOKABLE int restart() {\n return time.restart();\n }\n\n Q_INVOKABLE int elapsed() const {\n return time.elapsed();\n }\n\nprotected:\n QTime time;\n};\n\nint main(int argc, char* argv[])\n{\n QCoreApplication::setOrganizationDomain(\"de.hsaugsburg.informatik\");\n QCoreApplication::setOrganizationName(\"HS Augsburg\");\n QCoreApplication::setApplicationName(\"mPlaneClient\");\n\n#ifdef Q_OS_ANDROID\n QGuiApplication app(argc, argv);\n#else\n QApplication app(argc, argv);\n#endif\n\n qmlRegisterUncreatableType(\"mplane\", 1, 0, \"AbstractTest\", \"abstract class\");\n qmlRegisterUncreatableType(\"mplane\", 1, 0, \"Client\", \"This is a singleton\");\n qmlRegisterUncreatableType(\"mplane\", 1, 0, \"TestScheduler\", \"uncreatable type\");\n\n \/\/ Common objects\n qmlRegisterType(\"mplane\", 1, 0, \"TimingInformation\");\n\n \/\/ Requests\n qmlRegisterUncreatableType(\"mplane\", 1, 0, \"Request\", \"abstract class\");\n qmlRegisterType(\"mplane\", 1, 0, \"RegisterDeviceRequest\");\n qmlRegisterType(\"mplane\", 1, 0, \"TestRequest\");\n qmlRegisterType(\"mplane\", 1, 0, \"UserRegisterRequest\");\n qmlRegisterType(\"mplane\", 1, 0, \"LoginRequest\");\n qmlRegisterType(\"mplane\", 1, 0, \"GetConfigRequest\");\n\n \/\/ Responses\n qmlRegisterUncreatableType(\"mplane\", 1, 0, \"Response\", \"abstract class\");\n qmlRegisterType(\"mplane\", 1, 0, \"UserRegisterResponse\");\n qmlRegisterType(\"mplane\", 1, 0, \"LoginResponse\");\n qmlRegisterType(\"mplane\", 1, 0, \"RegisterDeviceResponse\");\n qmlRegisterType(\"mplane\", 1, 0, \"GetConfigResponse\");\n\n qmlRegisterType(\"mplane\", 1, 0, \"Settings\");\n qmlRegisterType(\"mplane\", 1, 0, \"WebRequester\");\n qmlRegisterType(\"mplane\", 1, 0, \"Ping\");\n qmlRegisterType(\"mplane\", 1, 0, \"ConnectionTester\");\n qmlRegisterType(\"mplane\", 1, 0, \"ConnectionTesterModel\");\n qmlRegisterType(\"mplane\", 1, 0, \"Discovery\");\n qmlRegisterType