text
stringlengths
8
6.88M
#include <iostream> #include <vector> constexpr int kNotFound = -1; int LinearSearch(int element, const int* v, int size) { for(int i=0; i < size; i++) { if(v[i] == element) { return i; } } return kNotFound; } int BinarySearch(int element, const int* v, int size) { int left = 0; int right = size - 1; while (left <= right) { int middle = (right + left) / 2; if (v[middle] == element) { return middle; } else if (v[middle] < element) { left = middle + 1; } else if (v[middle] > element) { right = middle - 1; } } return kNotFound; } void Print(const std::vector<int>& v) { std::cout << "[ "; for (int x : v) { std::cout << x << ' '; } std::cout << "]\n"; } int main() { std::vector<int> v{33, 44, 55, 11, 22}; Print(v); int x; std::cin >> x; int pos = LinearSearch(x, v.data(), v.size()); if (pos == kNotFound) { std::cout << "Element not found.\n"; } else { std::cout << "Element found at index " << pos << ".\n"; } return 0; }
#pragma once #include<string> #include<vector> #include<iostream> #include<fstream> #include<iomanip> #include<stack> #include<map> #include<Windows.h> #include"Interfaces.h" using std::ifstream; using std::ofstream; using std::string; using std::vector; using std::cout; using std::cin; using std::cerr; using std::endl; using std::stack; using std::map; enum class TypeAnalyzer { TypeA, // OLD(MachineA) TypeB // MPA }; enum class ReservedName { _none, _def, _in, _out, _while, _do, _if, _return, _then, _endl, _else, _AND, _OR, _NOT, _main, _int, _double, _Ind, _Con, _operator }; struct AllLexem { string val; int index; int numOfLine; int numOfID; string type; ReservedName alias; AllLexem() : val("") , index() , numOfLine() , numOfID() , type("") , alias(ReservedName::_none) {} AllLexem(const string& _val, int _index, int numLine, int numID, const string& _type, ReservedName _alias) : val(_val) , index(_index) , numOfLine(numLine) , numOfID(numID) , type(_type) , alias(_alias) {} AllLexem(const AllLexem& other) : val(other.val) , index(other.index) , numOfLine(other.numOfLine) , numOfID(other.numOfID) , type(other.type) , alias(other.alias) {} AllLexem& operator= (const AllLexem& other) { if (this != &other) // защита от неправильного самоприсваивания { val = other.val; index = other.index; numOfLine = other.numOfLine; numOfID = other.numOfID; type = other.type; alias = other.alias; } return *this; } AllLexem( AllLexem&& other) : val(std::move(other.val)) , index(other.index) , numOfLine(other.numOfLine) , numOfID(other.numOfID) , type(std::move(other.type)) , alias(other.alias) {} virtual ~AllLexem() {} friend std::ostream& operator<<(std::ostream& os, const AllLexem& dt) { os << std::setw(5) << dt.numOfLine << std::setw(22) << dt.val << std::setw(7) << dt.index << std::setw(7) << dt.numOfID << std::setw(13) << dt.type; return os; } }; struct ConVal { bool flag; // is con val? string val; //type if yes // is con val? //type if yes ConVal(string v, bool i) :val(v), flag(i) {} ConVal(const ConVal& other) :val(other.val), flag(other.flag) {} ConVal& operator= (const ConVal& other) { if (this != &other) { val = other.val; flag = other.flag; } return *this; } ConVal(ConVal&& other) :val(std::move(other.val)), flag(other.flag) {} ~ConVal() {} }; struct Exept { string mess; int line; string val; //v - value which find exept //l - line where find exept //m - message where find exept Exept(const string &v, int l, string m) : val(v) , line(l) , mess(m) {} Exept(const Exept& other) : mess(other.mess) , line(other.line) , val(other.val) {} Exept& operator= (const Exept& other) { if (this != &other) // защита от неправильного самоприсваивания { mess = other.mess; line = other.line; val = other.val; } return *this; } Exept(Exept&& other) :val(std::move(other.val)), line(other.line), mess(std::move(other.mess)) {} ~Exept() {} }; struct FLAGS { bool unexpectedIdVal = false; //taken leter before dot bool unexpectedBehaviorBeforeDot = false; //taken later after dot bool unexpectedBehaviorAfterDot = false; bool numStartFromNull = false; bool unexpectedSignAfterDot = false; FLAGS() : unexpectedIdVal(false), unexpectedBehaviorBeforeDot(false), unexpectedBehaviorAfterDot(false), unexpectedSignAfterDot(false), numStartFromNull(false) {} void SET_FALSE_ALL() { unexpectedIdVal = false; unexpectedBehaviorBeforeDot = false; unexpectedBehaviorAfterDot = false; numStartFromNull = false; unexpectedSignAfterDot = false; } ~FLAGS() {} }; struct blockAddapter { int block; string whichBlock; int line; int id; blockAddapter(int b, string wB, int l, int idd) : block(b) , whichBlock(wB) , line(l) , id(idd) {} blockAddapter(const blockAddapter& other) : block(other.block) , whichBlock(other.whichBlock) , line(other.line) , id(other.id) {} blockAddapter(blockAddapter&& other) : block(other.block) , whichBlock(std::move(other.whichBlock)) , line(other.line) , id(other.id) {} ~blockAddapter() {} }; struct MPAMemento { int thisState; int indexThis; int nextState; int finishState; string messError; MPAMemento( int a, int b, int c, int d, string e ) : thisState(a) , indexThis(b) , nextState(c) , finishState(d) , messError(e) {} MPAMemento( const MPAMemento& other ) : thisState( other.thisState ) , indexThis( other.indexThis ) , nextState( other.nextState ) , finishState( other.finishState ) , messError(other.messError) {} MPAMemento( MPAMemento&& other ) : thisState( other.thisState ) , indexThis( other.indexThis ) , nextState( other.nextState ) , finishState( other.finishState ) , messError( std::move( other.messError ) ) {} friend std::ostream& operator<< ( std::ostream& os, const MPAMemento& dt ) { os << std::setw( 5 ) << dt.thisState << std::setw( 5 ) << dt.indexThis << std::setw( 5 ) << dt.nextState << std::setw( 5 ) << dt.finishState << std::setw( 30 ) << dt.messError; return os; } ~MPAMemento() {} };
// ------------------------------------------------------------------------------------------------ #include "Common.hpp" // ------------------------------------------------------------------------------------------------ #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> // ------------------------------------------------------------------------------------------------ namespace SqMod { // ------------------------------------------------------------------------------------------------ void SqDateToMySQLTime(Object & obj, MYSQL_TIME & t) { // The resulted date values uint16_t year = 0; uint8_t month = 0, day = 0; { // Obtain the initial stack size const StackGuard sg; // Push the specified object onto the stack Var< Object >::push(DefaultVM::Get(), obj); // Attempt to get the values inside the specified object if (SQ_FAILED(SqMod_GetDate(DefaultVM::Get(), -1, &year, &month, &day))) { STHROWF("Invalid date specified"); } } // Populate the given structure t.year = year; t.month = month; t.day = day; t.hour = 0; t.minute = 0; t.second = 0; t.neg = false; t.second_part = 0; t.time_type = MYSQL_TIMESTAMP_DATE; } // ------------------------------------------------------------------------------------------------ void SqTimeToMySQLTime(Object & obj, MYSQL_TIME & t) { // The resulted time values uint8_t hour = 0, minute = 0, second = 0; uint16_t milli = 0; { // Obtain the initial stack size const StackGuard sg; // Push the specified object onto the stack Var< Object >::push(DefaultVM::Get(), obj); // Attempt to get the values inside the specified object if (SQ_FAILED(SqMod_GetTime(DefaultVM::Get(), -1, &hour, &minute, &second, &milli))) { STHROWF("Invalid time specified"); } } // Populate the given structure t.year = 0; t.month = 0; t.day = 0; t.neg = false; t.second_part = (milli * 1000L); t.time_type = MYSQL_TIMESTAMP_TIME; } // ------------------------------------------------------------------------------------------------ void SqDatetimeToMySQLTime(Object & obj, MYSQL_TIME & t) { // The resulted date values uint16_t year = 0, milli = 0; uint8_t month = 0, day = 0, hour = 0, minute = 0, second = 0; { // Obtain the initial stack size const StackGuard sg; // Push the specified object onto the stack Var< Object >::push(DefaultVM::Get(), obj); // Attempt to get the values inside the specified object if (SQ_FAILED(SqMod_GetDatetime(DefaultVM::Get(), -1, &year, &month, &day, &hour, &minute, &second, &milli))) { STHROWF("Invalid date and time specified"); } } // Populate the given structure t.year = year; t.month = month; t.day = day; t.hour = hour; t.minute = minute; t.second = second; t.neg = false; t.second_part = (milli * 1000L); t.time_type = MYSQL_TIMESTAMP_DATETIME; } } // Namespace:: SqMod
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long int main() { ll i,w,h,s_w,s_h,s2_w,s2_h,ans,stp=0; cin>>w>>h; cin>>s_w>>s_h; cin>>s2_w>>s2_h; ans=(w); for(i=h; i>=0;i--){ ans+=i; if(i==s_h ){ ans-=s_w; if(ans<0 )ans=0; } if(i==s2_h){ ans-=s2_w; if(ans<0) ans=0;} } cout<<ans<<endl; return 0; }
vector<int> Solution::solve(vector<int> &A, int B) { vector<int> ans; priority_queue<int, vector<int>, greater<int> > pq; // Creating a min-heap for(int i=0;i<A.size();i++){ pq.push(A[i]); if(pq.size()>B){ pq.pop(); } } while(!pq.empty()){ ans.push_back(pq.top()); pq.pop(); } return ans; }
#pragma once #include "HumanoidFootprintManager.hpp" namespace FootStepPlanner { class FootStepManager { public : virtual ~FootStepManager(); private : }; }
#ifndef EXTERNALCOMMANDS_H #define EXTERNALCOMMANDS_H using namespace std; //int bg_pid; //int fg_pid; class ExternalCommands { public: ExternalCommands(); ~ExternalCommands(); void callExternal(int fg, vector<string> args); }; #endif
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { int t;cin>>t; while(t--) { int n,v,q;cin>>n; string x; char ch; map<char,int>ara; ll ans=0; while(n--) { getchar(); ch=getchar(); cin>>v; ara[ch]=v; } cin>>q; getline(cin,x); while(q--) { getline(cin,x); int len=x.size(); for(int i=0;i<len;i++){ ans+=ara[x[i]]; } } double bhag=( double)ans/100.0; cout<<setprecision(2)<<fixed<<bhag<<"$"<<endl; } return 0; }
#include"Maltese.h" #include<cstdio> Maltese::Maltese(const char* name) : Dog(LivesInterface::Origin::EVERYWHERE, name) { setColor(FUR_COLOR_WHITE); } Maltese::~Maltese() {} void Maltese::printToConsole() { using namespace std; cout << "우리 귀여운 말티즈~" << endl; Dog::printToConsole(); cout << endl; } const char* Maltese::getSpeciesString() { return "말티즈"; }
#include"LinkListStack.h" #include"ArrayStack.h" #include<ctime> //int main() { // LinkListStack<int>* Stack = new LinkListStack<int>(); // for (int i = 0; i < 5; i++) // { // Stack->push(i); // Stack->print(); // } // // Stack->pop(); // Stack->print(); // // return 0; //} template<typename T> double test(T *e, int op) { clock_t start=clock(); for (int i = 0; i < op; i++) { //cout << "1"; e->push(i); } for (int i = 0; i < op; i++) { e->pop(); } clock_t end = clock(); return (double)(end - start) / CLOCKS_PER_SEC; } int main() { ArrayStack<int>* stack1 = new ArrayStack<int>(); cout<<"ArrayStack:"<<test(stack1, 1000)<<"s"<<endl; LinkListStack<int>* stack2 = new LinkListStack<int>(); cout <<"LinkListStack:"<< test(stack2, 100000) << "s" << endl; return 0; }
#pragma once #include <stdlib.h> namespace _5_задание___работа_с_массивами { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { InitializeComponent(); // //TODO: добавьте код конструктора // } protected: /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::DataGridView^ dataGridView1; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::RichTextBox^ richTextBox1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::DataGridView^ dataGridView2; private: System::Windows::Forms::ToolStripMenuItem^ менюToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ вводМатрицыToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ сргеомполToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ сравнениеToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ сортировкаToolStripMenuItem; protected: private: /// <summary> /// Требуется переменная конструктора. /// </summary> System::ComponentModel::Container ^components; private: int n, m; array <double,2> ^arr; #pragma region Windows Form Designer generated code /// <summary> /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// </summary> void InitializeComponent(void) { System::Windows::Forms::DataGridViewCellStyle^ dataGridViewCellStyle3 = (gcnew System::Windows::Forms::DataGridViewCellStyle()); System::Windows::Forms::DataGridViewCellStyle^ dataGridViewCellStyle4 = (gcnew System::Windows::Forms::DataGridViewCellStyle()); this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->label3 = (gcnew System::Windows::Forms::Label()); this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox()); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->менюToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->вводМатрицыToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->сргеомполToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->сравнениеToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->сортировкаToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->dataGridView2 = (gcnew System::Windows::Forms::DataGridView()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->BeginInit(); this->menuStrip1->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView2))->BeginInit(); this->SuspendLayout(); // // dataGridView1 // this->dataGridView1->AllowUserToAddRows = false; this->dataGridView1->AllowUserToDeleteRows = false; this->dataGridView1->AllowUserToResizeColumns = false; this->dataGridView1->AllowUserToResizeRows = false; this->dataGridView1->AutoSizeColumnsMode = System::Windows::Forms::DataGridViewAutoSizeColumnsMode::Fill; this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; dataGridViewCellStyle3->Alignment = System::Windows::Forms::DataGridViewContentAlignment::MiddleLeft; dataGridViewCellStyle3->BackColor = System::Drawing::SystemColors::Window; dataGridViewCellStyle3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); dataGridViewCellStyle3->ForeColor = System::Drawing::SystemColors::ControlText; dataGridViewCellStyle3->SelectionBackColor = System::Drawing::SystemColors::Highlight; dataGridViewCellStyle3->SelectionForeColor = System::Drawing::SystemColors::HighlightText; dataGridViewCellStyle3->WrapMode = System::Windows::Forms::DataGridViewTriState::True; this->dataGridView1->DefaultCellStyle = dataGridViewCellStyle3; this->dataGridView1->Location = System::Drawing::Point(185, 27); this->dataGridView1->MaximumSize = System::Drawing::Size(264, 235); this->dataGridView1->MinimumSize = System::Drawing::Size(264, 235); this->dataGridView1->Name = L"dataGridView1"; this->dataGridView1->ReadOnly = true; this->dataGridView1->RowHeadersWidthSizeMode = System::Windows::Forms::DataGridViewRowHeadersWidthSizeMode::DisableResizing; this->dataGridView1->Size = System::Drawing::Size(264, 235); this->dataGridView1->TabIndex = 0; // // textBox1 // this->textBox1->Location = System::Drawing::Point(12, 46); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(150, 20); this->textBox1->TabIndex = 2; // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(9, 30); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(120, 13); this->label1->TabIndex = 3; this->label1->Text = L"Введите кол-во строк:"; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(9, 76); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(138, 13); this->label2->TabIndex = 5; this->label2->Text = L"Введите кол-во столбцов:"; // // textBox2 // this->textBox2->Location = System::Drawing::Point(12, 92); this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(150, 20); this->textBox2->TabIndex = 4; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(9, 122); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(153, 13); this->label3->TabIndex = 7; this->label3->Text = L"Введите элементы массива:"; // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point(12, 139); this->richTextBox1->Name = L"richTextBox1"; this->richTextBox1->Size = System::Drawing::Size(150, 123); this->richTextBox1->TabIndex = 10; this->richTextBox1->Text = L""; // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) {this->менюToolStripMenuItem}); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(728, 24); this->menuStrip1->TabIndex = 11; this->menuStrip1->Text = L"menuStrip1"; // // менюToolStripMenuItem // this->менюToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) {this->вводМатрицыToolStripMenuItem, this->сргеомполToolStripMenuItem, this->сравнениеToolStripMenuItem, this->сортировкаToolStripMenuItem}); this->менюToolStripMenuItem->Name = L"менюToolStripMenuItem"; this->менюToolStripMenuItem->Size = System::Drawing::Size(53, 20); this->менюToolStripMenuItem->Text = L"Меню"; // // вводМатрицыToolStripMenuItem // this->вводМатрицыToolStripMenuItem->Name = L"вводМатрицыToolStripMenuItem"; this->вводМатрицыToolStripMenuItem->Size = System::Drawing::Size(245, 22); this->вводМатрицыToolStripMenuItem->Text = L"Ввод матрицы"; this->вводМатрицыToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::вводМатрицыToolStripMenuItem_Click); // // сргеомполToolStripMenuItem // this->сргеомполToolStripMenuItem->Name = L"сргеомполToolStripMenuItem"; this->сргеомполToolStripMenuItem->Size = System::Drawing::Size(245, 22); this->сргеомполToolStripMenuItem->Text = L"Среднее геом. положительных"; this->сргеомполToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::сргеомполToolStripMenuItem_Click); // // сравнениеToolStripMenuItem // this->сравнениеToolStripMenuItem->Name = L"сравнениеToolStripMenuItem"; this->сравнениеToolStripMenuItem->Size = System::Drawing::Size(245, 22); this->сравнениеToolStripMenuItem->Text = L"Сравнение"; this->сравнениеToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::сравнениеToolStripMenuItem_Click); // // сортировкаToolStripMenuItem // this->сортировкаToolStripMenuItem->Name = L"сортировкаToolStripMenuItem"; this->сортировкаToolStripMenuItem->Size = System::Drawing::Size(245, 22); this->сортировкаToolStripMenuItem->Text = L"Сортировка"; this->сортировкаToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::сортировкаToolStripMenuItem_Click); // // dataGridView2 // this->dataGridView2->AllowUserToAddRows = false; this->dataGridView2->AllowUserToDeleteRows = false; this->dataGridView2->AllowUserToResizeColumns = false; this->dataGridView2->AllowUserToResizeRows = false; this->dataGridView2->AutoSizeColumnsMode = System::Windows::Forms::DataGridViewAutoSizeColumnsMode::Fill; this->dataGridView2->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; dataGridViewCellStyle4->Alignment = System::Windows::Forms::DataGridViewContentAlignment::MiddleLeft; dataGridViewCellStyle4->BackColor = System::Drawing::SystemColors::Window; dataGridViewCellStyle4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); dataGridViewCellStyle4->ForeColor = System::Drawing::SystemColors::ControlText; dataGridViewCellStyle4->SelectionBackColor = System::Drawing::SystemColors::Highlight; dataGridViewCellStyle4->SelectionForeColor = System::Drawing::SystemColors::HighlightText; dataGridViewCellStyle4->WrapMode = System::Windows::Forms::DataGridViewTriState::True; this->dataGridView2->DefaultCellStyle = dataGridViewCellStyle4; this->dataGridView2->Location = System::Drawing::Point(455, 27); this->dataGridView2->MaximumSize = System::Drawing::Size(264, 235); this->dataGridView2->MinimumSize = System::Drawing::Size(264, 235); this->dataGridView2->Name = L"dataGridView2"; this->dataGridView2->ReadOnly = true; this->dataGridView2->RowHeadersWidthSizeMode = System::Windows::Forms::DataGridViewRowHeadersWidthSizeMode::DisableResizing; this->dataGridView2->Size = System::Drawing::Size(264, 235); this->dataGridView2->TabIndex = 0; // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(728, 276); this->Controls->Add(this->dataGridView2); this->Controls->Add(this->richTextBox1); this->Controls->Add(this->label3); this->Controls->Add(this->label2); this->Controls->Add(this->textBox2); this->Controls->Add(this->label1); this->Controls->Add(this->textBox1); this->Controls->Add(this->dataGridView1); this->Controls->Add(this->menuStrip1); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::Fixed3D; this->MainMenuStrip = this->menuStrip1; this->MaximizeBox = false; this->Name = L"MyForm"; this->Text = L"Матрицы"; (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->EndInit(); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView2))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void вводМатрицыToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { //this->ClientSize = System::Drawing::Size(455, 276); //dataGridView2->Visible=false; dataGridView1->Columns->Clear(); dataGridView1->Rows->Clear(); String ^strBuf; int i,j; n = Convert::ToInt16(textBox1->Text); m = Convert::ToInt16(textBox2->Text); dataGridView1->ColumnCount=m; arr = gcnew array <double, 2>(n, m); for (i=0; i<n; i++){ dataGridView1->Rows->Add(); strBuf = richTextBox1->Lines[i]->ToString(); array <String ^>^ str = strBuf->Split(' '); for (j=0; j<m; j++){ //MessageBox::Show(str[j]); dataGridView1->Rows[i]->Cells[j]->Value=Convert::ToString(str[j]); arr[i,j] = Convert::ToDouble(str[j]); } } } private: System::Void сргеомполToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { int i, j, k=0; double summPol = 0, srGeom; n = dataGridView1->RowCount; m = dataGridView1->ColumnCount; for (i=0; i<n; i++){ for (j=0; j<m; j++){ if (arr[i,j] > 0){ summPol+=arr[i, j]; k++; } } } srGeom = Math::Pow(summPol, 1./k); MessageBox::Show("Среднее геометрическое положительных = " + srGeom); } private: System::Void сравнениеToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { int i, j, k=0, maxi=0, maxj=0; double summPol = 0, srGeom, maxVal; n = dataGridView1->RowCount; m = dataGridView1->ColumnCount; for (i=0; i<n; i++){ for (j=0; j<m; j++){ if (arr[i,j] > 0){ summPol+=arr[i, j]; k++; } } } srGeom = Math::Pow(summPol, 1./k); maxVal = arr[0, 0]; for (i=0; i<n; i++){ for (j=0; j<m; j++){ if (arr[i, j] > maxVal){ maxi = i; maxj = j; } } } if (maxj == 0){ if (srGeom > arr[maxi-1, maxj]){ MessageBox::Show("Среднее геометрическое положительных больше элемента стоящего перед максимальным"); } else { MessageBox::Show("Среднее геометрическое положительных меньше элемента стоящего перед максимальным"); } } else { if (srGeom > arr[maxi, maxj-1]){ MessageBox::Show("Среднее геометрическое положительных больше элемента стоящего перед максимальным"); } else { MessageBox::Show("Среднее геометрическое положительных меньше элемента стоящего перед максимальным"); } } } private: System::Void сортировкаToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { dataGridView2->Columns->Clear(); dataGridView2->Rows->Clear(); //this->ClientSize = System::Drawing::Size(728, 276); //dataGridView2->Visible=true; int i, j, k; n = dataGridView1->RowCount; m = dataGridView1->ColumnCount; dataGridView2->RowCount = n; dataGridView2->ColumnCount = m; for (k=0; k<n; k++){ for(i = 0 ; i < m - 1; i++) { for(j = 0 ; j < m - i - 1 ; j++) { double VAL = arr[k, j]; double VAL2 = arr[k, j+1]; if(VAL > VAL2) { double tmp = VAL; arr[k, j] = VAL2 ; arr[k, j+1] = tmp; } } } } for (i=0; i<n; i++){ for (j=0; j<m; j++){ dataGridView2->Rows[i]->Cells[j]->Value = arr[i, j]; } } } }; }
#include <cstdio> #include <algorithm> using namespace std; bool cmp(int a, int b) { return a > b; } // 0-1背包问题,需要记录选择 int main() { const int MAXM = 110; const int MAXN = 10010; int N, M; scanf("%d%d", &N, &M); int c[MAXN]; for (int i = 0; i < N; i++) scanf("%d", &c[i]); // 默认升序 // 到底是升序还是降序 // 必须要降序,降序最后才循环1,保证选1的时候可以被更新,满足字典序 // 如果是升序,根本不知道前面的状态到底有没有用1 // 挺难理解的,需要对数组整个更新的过程有一个比较好的认识 sort(c, c + N); int dp[MAXM] = {}; bool choice[MAXN][MAXM] = {}; for (int i = 0; i < N; i++) { for (int j = M; j >= c[i]; j--) { if (dp[j - c[i]] + c[i] > dp[j]) { dp[j] = dp[j - c[i]] + c[i]; choice[i][j] = true; } else { choice[i][j] = false; } } } if (dp[M] != M) printf("No Solution\n"); else { int j = M; bool flag[MAXN] = {}; int num = 0; for (int i = N; i >= 0; i--) { if (choice[i][j]) { j -= c[i]; flag[i] = true; num++; } } for (int i = N; i >= 0; i--) { if (flag[i]) { printf("%d", c[i]); num--; num == 0 ? printf("\n") : printf(" "); } } } }
#include <algorithm> #include <cstdio> #include <iostream> using namespace std; typedef long long ll; struct Rubbish { int t, h, e; Rubbish() {} bool operator<(Rubbish& a) { return t < a.t; } }; const int maxn = 105, maxh = 1005; int h, n; Rubbish rub[maxn]; // dp[i][j]表示前i个垃圾到达高度j时能维持的最大生命时间 int dp[maxn][maxh + 25] = { 0 }; // #define DEBUG int main() { #ifdef DEBUG freopen("d:\\.in", "r", stdin); freopen("d:\\.out", "w", stdout); #endif cin >> h >> n; for (int i = 1; i <= n; ++i) cin >> rub[i].t >> rub[i].e >> rub[i].h; sort(rub + 1, rub + n + 1); dp[0][0] = 10; for (int i = 1; i <= n; ++i) for (int j = 0; j <= h + 25; ++j) { // 要活着 if (dp[i - 1][j] >= rub[i].t) // 用来吃 dp[i][j] = dp[i - 1][j] + rub[i].e; // 要活着 if (j >= rub[i].h && dp[i - 1][j - rub[i].h] >= rub[i].t) { if (j >= h) { cout << rub[i].t; return 0; } // 用来填高度 dp[i][j] = max(dp[i][j], dp[i - 1][j - rub[i].h]); } } // 如若无法出去,最大存活时间就是依次吃掉每个垃圾所能坚持的时间 int idx; for (idx = 0; idx < n; ++idx) if (dp[idx + 1][0] == 0) break; cout << dp[idx][0]; return 0; }
#include "Command_Line_UI/ui.hpp" int main(int argc, char** argv) { #ifndef FUNDRAISING_USE_UI Fundraising::Command_Line::command_line_run(argc, argv); #else Fundraising::UI::run(); #endif return 0; }
#ifndef WBPEOWNER_H #define WBPEOWNER_H #include "wbpe.h" class WBPEOwner : public WBPE { public: WBPEOwner(); virtual ~WBPEOwner(); DEFINE_WBPE_FACTORY( Owner ); virtual void InitializeFromDefinition( const SimpleString& DefinitionName ); virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const; private: bool m_Topmost; }; #endif // WBPEOWNER_H
#ifndef _HS_SFM_CALIBRATE_PLANAR_CALIBRATION_GENERATOR_HPP_ #define _HS_SFM_CALIBRATE_PLANAR_CALIBRATION_GENERATOR_HPP_ #include <cmath> #include "hs_math/random/uniform_random_var.hpp" #include "hs_math/random/normal_random_var.hpp" #include "hs_math/linear_algebra/eigen_macro.hpp" #include "hs_math/geometry/euler_angles.hpp" #include "hs_sfm/sfm_utility/camera_type.hpp" #include "hs_sfm/sfm_utility/projective_functions.hpp" #include "hs_sfm/calibrate/planar_calibrator.hpp" namespace hs { namespace sfm { namespace calibrate { /** * 平面标定模拟数据生成器。 * * 该Functor生成模拟的平面点和影像点对应,以及多张相片拍摄时相机的外方位元素( * 即相机旋转与相机平移),并为平面点与影像点加入高斯误差。其中平面点是位于z=0 * 平面的棋盘点。相机外方位元素由以下方法生成:随机选取一个由三个旋转角组成的 * 旋转,在该旋转后的坐标系的Z轴上取距离为f * w_p / w_i的点作为相机位置,其中 * f为焦距w_p为标定棋盘宽度,w_i为影像宽度,然后为相机位置以及相机旋转加入高斯 * 误差以形成较为无规率的配置。 */ template <typename _Scalar, typename _ImageDimension> class PlanarCalibrationGenerator { public: typedef _Scalar Scalar; typedef _ImageDimension ImageDimension; typedef hs::sfm::calibrate::PlanarCalibrator<Scalar> Calibrator; typedef typename Calibrator::IntrinsicParams IntrinsicParams; typedef typename Calibrator::ExtrinsicParams ExtrinsicParams; typedef typename Calibrator::ExtrinsicParamsContainer ExtrinsicParamsContainer; private: typedef typename Calibrator::Key Key; typedef typename Calibrator::Point Point; typedef typename Calibrator::Correspondence Correspondence; typedef typename Calibrator::PatternView PatternView; typedef typename Calibrator::PatternViewContainer PatternViewContainer; typedef hs::math::geometry::EulerAngles<Scalar> EulerAngles; typedef EIGEN_VECTOR(Scalar, 3) Vector3; typedef typename EulerAngles::OrthoRotMat RMatrix; typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33; public: PlanarCalibrationGenerator( const IntrinsicParams& intrinsic_params, Scalar pattern_grid_size, size_t number_of_grid_rows, size_t number_of_grid_cols, size_t number_of_views, ImageDimension image_width, ImageDimension image_height) : intrinsic_params_(intrinsic_params), pattern_grid_size_(pattern_grid_size), number_of_grid_rows_(number_of_grid_rows), number_of_grid_cols_(number_of_grid_cols), number_of_views_(number_of_views), image_width_(image_width), image_height_(image_height) {} int operator() (ExtrinsicParamsContainer& extrinsic_params_set, PatternViewContainer& pattern_views) const { extrinsic_params_set.resize(number_of_views_); pattern_views.resize(number_of_views_); Scalar pattern_width = pattern_grid_size_ * (number_of_grid_cols_ - 1); Scalar pattern_height = pattern_grid_size_ * (number_of_grid_rows_ - 1); Scalar distance = intrinsic_params_.focal_length() * std::max(pattern_width / Scalar(image_width_), pattern_height / Scalar(image_height_)); Scalar camera_rotation_stddev = Scalar(5) * Scalar(M_PI) / Scalar(180); Scalar camera_position_x_stddev = distance * 0.02; Scalar camera_position_y_stddev = distance * 0.02; Scalar camera_position_z_stddev = distance * 0.04; for (size_t i = 0; i < number_of_views_; i++) { //生成相机旋转 Vector3 euler_angles_mean, euler_angles_random, min, max; min.setZero(); max << Scalar(20) * Scalar(M_PI) / Scalar(180), Scalar(20) * Scalar(M_PI) / Scalar(180), Scalar(M_PI); hs::math::random::UniformRandomVar<Scalar, 3>::Generate( min, max, euler_angles_mean); Matrix33 euler_angles_covariance = Matrix33::Identity(); euler_angles_covariance *= camera_rotation_stddev * camera_rotation_stddev; hs::math::random::NormalRandomVar<Scalar, 3>::Generate( euler_angles_mean, euler_angles_covariance, euler_angles_random); EulerAngles euler_angles; euler_angles[0] = euler_angles_random[0]; euler_angles[1] = euler_angles_random[1]; euler_angles[2] = euler_angles_random[2]; RMatrix r_matrix = euler_angles.template ToOrthoRotMat<1, 2, 3, 1>(); extrinsic_params_set[i].rotation() = r_matrix; //生成相机位置 Vector3 camera_position_mean = r_matrix.col(2) * distance; Matrix33 camera_position_covariance = Matrix33::Identity(); camera_position_covariance(0, 0) = camera_position_x_stddev * camera_position_x_stddev; camera_position_covariance(1, 1) = camera_position_y_stddev * camera_position_y_stddev; camera_position_covariance(2, 2) = camera_position_z_stddev * camera_position_z_stddev; hs::math::random::NormalRandomVar<Scalar, 3>::Generate( camera_position_mean, camera_position_covariance, extrinsic_params_set[i].position()); std::cout<<"camera position:\n"<<extrinsic_params_set[i].position()<<"\n"; } //生成平面三维点和影像二维点 for (size_t i = 0; i < number_of_grid_rows_; i++) { for (size_t j = 0; j < number_of_grid_cols_; j++) { Point point; point << pattern_grid_size_ * Scalar(j) - pattern_width * Scalar(0.5), pattern_grid_size_ * Scalar(i) - pattern_height * Scalar(0.5), Scalar(0); for (size_t k = 0; k < number_of_views_; k++) { Key key = hs::sfm::ProjectiveFunctions<Scalar>:: WorldPointProjectToImageKeyNoDistort( intrinsic_params_, extrinsic_params_set[k], point); if (key[0] >=0 && key[0] < Scalar(image_width_) && key[1] >=0 && key[1] < Scalar(image_height_)) { key = hs::sfm::ProjectiveFunctions<Scalar>:: WorldPointProjectToImageKey( intrinsic_params_, extrinsic_params_set[k], point); if (key[0] >= 0 && key[0] < Scalar(image_width_) && key[1] >= 0 && key[1] < Scalar(image_height_)) { pattern_views[k].push_back(Correspondence(key, point)); } } } } } auto itr_pattern_view = pattern_views.begin(); auto itr_extrinsic_params = extrinsic_params_set.begin(); for (; itr_pattern_view != pattern_views.end();) { if (itr_pattern_view->size() < 10) { itr_pattern_view = pattern_views.erase(itr_pattern_view); itr_extrinsic_params = extrinsic_params_set.erase(itr_extrinsic_params); } else { ++itr_pattern_view; ++itr_extrinsic_params; } } return 0; } const IntrinsicParams& intrinsic_params() const { return intrinsic_params_; } size_t number_of_views() const{return number_of_views_;} private: /** * 相机内参数真实值 */ IntrinsicParams intrinsic_params_; /** * 标定棋盘一个格子的大小,以米为单位 */ Scalar pattern_grid_size_; /** * 标定棋盘格子行数 */ size_t number_of_grid_rows_; /** * 标定棋盘格子列数 */ size_t number_of_grid_cols_; /** * 随机生成的影像数量 */ size_t number_of_views_; /** * 影像宽度,像素为单位 */ ImageDimension image_width_; /** * 影像高度,像素为单位 */ ImageDimension image_height_; }; } } } #endif
////////////////////////////////////////////////////////////////////// // GLFBO.h // // Fangyang SHEN, VRLab, Beihang University // me@shenfy.net // // Edited by BAI Gang, for unsigned char pixel values... // // (C) Copyright VRLab, Beihang University 2009. ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Brief Description // // Simple Wrapper for OpenGL Frame Buffer Object // ////////////////////////////////////////////////////////////////////// #ifndef __GL_FBO_H_ #define __GL_FBO_H_ #include <gl/glew.h> class CGLCamera; class CGLFBO { public: CGLFBO(void); ~CGLFBO(void); void Init(int width, int height); void ReleaseFBO(void); void BeginDraw2FBO(void); void EndDraw2FBO(void); bool CheckFBOErr(void); bool IsReady(void); float *ReadPixels(void); int GetWidth(void) {return m_width;} int GetHeight(void) {return m_height;} // added by Bai, Gang // for convenient usage inline const GLuint& GetColorTex() const {return m_colorTexture;} protected: GLuint m_fbo; GLuint m_colorTexture; GLuint m_depthTexture; float *m_output; int m_width, m_height; }; #endif //__GL_FBO_H_
// ***************************************************************** // This file is part of the CYBERMED Libraries // // Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve), // Federal University of Paraiba and University of São Paulo. // All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // ***************************************************************** #include "myViewMono.h" #include <iostream> #include <cybermed/cyb5DTGlove.h> void MyViewMono::keyboard(unsigned char key, int x, int y) { CybParameters *cybCore = CybParameters::getInstance(); CybInterator *interator; Cyb5DTGlove *glove; switch (key) { /*Stop the auto calibrate*/ case '1': interator = cybCore->getInterator(0); glove = dynamic_cast<Cyb5DTGlove *>(interator->getDevice()); glove->setAutoCalibrate(false); std::cout << "Auto calibrate disabled!" << std::endl; break; /*Reset the calibration*/ case '2': interator = cybCore->getInterator(0); glove = dynamic_cast<Cyb5DTGlove *>(interator->getDevice()); glove->resetCalibration(); std::cout << "Calibration reseted!" << std::endl; break; /*Save the Calibration*/ case '3': interator = cybCore->getInterator(0); glove = dynamic_cast<Cyb5DTGlove *>(interator->getDevice()); glove->saveCalibration("calibration.cal"); std::cout << "Calibration saved!" << std::endl; break; /*Load the Calibration*/ case '4': interator = cybCore->getInterator(0); glove = dynamic_cast<Cyb5DTGlove *>(interator->getDevice()); glove->loadCalibration("calibration.cal"); std::cout << "Calibration loaded!" << std::endl; break; } }
#ifndef TREEWIDZARD_INSTRUCTIVETREEDECOMPOSITION_H #define TREEWIDZARD_INSTRUCTIVETREEDECOMPOSITION_H #include <algorithm> #include <cstring> #include <experimental/filesystem> #include <iostream> #include <sstream> #include "../Multigraph/MultiGraph.h" #include "ConcreteTreeDecomposition.h" #include "Term.h" class InstructiveTreeDecompositionNodeContent : public TermNodeContentType { private: std::string symbol = "Leaf"; public: InstructiveTreeDecompositionNodeContent(); InstructiveTreeDecompositionNodeContent(const std::string &symbol); InstructiveTreeDecompositionNodeContent( const InstructiveTreeDecompositionNodeContent &instructiveTreeDecompositionNodeContent); InstructiveTreeDecompositionNodeContent &operator=( const InstructiveTreeDecompositionNodeContent &other); bool operator<(const InstructiveTreeDecompositionNodeContent &rhs) const; bool operator>(const InstructiveTreeDecompositionNodeContent &rhs) const; bool operator<=(const InstructiveTreeDecompositionNodeContent &rhs) const; bool operator>=(const InstructiveTreeDecompositionNodeContent &rhs) const; bool operator==(const InstructiveTreeDecompositionNodeContent &rhs) const; bool operator!=(const InstructiveTreeDecompositionNodeContent &rhs) const; const std::string &getSymbol() const; void setSymbol(const std::string &symbol); std::string nodeInformation() override; void print() override; int symbolType( std::string symbol) const; // returns "0 if Leaf, 1 if IntroVertex, 2 if // ForgetVertex, 3 if IntroEdge or 4 if Join" // ToDo: implement this std::vector<int> symbolNumbers( std::string s) const; // returns vector "[i]" if symbol="IntroVertex_i // or ForgetVertex_i", Returns vector "[i,j]" if // symbol="IntroEdge_i_j", Returns empty vector if // symbol = "Join" std::vector<int> extractIntegerWords(std::string s) const; // Define the lexicographically smallest content. std::string smallestContent(); }; class InstructiveTreeDecomposition : public Term<InstructiveTreeDecompositionNodeContent> { public: void writeToFile(std::string fileName); std::shared_ptr<TermNode<ConcreteNode>> constructCTDNode( TermNode<InstructiveTreeDecompositionNodeContent> &node); ConcreteTreeDecomposition convertToConcreteTreeDecomposition(); }; #endif // TREEWIDZARD_INSTRUCTIVETREEDECOMPOSITION_H
#include "Inventory.h" Inventory::Inventory() : IStorage(4, 1) { }
#include <bits/stdc++.h> #define ll long long #define MOD 1000000007 using namespace std; ll n, x, y, cx, cy, ans; ll f[2000006]; ll r[2000006]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> x >> y; f[0] = 0; f[1] = 1; for(int i=2; i<=max(x,y)+1; i++) f[i]=(f[i-1]+f[i-2])%MOD; r[1] = 1; for(int i = 2; i < 2000006; ++i) r[i] = (MOD - (MOD/i) * r[MOD%i] % MOD) % MOD; x-=1,y-=1; n = x+y; cx = cy = 1; for(int i=x+1; i<=n; i++) cx=(cx*i)%MOD,cx=(cx*r[i-x])%MOD; // cout<<cx<<endl; for(int i=0; i<=y; i++) { ans=(ans+f[i+1]*cx)%MOD; // cout<<f[i+1]<<" "<<cx<<endl; cx=(cx*(n-i-x))%MOD; cx=(cx*r[n-i])%MOD; } for(int i=y+1; i<=n; i++) cy=(cy*i)%MOD,cy=(cy*r[i-y])%MOD; // cout<<cy<<endl; for(int i=0; i<=x; i++) { ans=(ans+f[i+1]*cy)%MOD; // cout<<f[i+1]<<" "<<cy<<endl; cy=(cy*(n-i-y))%MOD; cy=(cy*r[n-i])%MOD; } cout<<ans; return 0; }
#include <iostream> #include <math.h> using namespace std; float median_h(int arr[], int size){ float median = 0.0; if(size%2 == 0) median = (arr[size/2] + arr[(size/2)-1])/2; else median = arr[(int)ceil((float)size/(float)2)]; return median; } float median(int arr1[], int arr2[], int size_1, int size_2){ if(size_1 == 1) return (arr1[0] + arr2[0])/2; float m1 = median_h(arr1,size_1); float m2 = median_h(arr2,size_2); float median_res = 0.0; if(m1 == m2) return m1; else{ int index = 0; int size = ceil((float)size_1/(float)2); (size_1 % 2 == 0)? index = size_1/2 + 1 : index = size_1/2; if(m1 < m2) median_res = median(arr1 + index,arr2, size, size); else median_res = median(arr1,arr2 + index, size, size); } return median_res; } int main(void){ int arr1[] = {1,2,3,4}; int arr2[] = {5,8,10,20}; float med = median(arr1,arr2,5,5); cout << med << endl; }
#include "main.h" int main(int argc, char* argv[]) { MyTAR mytar = MyTAR(); if(!mytar.openFile(argc, argv)) return 0; mytar.readFile(); mytar.printList(); return 0; }
/* ID: hjl11841 TASK: namenum LANG: C++ */ #include<bits/stdc++.h> using namespace std; string name[5000]; char a[10][4]={{},{},"ABC","DEF","GHI","JKL","MNO","PRS","TUV","WXY"}; int main(){ freopen("namenum.in","r",stdin); freopen("namenum.out","w",stdout); int n=0; cin>>name[n]; n++; freopen("dict.txt","r",stdin); while(cin>>name[n]) n++; string x=name[0]; n--; bool none=1; for(int i=1;i<=n;i++){ bool tmp=(name[i].size()==x.size()); for(int j=0;j<name[i].size();j++){ char c=name[i][j]; tmp=tmp&(c==a[x[j]-'0'][0]||c==a[x[j]-'0'][1]||c==a[x[j]-'0'][2]); } if(tmp){ cout<<name[i].c_str()<<endl; none=0; } } if(none) cout<<"NONE"<<endl; }
# include "velocityBound.h" VelocityBound velocityBound(double q[6], double qMin[6], double qMax[6], double V[6], double A[6], double Ts) { // qDotMin <= qDot <= qDotMax // Eq. (13) in "Control of Redundant Robots Under Hard Joint // Constraints: Saturation in the Null Space", F, Flacco, A. De Luca, // O. Khatib, IEEE Trnsactions on Robotics, 2015 double a, b, c; VelocityBound bound; for (int i = 0; i < 6; i++) { // Ensure that V and A is positive V[i] = fabs(V[i]); A[i] = fabs(A[i]); // Ensure q is in [qMin, qMax] q[i] = fmax(q[i], qMin[i]); q[i] = fmin(q[i], qMax[i]); // Lower Bound a = (qMin[i] - q[i])/Ts; b = -V[i]; c = -sqrt(2*A[i]*(q[i] - qMin[i])); bound.qDotMin[i] = fmax(a, fmax(b, c)); // Upper Bound a = (qMax[i] - q[i])/Ts; b = V[i]; c = sqrt(2*A[i]*(qMax[i] - q[i])); bound.qDotMax[i] = fmin(a, fmin(b, c)); } // Return velocity bound return bound; }
#ifndef STICKUINO_UTILITIES_LOOPABLE_H #define STICKUINO_UTILITIES_LOOPABLE_H #include "DynamicArray.h" #include <Arduino.h> namespace Stickuino { namespace Utilities { template <typename SelfType> class ScheduledTask; /// <summary> /// A loopable object. /// </summary> class Loopable { public: /// <summary> /// Creates a new Loopable. /// </summary> /// <param name="type">The type of the Loopable.</param> Loopable(const char* type = "Loopable"); /// <summary> /// Declares the object virtual. /// </summary> virtual ~Loopable() = 0; /// <summary> /// Loops the object. /// </summary> /// <param name="interrupt">The latest interrupt.</param> void loop(volatile int& interrupt); /// <summary> /// Is executed before child objects are looped. /// </summary> /// <param name="interrupt">The latest interrupt.</param> virtual void preLoop(volatile int& interrupt); /// <summary> /// Is executed after child objects are looped. /// </summary> /// <param name="interrupt"></param> virtual void postLoop(volatile int& interrupt); /// <summary> /// Gets the type of the Loopable. /// </summary> /// <returns>The Loopable's type.</returns> const char* getType() const; /// <summary> /// Gets the parent. /// </summary> /// <returns>The parent.</returns> Loopable* getParent() const; /// <summary> /// Gets the children. /// </summary> /// <returns>The children.</returns> const DynamicArray<Loopable*>& getChildren() const; /// <summary> /// Checks whether this Loopable is enabled. /// </summary> /// <returns>Whether this Loopable is enabled.</returns> bool isEnabled() const; /// <summary> /// Checks whether this Loopable is disabled. /// </summary> /// <returns>Whether this Loopable is disabled.</returns> bool isDisabled() const; /// <summary> /// Enables the Loopable. /// </summary> void enable(); /// <summary> /// Disables the Loopable. /// </summary> void disable(); /// <summary> /// Is called just after the Loopable becomes enabled. /// </summary> virtual void enabled(); /// <summary> /// Is called just before the Loopable becomes disabled. /// </summary> virtual void disabled(); /// <summary> /// Adds the specified Loopable as a child of this Loopable. /// </summary> /// <param name="loopable">The Loopable to add.</param> void addChild(Loopable* loopable); /// <summary> /// Removes the specified Loopable from the children of this Loopable. /// </summary> /// <param name="name">The Loopable to remove.</param> void removeChild(Loopable* loopable); protected: template <typename SelfType> /// <summary> /// Schedules a function to execute after the specified delay. /// </summary> /// <param name="scheduledTask">The task to schedule.</param> /// <param name="executeNow">Whether the scheduled task should execute immediately.</param> void schedule(ScheduledTask<SelfType>* scheduledTask, const bool& executeNow = false); private: /// <summary> /// The type of the Loopable. /// </summary> const char* type_; /// <summary> /// The parent Loopable. /// </summary> Loopable* parent_ = nullptr; /// <summary> /// Whether the Loopable is enabled. Won't loop if false. /// </summary> bool enabled_ = true; /// <summary> /// The children of this loopable object. /// </summary> DynamicArray<Loopable*> children_; /// <summary> /// Whether to remove this object at the next loop. /// </summary> bool remove_ = false; }; } } #include "Loopable.hpp" #endif
#include <iostream> #include "RegistrationSystem.h" RegistrationSystem::RegistrationSystem():students(NULL),studentNumber(0) { } RegistrationSystem::~RegistrationSystem() { delete[] students; } void RegistrationSystem::addStudent(const int studentId, const string firstName, const string lastName) { if (studentId <= 0 || firstName == "" || lastName == "") { cout << "invalid student information, check id or name fields" << endl; return; } int index = 0; for (; index < studentNumber; index++) { if (studentId == students[index].studentId) { cout << "Student " << studentId << " already exists" << endl; return; } if (studentId < students[index].studentId) { break; } } Student* temp = new Student[studentNumber + 1]; for (int i = 0; i < index; i++) { temp[i] = students[i]; } temp[index].studentId = studentId; temp[index].firstName = firstName; temp[index].lastName = lastName; for (int i = index; i < studentNumber; i++) { temp[i + 1] = students[i]; } delete[] students; studentNumber++; students = temp; temp = NULL; cout << "Student " << studentId << " has been added" << endl; } void RegistrationSystem::deleteStudent(const int studentId) { if (studentId <= 0 || students == NULL || studentNumber <= 0) { if (studentId <= 0) cout << "invalid student id" << endl; else cout << "There are no students in the system" << endl; return; } int index = 0; for (; index < studentNumber; index++) { if (students[index].studentId == studentId) { break; } } if (index == studentNumber) { //it means id not exist cout << "Student " << studentId << " does not exist" << endl; return; } else { Student* temp = new Student[studentNumber - 1]; for (int i = 0; i < index; i++) { temp[i] = students[i]; } for (int i = index; i < studentNumber - 1; i++) { temp[i] = students[i + 1]; } delete[] students; studentNumber--; if (studentNumber == 0) temp = NULL; students = temp; temp = NULL; cout << "Student " << studentId << " has been deleted" << endl; } } void RegistrationSystem::showAllStudents() { if (students == NULL || studentNumber == 0) { cout << "There are no students in the system" << endl; return; } cout << "\nStudent id\t" << "Fist Name\t" << "Last Name" << endl; for (int i = 0; i < studentNumber; i++) { cout << students[i].studentId << "\t\t" << students[i].firstName << "\t\t" << students[i].lastName << endl; } cout << endl; } void RegistrationSystem::showStudent(const int studentId) { for (int i = 0; i < studentNumber; i++) { if (studentId == students[i].studentId) { cout << students[i].studentId << "\t\t" << students[i].firstName << "\t\t" << students[i].lastName << endl; return; } } cout << "Student " << studentId << " does not exist" << endl; }
/* * SomaPares.cpp * * Created on: 17 de fev de 2018 * Author: kryptonian */ #include <iostream> using namespace std; int cnt, soma; int main(){ for (int c = 1; c <= 500; c++){ if (c % 2 == 0){ cnt += 1; soma += c; } } cout << "\nExistem " << cnt << " números pares entre 1 e 500 (inclusive)" << endl; cout << "\nA soma entre todos os números pares é " << soma << endl; }
#include "pch.hpp" #include "DirectXHelper.hpp" #include "Math.hpp" #define STB_TRUETYPE_IMPLEMENTATION #define STB_RECT_PACK_IMPLEMENTATION #include "Core/StbRectPack.hpp" #include "TextRenderer.hpp" using Microsoft::WRL::ComPtr; using Windows::ApplicationModel::Package; AppCore::BitmapFont::BitmapFont( const std::string& File, const std::shared_ptr<DeviceResources>& DevRes, const Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> CmdList, size_t FirstChar, size_t NumChars ) : deviceResources(DevRes), chars(nullptr) { auto loc = Package::Current->InstalledLocation->Path; std::wstring_convert<std::codecvt_utf8<wchar_t>> convert; std::string file = convert.to_bytes(loc->Data()); file += "\\" + File; std::ifstream fin(file, std::ios::ate | std::ios::binary); if (fin.is_open()) { auto pos = fin.tellg(); byte* data = new byte[pos]; fin.seekg(0, std::ios::beg); fin.read((char*)data, pos); fin.close(); const unsigned texSize = 512; byte bitmap[texSize * texSize]; chars = new stbtt_bakedchar[NumChars]; stbtt_BakeFontBitmap(data, 0, 12, bitmap, texSize, texSize, (int)FirstChar, (int)NumChars, chars); auto d3dDevice = DevRes->GetD3DDevice(); // Describe and create a shader resource view (SRV) heap for the texture. D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = { }; srvHeapDesc.NumDescriptors = 1; srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; ThrowIfFailed(d3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&srvHeap))); D3D12_RESOURCE_DESC textureDesc = { }; textureDesc.MipLevels = 1; textureDesc.Format = DXGI_FORMAT_R8_UNORM; textureDesc.Width = texSize; textureDesc.Height = texSize; textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE; textureDesc.DepthOrArraySize = 1; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; ThrowIfFailed(d3dDevice->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &textureDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&texture))); const UINT64 uploadBufferSize = GetRequiredIntermediateSize(texture.Get(), 0, 1); // Create the GPU upload buffer. ThrowIfFailed(d3dDevice->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&textureUploadHeap))); D3D12_SUBRESOURCE_DATA textureData = { }; textureData.pData = bitmap; textureData.RowPitch = texSize * sizeof(byte); textureData.SlicePitch = textureData.RowPitch * texSize; UpdateSubresources(CmdList.Get(), texture.Get(), textureUploadHeap.Get(), 0, 0, 1, &textureData); CmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); // Describe and create a SRV for the texture. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = 1; d3dDevice->CreateShaderResourceView(texture.Get(), &srvDesc, srvHeap->GetCPUDescriptorHandleForHeapStart()); } } const D3D12_INPUT_ELEMENT_DESC AppCore::TextRenderer::inputLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; AppCore::TextRenderer::TextRenderer(const std::shared_ptr<DeviceResources>& DevRes) : deviceResources(DevRes), isReady(false) { return; auto d3dDevice = DevRes->GetD3DDevice(); //root sig CD3DX12_DESCRIPTOR_RANGE range; CD3DX12_ROOT_PARAMETER parameter; range.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0); parameter.InitAsDescriptorTable(1, &range, D3D12_SHADER_VISIBILITY_PIXEL); D3D12_ROOT_SIGNATURE_FLAGS rsFlags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; CD3DX12_ROOT_SIGNATURE_DESC descRootSignature; descRootSignature.Init(1, &parameter, 0, nullptr, rsFlags); ComPtr<ID3DBlob> pSignature; ComPtr<ID3DBlob> pError; AppCore::ThrowIfFailed(D3D12SerializeRootSignature(&descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetAddressOf(), pError.GetAddressOf())); AppCore::ThrowIfFailed(d3dDevice->CreateRootSignature(0, pSignature->GetBufferPointer(), pSignature->GetBufferSize(), IID_PPV_ARGS(&rootSig))); //pso CD3DX12_BLEND_DESC blendDesc(D3D12_DEFAULT); blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].LogicOpEnable = false; blendDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; blendDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO; blendDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; blendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f; CD3DX12_RASTERIZER_DESC rasterDesc(D3D12_DEFAULT); rasterDesc.AntialiasedLineEnable = true; rasterDesc.MultisampleEnable = true; D3D12_GRAPHICS_PIPELINE_STATE_DESC state = {}; state.InputLayout = { inputLayout, _countof(inputLayout) }; state.pRootSignature = rootSig.Get(); state.RasterizerState = rasterDesc; state.BlendState = blendDesc; state.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); state.SampleMask = UINT_MAX; state.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; state.NumRenderTargets = 1; state.RTVFormats[0] = DXGI_FORMAT_B8G8R8A8_UNORM; state.DSVFormat = DXGI_FORMAT_D32_FLOAT; state.SampleDesc.Count = 1; std::vector<byte> sources[2]; auto vs = AppCore::ReadDataAsync(L"Text.vs.hlsl") .then([&](const std::vector<byte>& data) { sources[0] = data; state.VS = { sources[0].data(), sources[0].size() }; }); auto ps = AppCore::ReadDataAsync(L"Text.ps.hlsl") .then([&](const std::vector<byte>& data) { sources[1] = data; state.PS = { sources[1].data(), sources[1].size() }; }); (vs && ps).then([&] { AppCore::ThrowIfFailed(d3dDevice->CreateGraphicsPipelineState(&state, IID_PPV_ARGS(&pso))); sources[0].clear(); sources[1].clear(); }).then([&] { //cbuf // Create a descriptor heap for the constant buffers. { D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { }; heapDesc.NumDescriptors = AppCore::c_frameCount; heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; // This flag indicates that this descriptor heap can be bound to the pipeline and that descriptors contained in it can be referenced by a root table. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; AppCore::ThrowIfFailed(d3dDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&cbvHeap))); cbvHeap->SetName(L"Constant Buffer View Descriptor Heap"); } CD3DX12_HEAP_PROPERTIES uploadHeapProperties(D3D12_HEAP_TYPE_UPLOAD); CD3DX12_RESOURCE_DESC constantBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(AppCore::c_frameCount * cBufferSize); AppCore::ThrowIfFailed(d3dDevice->CreateCommittedResource( &uploadHeapProperties, D3D12_HEAP_FLAG_NONE, &constantBufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constantBuffer))); constantBuffer->SetName(L"Text Color Constant Buffer"); // Create constant buffer views to access the upload buffer. D3D12_GPU_VIRTUAL_ADDRESS cbvGpuAddress = constantBuffer->GetGPUVirtualAddress(); CD3DX12_CPU_DESCRIPTOR_HANDLE cbvCpuHandle(cbvHeap->GetCPUDescriptorHandleForHeapStart()); cbvDescriptorSize = d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); for (int n = 0; n < AppCore::c_frameCount; n++) { D3D12_CONSTANT_BUFFER_VIEW_DESC desc; desc.BufferLocation = cbvGpuAddress; desc.SizeInBytes = cBufferSize; d3dDevice->CreateConstantBufferView(&desc, cbvCpuHandle); cbvGpuAddress += desc.SizeInBytes; cbvCpuHandle.Offset(cbvDescriptorSize); } // Map the constant buffer AppCore::ThrowIfFailed(constantBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mappedCBuffer))); ZeroMemory(mappedCBuffer, AppCore::c_frameCount * cBufferSize); }).then([&] { isReady = true; }); } AppCore::TextRenderer::~TextRenderer() { if (mappedCBuffer != nullptr) { constantBuffer->Unmap(0, nullptr); mappedCBuffer = nullptr; } } void AppCore::TextRenderer::Draw(const std::string& Text, const Math::Color& Color, float Size, const Math::Vector2& Position, const AppCore::BitmapFont& Font) { std::vector<Math::Vector3> vertices; int advance, lsb; float x = Position.x, y = Position.y; for (size_t i = 0; i < Text.length(); i++) { /*stbtt_GetCodepointHMetrics(Font, i, &advance, &lsb); x += (advance * scale); if (i + 1 != Text.length()) x += scale * stbtt_GetCodepointKernAdvance(Font, Text[i], Text[i + 1]);*/ } }
#include<iostream> using namespace std; int main() { cout<<"rishikesh"; cout<<"bioinformatics"; return 0; }
#include "BinarySearchTree.hpp" BinarySearchTree::BinarySearchTree() { this->root = NULL; } BinarySearchTree::~BinarySearchTree() { // TODO: メモリ解放: delete() } void BinarySearchTree::insert_node(int key) { // 挿入するノードの宣言と初期化 node_t *z = new node_t(); z->key = key; z->parent = NULL; z->left = NULL; z->right = NULL; // ノードの挿入 if (this->root == NULL) { this->root = z; } else { node_t *x; // 先を探索するノード node_t *y; // 探索前に保持しておくノード x = root; y = NULL; while (x != NULL) { // 探索前にのdーを保持 y = x; // 小さい場合は左に移動 if (key <= x->key) x = x->left; // 大きい場合は右に移動 else x = x->right; } // ノードの登録 if (key <= y->key) { y->left = z; z->parent = y; } else { y->right = z; z->parent = y; } } } bool BinarySearchTree::search_node(int key) { bool flag_existance = false; if (this->root == NULL) flag_existance = false; else { node_t *x = this->root; while (x != NULL) { // 一致するものがあれば終了 if (key == x->key) { flag_existance = true; break; } // なければ次のノードを探索 if (key <= x->key) x = x->left; else x = x->right; } } return flag_existance; } bool BinarySearchTree::delete_node(int key) { bool flag_deletion = false; if (this->root == NULL) flag_deletion = false; else { node_t *x = root; while (x != NULL) { // 消したいノードが見つかれば削除 if (x->key == key) { // ノード削除関数 this->_remove_node(x); flag_deletion = true; break; } // なければ次のノード探索 if (key <= x->key) x = x->left; else x = x->right; } } return flag_deletion; } void BinarySearchTree::_remove_node(node_t *z) { node_t *deletion_node = z; node_t *y; int deletion_key; while (deletion_node != NULL) { // 削除対象ノードの親ノードを保持 y = deletion_node->parent; deletion_key = deletion_node->key; // (1) 削除対象ノードがひとつも子を持っていないとき // -> そのまま削除 if (deletion_node->left == NULL && deletion_node->right == NULL) { // 削除対象がルートだったとき if (deletion_node == this->root) { this->root = NULL; } // 削除対象がルートでないとき else { if (deletion_key <= y->key) y->left = NULL; else y->right = NULL; } delete deletion_node; deletion_node = NULL; } // (2) 削除対象ノードの子がひとつでそれが左のとき else if (deletion_node->left != NULL && deletion_node->right == NULL) { // 削除対象がルートだったとき if (deletion_node == this->root) { this->root = deletion_node->left; } // 削除対象がルートでないとき else { // つなぎ変え (削除対象が親の左の子か右の子かで場合分け) if (deletion_key <= y->key) { y->left = deletion_node->left; deletion_node->left->parent = y; } else { y->right = deletion_node->left; deletion_node->left->parent = y; } } delete deletion_node; deletion_node = NULL; } // (2) 削除対象ノードの子がひとつでそれが右のとき else if (deletion_node->left == NULL && deletion_node->right != NULL) { if (deletion_node == this->root) { this->root = deletion_node->right; } else { // つなぎ変え (削除対象が親の左の子か右の子かで場合分け) if (deletion_key <= y->key) { y->left = deletion_node->right; deletion_node->right->parent = y; } else { y->right = deletion_node->right; deletion_node->right->parent = y; } } delete deletion_node; deletion_node = NULL; } // (3) 削除対象ノードが左右どちらにも子を持つとき else if (deletion_node->left != NULL && deletion_node->right != NULL) { // 削除対象の左部分木で最も大きいノードを探索する node_t *left_max_n, *n; n = deletion_node->left; while (n != NULL) { left_max_n = n; n = n->right; } deletion_node->key = left_max_n->key; deletion_node = left_max_n; } } } void BinarySearchTree::show_node() { // 昇順で値を表示(中間順) if (this->root == NULL) std::cout << "NULL" << std::endl; else { this->_show_inorder(this->root); std::cout << std::endl; } } void BinarySearchTree::_show_inorder(node_t *x) { if (x == NULL) return; this->_show_inorder(x->left); std::cout << x->key << " "; this->_show_inorder(x->right); }
/** * @file GaussianGenerator.h * @author F. Gratl * @date 7/31/18 */ #pragma once #include <random> #include "autopas/AutoPas.h" /** * Generator class for gaussian distributions */ class GaussianGenerator { public: /** * Fills any container (also AutoPas object) with randomly 3D gaussian distributed particles. * * @tparam Container Arbitrary container class that needs to support getBoxMax() and addParticle(). * @tparam Particle Type of the default particle. * @param autoPas * @param numParticles number of particles * @param defaultParticle inserted particle * @param distributionMean mean value / expected value * @param distributionStdDev standard deviation */ template <class Particle, class ParticleCell> static void fillWithParticles(autopas::AutoPas<Particle, ParticleCell> &autoPas, size_t numParticles, const Particle &defaultParticle = autopas::Particle(), double distributionMean = 5.0, double distributionStdDev = 2.0); }; template <class Particle, class ParticleCell> void GaussianGenerator::fillWithParticles(autopas::AutoPas<Particle, ParticleCell> &autoPas, size_t numParticles, const Particle &defaultParticle, double distributionMean, double distributionStdDev) { std::default_random_engine generator(42); std::normal_distribution<double> distribution(distributionMean, distributionStdDev); for (size_t id = 0; id < numParticles;) { std::array<double, 3> position = {distribution(generator), distribution(generator), distribution(generator)}; // only increment loop var (and place particle) if position is valid if (not autopas::utils::inBox(position, autoPas.getBoxMin(), autoPas.getBoxMax())) continue; Particle p(defaultParticle); p.setR(position); p.setID(id++); autoPas.addParticle(p); } }
#include <bits/stdc++.h> using namespace std; // Complete the flippingBits function below. long flippingBits(long n) { string s = bitset<32>(n).to_string(); for (int i=0; i<s.length(); i++) { if (s[i]=='0') s[i] = '1'; else s[i] = '0'; } bitset<32> s_casted(s); return s_casted.to_ulong(); } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { long n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); long result = flippingBits(n); fout << result << "\n"; } fout.close(); return 0; }
#ifndef EDAFOS_H #define EDAFOS_H #include "Planitis.h" #include <iostream> #include <cstdlib> #include <ctime> using std::cout; using std::endl; class Edafos:public Planitis{ public: Edafos(); //constructor Edafos // sinartiseis pliroforiwn kai simvolwn virtual void PrintInfo() const; virtual void PrintSymbol() const; // sinartiseis gia prospelasi kai tropopoihsh twn timwn twn stoixeiwn pou exei kathe antikeimeno edafus void setIridium(int); void setPlatinum(int); void setPalladium(int); inline int getIridium() const {return iridium;} inline int getPlatinum() const {return platinum;} inline int getPalladium() const {return palladium;} inline float getAccess() const {return access;} inline bool getDanger() const {return danger;} void setDanger(bool); // dilwsi metavlitwn edafus private: int iridium; int platinum; int palladium; int sumElements; float access; bool danger; }; //constructor edafos, dinei rand times se kathe antikeimeno edafus, me megisti periektikotita to 100. Episis dinei tixaia timi gia tin epikindinotita access kai orizei san true oles tis theseis edafus ( den exei simaia kindinou ) Edafos::Edafos() { iridium=rand()%60; platinum=rand()%(99-iridium); palladium=rand()%(99-iridium-platinum); sumElements=iridium+platinum+palladium; danger=true; access=static_cast<float>(rand()%10)/10; } //sunartisi PrintInfo(), ektupwnei pliroforia edafus void Edafos::PrintInfo() const { cout<<"\nEdw exoume stoixeio edafous me: \nSinoliki posotita stoixeiwn : "<<sumElements<< " monades\nIridio : "<<iridium<<" monades\nPlatinum: "<<platinum<<" monades\nPalladium: "<<palladium<<" monades"<<"\nEpikindinotita Prosvasis: "<<access<<"\nSimaia Kindinou: "<<danger<<"\t\t ( 1 = eukoli prosvasi, 0 = epikindini )"<<endl; } //sunartisi PrintSymbol(), xrisimopoieite gia tin eikoniki anaparastasi stoixiwn Edafous void Edafos::PrintSymbol() const { cout<<" "; } void Edafos::setIridium(int iridium){ this->iridium=iridium; sumElements=iridium+platinum+palladium; } void Edafos::setPlatinum(int platinum){ this->platinum=platinum; sumElements=iridium+platinum+palladium; } void Edafos::setPalladium(int palladium){ this->palladium=palladium; sumElements=iridium+platinum+palladium; } void Edafos::setDanger(bool danger) { this->danger=danger; } #endif
#include <math.h> #include <cstdlib> #include <time.h> #include <cstdio> #include <iostream> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/nonfree/nonfree.hpp" #include "cv.h" using namespace std; double M_pi = 3.1415926535; double M_1_Pi = 1.0 / M_pi; const int w=1366*3, h=768*3 , samps = 9; // #screen size IplImage *text1=cvLoadImage("Default_Bump.jpg",1); IplImage *text2=cvLoadImage("six_texture.jpg",1); CvScalar s; class Vec { public: double x, y, z; // position, also color (r,g,b) Vec operator+(const Vec &b) const{ return Vec(x+b.x,y+b.y,z+b.z); } Vec operator-(const Vec &b) const{ return Vec(x-b.x,y-b.y,z-b.z); } Vec operator*(double b)const { return Vec(x*b,y*b,z*b); } // cross product Vec operator%(const Vec&b) const{return Vec(y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x);} Vec(double x_=0, double y_=0, double z_=0){ x=x_; y=y_; z=z_; } Vec mult(const Vec &b) { return Vec(x*b.x,y*b.y,z*b.z); } Vec& norm(){ return *this = *this * (1/sqrt(x*x+y*y+z*z)); } //dot product double dot(const Vec &b) const { return x*b.x+y*b.y+z*b.z; } double len(){ return sqrt(x*x+y*y+z*z); } }; class Ray { public: Vec o;// position Vec d;// direction Ray(Vec o_ = Vec(), Vec d_ = Vec()) : o(o_), d(d_) {} }; class Camera { public: Vec focus;//focus point Vec dir;//gaze direction Vec dy; Vec dz;//to get the screen Camera(Vec o_, Vec d_) : focus(o_), dir(d_) // to determine dx and dy { dy.x = 0.0; dy.y = 0.16 / w; dy.z = 0.0; dz.x = 0.0; dz.y = 0; dz.z = 0.09 / h; } Ray pixel_dir(int pos_w, int pos_h)//return the direction of certain pixels d need to be norm(); { Vec d = dir*0.1 + dy * (pos_w - w / 2) + dz*(pos_h - h / 2); Vec f = focus; Ray r(f,d); return r; } }; double clamp(double x) { return x<0 ? 0 : x>1 ? 1 : x; } int toInt(double x) { //return int(pow(clamp(x),1/2.2)*255+.5); return (x > 1 ? 255 : (x < 0 ? 0 : int(255*x))); } enum Refl_t { DIFF, SPEC, REFR, TEXT1 ,TEXT2}; // material types, used in radiance() enum Shape{PLANE, SPHERE, CUBE, TETRA}; class Basic_obj { public: Vec pos; Vec color; Refl_t refl; Shape shape; virtual double intersect(const Ray &ray) const { return 0; } virtual Vec Normal_V(const Vec &intersect_p) const { return Vec(0,0,0); } }; class Sphere:public Basic_obj { public: double rad; // radius Sphere(double rad_, Vec p_, Vec c_, Refl_t refl_):rad(rad_) { pos = p_; color = c_; refl = refl_; shape = SPHERE; } double intersect(const Ray &ray) const { // returns distance, 0 if nohit Vec op = ray.o - pos; // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0 double t, eps = 1e-4; double b = op.dot(ray.d); double det = b*b - op.dot(op)+rad*rad; int num = 0; //cerr << "I'm alive" << endl; if (det<0) return 0; else det=sqrt(det); return (t=-b-det)>eps ? t : ((t=-b+det)>eps ? t : 0); } Vec Normal_V(const Vec& intersect_p) const { Vec N = (intersect_p-pos).norm(); return N; } }; class Plane:public Basic_obj { public: Vec N; // Normal Vector Plane(Vec N_, Vec p_, Vec c_, Refl_t refl_): N(N_) { pos = p_; color = c_; refl = refl_; shape = PLANE; } double intersect(const Ray& ray) const { double t, eps = 1e-4; Vec n = N; Vec p = pos; if(n.dot(ray.d) == 0) return 0; else t = (n.dot(p) - n.dot(ray.o)) / (n.dot(ray.d)); return (t > eps? t : 0); } Vec Normal_V(const Vec& intersect_p) const { Vec n = N; //cerr << n.x << ' ' << n.y << ' ' << n.z << endl; return n; } }; class Cube:public Basic_obj { public: Ray LWH; Ray side[6]; Cube(Ray LWH_, Vec p_, Vec c_, Refl_t refl_): LWH(LWH_) { pos = p_; color = c_; refl = refl_; shape = CUBE; //generate six related plane //front back side[0].o = pos + LWH.d * (LWH.o.x / 2.); side[0].d = LWH.d; side[1].o = pos - LWH.d * (LWH.o.x / 2.); side[1].d = LWH.d*-1; //up down side[2].o = pos + Vec(0,0,1) * (LWH.o.z / 2.); side[2].d = Vec(0,0,1); side[3].o = pos - Vec(0,0,1) * (LWH.o.z / 2.); side[3].d = Vec(0,0,-1); //left right side[4].o = pos + Vec(LWH.d.y*-1.0, LWH.d.x*+1.0) * (LWH.o.y / 2.0); side[4].d = Vec(LWH.d.y*-1.0, LWH.d.x*1.0,0); side[5].o = pos - Vec(LWH.d.y*-1.0, LWH.d.x*+1.0) * (LWH.o.y / 2.0); side[5].d = Vec(LWH.d.y*1.0, LWH.d.x*-1.0,0); } double intersect(const Ray& ray) const { double t[6], t_max[3], t_min[3], eps = 1e-4; for(int i = 0; i != 6; i+= 1) { Vec n = side[i].d, p = side[i].o; if(n.dot(ray.d) == 0) t[i] = 0; else t[i] = (n.dot(p) - n.dot(ray.o)) / (n.dot(ray.d)); } for(int i = 0; i != 3; i++) { t_max[i] = max(t[2*i],t[2*i+1]); t_min[i] = min(t[2*i],t[2*i+1]); if(t[2*i] < 0 & t[2*i +1] < 0) return 0; } double ttmax = min(min(t_max[0],t_max[1]),t_max[2]), ttmin = max(max(t_min[0],t_min[1]),t_min[2]); return (ttmax - ttmin > eps? ((ttmin > eps)? ttmin: 0) : 0); } Vec Normal_V(const Vec& intersect_p) const { Vec x = intersect_p; for(int i = 0; i != 6; i++) { Vec n = side[i].d; Vec p = side[i].o; if( x.dot(n) == p.dot(n) ) return n; } } }; class Tetrahedron: public Basic_obj { Vec Triangle(int which, const Ray& ray) const { //the 1st triangle use p234 Vec point[3]; int count = 0; for(int i = 0 ; i != 4; i++) if(i != which) point[count++] = p[i]; assert(count == 3); Vec S = point[0] - ray.o; Vec E1 = point[0] - point[1]; Vec E2 = point[0] - point[2]; return ( Vec( Det(S, E1, E2), Det(ray.d, S, E2), Det(ray.d, E1, S)) * (1.0 / Det(ray.d, E1 , E2) ) ); } double Det(Vec a, Vec b, Vec c) const { return( a.x*b.y*c.z + b.x*c.y*a.z + c.x*a.y*b.z - c.x*b.y*a.z - b.x*a.y*c.z - a.x*c.y*b.z); } Vec parse_normal(int which, const Vec& intersect_p) const { Vec point[3]; int count = 0; for(int i = 0 ; i != 4; i++) if(i != which) point[count++] = p[i]; assert(count == 3); Vec n = ((point[0] - point[1]) % (point[0] - point[2])).norm(); if( abs(point[0].dot(n) - intersect_p.dot(n)) < 1e-4) return n; else return Vec(); } public: Vec p[4]; // Normal Vector Tetrahedron(Ray p12, Ray p34, Vec c_, Refl_t refl_) { p[0] = p12.o; p[1] = p12.d; p[2] = p34.o; p[3] = p34.d; this->pos = (p[0] + p[1] + p[2] + p[3] ) * 0.25; color = c_; refl = refl_; shape = TETRA; } double intersect(const Ray& ray) const { double t[4], beta[4], gama[4], eps = 1e-4; double small_p = 1e20; for(int i = 0; i != 4; i++) { Vec ans = Triangle(i, ray); t[i] = ans.x; beta[i] = ans.y; gama[i] = ans.z; if(beta[i] >= 0 && beta[i] <= 1) if(gama[i] >= 0 && gama[i] <= 1) if(beta[i]+gama[i]<=1) if(t[i] >= eps && t[i] < small_p) small_p = t[i]; } return ((small_p < 1e20) ? small_p : 0); } Vec Normal_V(const Vec& intersect_p) const { Vec ans; Vec rt; for(int i = 0 ; i != 4; i++) { ans = parse_normal(i, intersect_p); if(ans.x != 0 || ans.y != 0 || ans.z != 0) rt = ans; } assert(rt.x != 0 || rt.y != 0 || rt.z != 0); return rt; } }; const int Up = 30, Right = 30, Front = 30; const int Down = -30, Left = -30, Back = -30; Vec Lights[] = { Vec (30.5,-0.5,9),Vec(30.25,-0.5,9), Vec (30,-0.5,9),Vec(29.75, -0.5, 9),Vec (29.5,-0.5,9), Vec (30.5,-0.25,9),Vec(30.25,-0.25,9), Vec (30,-0.25,9),Vec(29.75, -0.25, 9),Vec (29.5,-0.25,9), Vec (30.5,0,9), Vec(30.25,0,9),Vec (30,0,9),Vec(29.75, 0, 9),Vec (29.5,0,9), Vec (30.5,0.25,9),Vec(30.25,0.25,9), Vec (30,0.25,9),Vec(29.75, 0.25, 9),Vec (29.5,0.25,9), Vec (30.5,0.5,9), Vec(30.25,0.5,9),Vec (30,0.5,9),Vec(29.75, 0.5, 9), Vec (29.5,0.5,9) }; int things_num = 11; Basic_obj* things[] = { new Sphere(3.6, Vec(28, 4, -6.4), Vec(0.75,0.75,0.25), TEXT1), //new Sphere(3.2, Vec(25, 10, -3.8), Vec(0.75,0.75,0.25), TEXT1), new Plane(Vec(0,1,0), Vec(0,-15,0), Vec(0.88,0.53,0.53), DIFF), //Left new Plane(Vec(0,1,0), Vec(0,15,0),Vec(0.53,0.53,0.88), DIFF), // right new Plane(Vec(1,0,0), Vec(40,0,0),Vec(0.88,0.88,0.88), SPEC), // back new Plane(Vec(0,0,1), Vec(0,0,10),Vec(0.88,0.88,0.88), DIFF), // up new Plane(Vec(0,0,-1), Vec(0,0,-10),Vec(0.88,0.88,0.88), TEXT2),// down new Plane(Vec(1,0,0), Vec(-100,0,0),Vec(0,0,0), DIFF), // front new Sphere(5.5, Vec(30, 0, 15), Vec(30,30,30), DIFF),// the light new Sphere(3.5,Vec(29, -8, -6.5), Vec(0.99,0.99,0.99),REFR), // the REFR one new Cube(Ray(Vec(3,3,3),Vec(1,0,0).norm()),Vec(25,+10,-8.5),Vec(0.53,0.88,0.53), DIFF), //new Tetrahedron(Ray(Vec(31, -2, -10),Vec(23, -3.2, -10)),Ray(Vec(27,-4.2,-6.5), Vec(26.5, -6.5, -10)), Vec(.45,.15,.75), DIFF) new Tetrahedron(Ray(Vec(26, -1, -10),Vec(18, -2.2, -10)),Ray(Vec(22,-3.2,-5), Vec(21.5, -5.5, -10)), Vec(0.88,0.53,0.88), DIFF) }; bool intersect(const Ray &ray, double &t, int &id) { double d; double inf=t=1e20; for(int i = 0; i < things_num; i++) if((d= things[i]->intersect(ray)) && d<t) { t=d; id=i; } return t<inf; } Vec radiance(const Ray &ray){ //cout << "into radiance" << endl; double distance; // distance to intersection // id of intersected object int id = 0; if (!intersect(ray, distance, id)) { cout << "not intersect" << endl; return Vec(0,0,0); // if miss, return black } const Basic_obj* obj = things[id]; // the hit object Vec x = ray.o+ray.d*distance;//intercect point Vec V = Vec() - ray.d; Vec N = obj->Normal_V(x); if(V.dot(N) < 0) N = Vec() - N; Vec f = obj->color; //if(obj->shape == TETRA) // cout << "Tetra N" << N.x << ' ' << N.y << ' ' << N.z << endl; //cout << "after color" << endl; //cerr << (obj->refl == DIFF) << endl; if(obj->refl == DIFF || obj-> refl == TEXT1 || obj-> refl == TEXT2) // Ideal DIFFUSE reflection { //Phong model double Ii = 1; Vec Kd; if(obj->refl == DIFF) Kd = obj->color; else { double XX, YY; if(obj->shape == SPHERE) { Vec xo = (x - obj->pos); Vec No; No.x = xo.x; No.y=xo.y; No.z = 0; No = No.norm(); XX = acos( No.dot(Vec(1,0,0))) *M_1_Pi / 0.75; YY = asin( xo.z / xo.len()) * M_1_Pi / 0.75; } else if(obj->shape == PLANE) { XX = x.x/3; // /how many meters an image YY = x.y/3; } int SCALE = 1; int i = int ( 1.0*(XX - SCALE * (int(XX) / SCALE)) / SCALE *text1->height); int j = int ( 1.0*(YY - SCALE * (int(YY) / SCALE)) / SCALE *text1->width); if(obj->refl == TEXT1) { while(i < 0) i += text1->height; while(j < 0) j += text1->width; s=cvGet2D(text1,i,j); // get the (i,j) pixel value } else if(obj->refl == TEXT2) { while(i < 0) i += text2->height; while(j < 0) j += text2->width; s=cvGet2D(text2,i,j); // get the (i,j) pixel value } Kd.x = (double)s.val[0]/200.0 ; Kd.y = (double)s.val[1]/200.0 ; Kd.z = (double)s.val[2]/200.0 ; } Vec Ks = Kd * 0.2; Vec Ka = Kd * 0.43; //cout << L.x << ' '<< L.y << ' ' << L.z << endl; //cout << N.x << ' '<< N.y << ' ' << N.z << endl; //cout << L.dot(N) << endl; int Light_num=sizeof(Lights)/sizeof(Vec); Vec total; for(int i = 0; i != Light_num; i++) { Vec t1,t2,t3; Vec L = (Lights[i] - x).norm(); Vec R; if(L.dot(N) > 1e-4) { t1 = Kd*Ii*(pow(L.dot(N),2)); R = (N*2*(N.dot(L)) - L).norm();//否则R为0,不考虑下边的高光 } if(R.dot(V) > 1e-4) t2 = Ks*Ii*(pow(R.dot(V),20)); t3 = Ka* Ii; //shadows the part that is shadowed by other object double d; int id2; bool c = intersect( Ray(x, L), d, id2); if(d < (Lights[i] - x).len() ) { t1 = Vec(); t2 = Vec(); } total = total + (t1 + t2 + t3) * (1.0 / Light_num); } return total; } else if(obj->refl == SPEC)//Ideal SPECULAR reflection { Vec R_ofV = (N*2*(N.dot(V)) - V).norm(); return f.mult(radiance(Ray(x, R_ofV))); } else if(obj->refl == REFR)//Ideal dielectric REFRACTION { Vec n = obj->Normal_V(x); Vec nl = (N.dot(ray.d) < 0) ? N:(Vec()-N); bool into = N.dot(nl)>0; // Ray from outside going in? double nnt = (into?1.0/1.5:1.5); double ddn= nl.dot(ray.d); double cos2t; Ray reflRay(x, ray.d-n*2*n.dot(ray.d)); if ((cos2t=1-nnt*nnt*(1-ddn*ddn))<0) // Total internal reflection return f.mult(radiance(reflRay)); Vec tdir = (ray.d*nnt - n*((into?1:-1)*(ddn*nnt+sqrt(cos2t)))).norm(); double a=1.5 - 1, b=1.5 + 1; double R0=a*a/(b*b), c = 1-(into?-ddn:tdir.dot(n)); double Re=R0+(1-R0)*c*c*c*c*c,Tr=1-Re,P=.25+.5*Re,RP=Re/P,TP=Tr/(1-P); //if((double)rand() / (double)RAND_MAX > 0.2) // return f.mult(radiance(reflRay)*Re+radiance(Ray(x,tdir))*Tr); //else return f.mult(radiance(Ray(x,tdir))); } } int main(){ freopen("ans.txt","w",stdout); cout << "start" << endl; Camera cam(Vec(-5,0,0),Vec(1,0,0)); //w=1366, h=768 unsigned srand(time(NULL)); Vec** screen; screen = new Vec*[w]; for(int i = 0; i != w; i++) screen[i] = new Vec[h]; Vec r; for (int y=0; y < h; y++) { fprintf(stderr,"\rRendering %5.2f%%", 100.* y /(h - 1)); for (int x=0; x < w; x++) // Loop cols { int n = sqrt(samps); for (int zz = 0; zz != n; zz++) for(int yy = 0; yy != n; yy++) { r = Vec(); Vec dir = (cam.pixel_dir(x,y).d + cam.dy * (-0.5+0.5/ n + yy / n) + cam.dz * (-0.5+0.5/ n + zz / n)).norm(); r = r + radiance(Ray(cam.focus, dir)); screen[x][y] = screen[x][y]+ r * (1.0 / samps); } } } cout << "draw_pixel done" << endl; Ray ray(Vec(0,0,0),Vec(1,0,0)); double distance; int id; bool a = intersect(ray, distance, id); FILE *f = fopen("cube.ppm", "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for(int y = h - 1; y >= 0; y--) for(int x = 0; x < w; x++) fprintf(f,"%d %d %d ", toInt(screen[x][y].x), toInt(screen[x][y].y), toInt(screen[x][y].z)); return 0; }
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int edges; cin>>edges; int arr[n]; int adj[n][n]; for(int i=0;i<n;i++) { arr[i]=0; for(int j=0;j<n;j++) { adj[i][j]=0; } } int src; cin>>src; for(int i=0;i<edges;i++) { int x; int y; cin>>x; cin>>y; adj[x][y]=1; } stack<int> st; st.push(src);//JUST NEED TO ADD 1 MORE LOOP FOR COMING UP WITH MOTHER VERTEX;-->0(N^3) cout<<st.top(); while(st.size()!=0) { int c=0; for(int i=0;i<n;i++) { if(adj[st.top()][i]==1&&arr[i]==0) { st.push(i); arr[i]=1; c=1; break; } } if(c==0) { st.pop(); } else { cout<<st.top(); } } }
class Solution { public: bool increasingTriplet(vector<int>& nums) { if(nums.empty()) return false; int n = nums.size(); if(n < 3) return false; int large = INT_MAX; int small = nums[0]; for(int i = 1; i < nums.size(); i++) { if(nums[i] > large) return true; else if(nums[i] > small && nums[i] < large) { large = nums[i]; } else if(nums[i] < small) { small = nums[i]; } } return false; } };
#include <Arduino.h> #include "AccelStepper.h" #include "MultiStepper.h" #include "axisDirectionStruct.h" //importing AxisAndDirection #define STEPPER_X_STEP_PIN 2 #define STEPPER_X_DIR_PIN 3 #define STEPPER_Z_STEP_PIN 6 #define STEPPER_Z_DIR_PIN 7 #define STEPPER_Y_STEP_PIN 9 #define STEPPER_Y_DIR_PIN 10 #define led_pin 13 enum Direction { FORWARD, BACKWORD } direction; String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete void blockingRunSpeedToPosition(int direction, String axis); AccelStepper stepperX(AccelStepper::DRIVER, STEPPER_X_STEP_PIN, STEPPER_X_DIR_PIN); AccelStepper stepperY(AccelStepper::DRIVER, STEPPER_Y_STEP_PIN, STEPPER_Y_DIR_PIN); AccelStepper stepperZ(AccelStepper::DRIVER, STEPPER_Z_STEP_PIN, STEPPER_Z_DIR_PIN); MultiStepper steppers; void setup() { Serial.begin(9600); pinMode(led_pin, OUTPUT); stepperX.setMaxSpeed(200.0); stepperX.setAcceleration(100); stepperY.setMaxSpeed(200.0); stepperY.setAcceleration(100); stepperZ.setMaxSpeed(200.0); stepperZ.setAcceleration(100); steppers.addStepper(stepperY); steppers.addStepper(stepperZ); } void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // clear the string: inputString.trim(); Serial.println(inputString.length()); if(inputString == "x") { direction = FORWARD; blockingRunSpeedToPosition(direction,"x"); } else if (inputString == "-x") { direction = BACKWORD; blockingRunSpeedToPosition(direction,"x"); } else if (inputString =="y") { direction = FORWARD; blockingRunSpeedToPosition(direction,"y"); } else if (inputString == "-y") { direction = BACKWORD; blockingRunSpeedToPosition(direction, "y"); } else if(inputString == "z"){ direction = FORWARD; blockingRunSpeedToPosition(direction, "z"); }else if (inputString == "-z") { direction = BACKWORD; blockingRunSpeedToPosition(direction, "z"); } inputString = ""; stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } } void blockingRunSpeedToPosition(int direction, String axis) { /* runSpeedToPosition is non blocking. You must call this as frequently as possible, but at least once per step interval, But we want blocking so we have to implement own loop using while */ Serial.println("got "+axis); int steps = 1600; if(direction == BACKWORD) { steps = -steps; } ///stepper.move funtion : Set the target position relative to the current position /// if position is negative then anticlockwise from the current position, else clockwise from current position if(axis.equals("x")){ stepperX.setCurrentPosition(0); stepperX.move(steps); while (stepperX.distanceToGo() != 0) { stepperX.run(); } }else if (axis.equals("y")) { long positions[2]; positions[0]=steps; positions[1]=steps; stepperY.setCurrentPosition(0); stepperZ.setCurrentPosition(0); steppers.moveTo(positions); // while (stepperY.distanceToGo()!=0 && stepperZ.distanceToGo()!=0) { // steppers.run(); // } steppers.runSpeedToPosition(); }else if (axis.equals("z")) { long positions[2]; positions[0]=steps; positions[1]=-steps; stepperY.setCurrentPosition(0); stepperZ.setCurrentPosition(0); steppers.moveTo(positions); steppers.runSpeedToPosition(); // while (stepperY.distanceToGo()!=0 && stepperZ.distanceToGo()!=0) { // steppers.run(); // } } }
#include "componentfactory.h" #include "arrowitem.h" #include "lineitem.h" #include "grawitem.h" #include "circleitem.h" #include "rectangletextitem.h" #include "elements/polylineitem.h" #include "elements/graphnode.h" #include "elements/twogtext.h" #include "elements/svgitem.h" #include "rectangleitem.h" // В GrawItem можна зберігати ComponentType як айді //і тоді ці статік касти будуть не потрібні. GrawItem *ComponentFactory::createComponent(ComponentType type) { switch (type) { case ComponentType::Arrow: return new ArrowItem(static_cast<int>(type)); case ComponentType::Line: return new LineItem(static_cast<int>(type)); case ComponentType::Circle: return new CircleItem(static_cast<int>(type)); case ComponentType::RectangleText: return new RectangleTextItem(static_cast<int>(type)); case ComponentType::Polyline: return new PolylineItem(static_cast<int>(type)); case ComponentType::GraphNode: return new GraphNode(static_cast<int>(type)); case ComponentType::TwoText: return new Twogtext(static_cast<int>(type)); case ComponentType::SvgItem: return new SvgItem(static_cast<int>(type)); case ComponentType::Rectangle: return new RectangleItem(static_cast<int>(type)); default: return nullptr; } } GrawItem *ComponentFactory::createComponent(int id) { return createComponent(static_cast<ComponentType>(id)); }
#include <iostream> #include "interpreter.hpp" #include <fstream> using std::cout; using std::cin; int main(int argc, char*argv[]) { int Output; Expression Error("Error"); if (argc == 1) { Interpreter Interp; std::string input; Expression output; while (1) { cout << "vtscript> "; getline(cin, input); std::istringstream TokenStream(input); Interp.parse(TokenStream); try { output = Interp.eval(); if (output.Node.type == Bool) if(output.Node.bool_value) cout << "(True)" << std::endl; else cout << "(False)" << std::endl; else if (output.Node.type == Value) cout << "(" << output.Node.double_value << ")" << std::endl; } catch (InterpreterSemanticError & ERR) { output = Error; cout << "Error" << std::endl; Interp.resetEnviro(); } Output = EXIT_SUCCESS; } } else if (argc == 3) { std::string input = argv[2]; Interpreter Interp; Expression output; std::istringstream TokenStream(input); Interp.parse(TokenStream); try { output = Interp.eval(); } catch (InterpreterSemanticError & ERR) { cout << "Error" << std::endl; Output = EXIT_FAILURE; return Output; } if (output.Node.type == Bool) cout << "(" << output.Node.bool_value << ")" << std::endl; else if (output.Node.type == Value) cout << "(" << output.Node.double_value << ")" << std::endl; Output = EXIT_SUCCESS; } else if(argc == 2) { std::ifstream in(argv[1]); if (!in.is_open()) { cout << "Error" << std::endl; Output = EXIT_FAILURE; } else { Interpreter Interp; Expression output; Interp.parse(in); try { output = Interp.eval(); } catch (InterpreterSemanticError & ERR) { cout << "Error" << std::endl; Output = EXIT_FAILURE; } if (output.Node.type == Bool) cout << "(" << output.Node.bool_value << ")" << std::endl; else if (output.Node.type == Value) cout << "(" << output.Node.double_value << ")" << std::endl; Output = EXIT_SUCCESS; in.close(); } } return Output; }
// <algorithm> includes the various algorithms #include<iostream> #include<algorithm> using namespace std; // This is for calculating the GCD of two numbers using the in-built function // EUCLID'S GCD Algorithm // Complexity - O(log2n) ( log2n -> log(n) to the base 2 ), n - upper limit of (a,b) // For details - https://www.quora.com/What-is-the-time-complexity-of-Euclids-GCD-algorithm int main() { int a,b; cin>>a>>b; cout<<__gcd(a,b); return 0; }
/* * Multiple MAX7221 can be chained. !CS must be kept low while clocking all bytes through, LEDs are set when !CS goes high. * * I assume we can send data to a device down the line without affecting the earlier ones if we just send 0-bytes to push the * "real" one. * * Clock does not run when !CS is high, hopefully this makes it possible to have multiple chains on the same SPI bus. * * HW connections: * Cols on the LED dial equals digit on the MAX7221 * Rows on the LED dial equals segments on the MAX7221. DP is col0, G is col7. * NB: bit7 = DP and bit0 = G when sending data. */ #include <LedControl.h> int DIN = 12; int CS = 11; int CLK = 10; LedControl lc=LedControl(DIN,CLK,CS,1); int wait = 25; int repeats = 0; void setup(){ Serial.begin(9600); lc.shutdown(0,false); //The MAX72XX is in power-saving mode on startup lc.setIntensity(0,15); // Set the brightness to maximum value lc.clearDisplay(0); // and clear the display*/ } /* * Leds are wired slightly weird. They must be adressed in this order (led num from left to right on ring): * 0-3: row0 -> col0-3 * 4-7: row1 -> col0-3 * 8-11: row2 -> col0-3 * 12-15: row3 -> col0-3 * 16-19: row3 -> col4-7 * 20-23: row2 -> col4-7 * 24-27: row1 -> col4-7 * 28-31: row0 -> col4-7 * * But cols are addressed in reverse order, col0 is bit7, col7 is bit0, so bits must be sent as: * 0-3: row0 -> bit7-4 * 4-7: row1 -> bit7-4 * 8-11: row2 -> bit7-4 * 12-15: row3 -> bit7-4 * 16-19: row3 -> bit3-0 * 20-23: row2 -> bit3-0 * 24-27: row1 -> bit3-0 * 28-31: row0 -> bit3-0 * * By reversing the input bit string we don't have to do any reversal internally: * 0-3 = bs31-28: row0 -> bit7-4 * 4-7 = bs27-24: row1 -> bit7-4 * 8-11 = bs23-20: row2 -> bit7-4 * 12-15 = bs19-16: row3 -> bit7-4 * 16-19 = bs15-12: row3 -> bit3-0 * 20-23 = bs11-8: row2 -> bit3-0 * 24-27 = bs7-4: row1 -> bit3-0 * 28-31 = bs3-0: row0 -> bit3-0 * * By splitting bs into four bytes b3,b2,b1,b0 we get: * 0-3 = b3 hi: row0 -> bit7-4 * 4-7 = b3 lo: row1 -> bit7-4 * 8-11 = b2 hi: row2 -> bit7-4 * 12-15 = b2 lo: row3 -> bit7-4 * 16-19 = b1 hi: row3 -> bit3-0 * 20-23 = b1 lo: row2 -> bit3-0 * 24-27 = b0 hi: row1 -> bit3-0 * 28-31 = b0 lo: row0 -> bit3-0 * * Finally, ordered by row: * 0-3 = b3 hi: row0 -> bit7-4 * 28-31 = b0 lo: row0 -> bit3-0 * 4-7 = b3 lo: row1 -> bit7-4 * 24-27 = b0 hi: row1 -> bit3-0 * 8-11 = b2 hi: row2 -> bit7-4 * 20-23 = b1 lo: row2 -> bit3-0 * 12-15 = b2 lo: row3 -> bit7-4 * 16-19 = b1 hi: row3 -> bit3-0 */ void setLeds(short address, long leds, bool status){ // NB: leds are in reverse order, b31 = led1. byte bytes[4]; bytes[0] = leds; bytes[1] = leds >> 8; bytes[2] = leds >> 16; bytes[3] = leds >> 24; byte row0 = (bytes[0] & 0b00001111 ) | (bytes[3] & 0b11110000); byte row1 = (bytes[0] >> 4) | ((bytes[3] << 4) & 0b11110000); byte row2 = (bytes[1] & 0b00001111 ) | (bytes[2] & 0b11110000); byte row3 = (bytes[1] >> 4) | ((bytes[2] << 4) & 0b11110000); lc.setRow(address, 0, row0); lc.setRow(address, 1, row1); lc.setRow(address, 2, row2); lc.setRow(address, 3, row3); } void setLedAtIndex(short address, short index, bool status){ int row, col; if(index < 16){ col = index % 4; row = index / 4; } else { col = 4 + (index % 4); row = 3 - ((index - 16)/ 4); } lc.setLed(address, row, col, status); } void setWiper(short address, short index, bool status, bool allOn){ int row, col; lc.clearDisplay(0); if(allOn){ // Fill all led positions up to index with 1 // NB: The MAX7221 is MSB = lowest col, so the bit string is reversed. // I'm using a little trick here: By letting long be a SIGNED variable, // and filling it with a 1 in the MSB, right shifting will extend the 1 to // all the places we want filled by a single shift command :) long leds=0x80000000; // first 1, rest 0 leds = leds >> index; setLeds(address, leds, status); } else { setLedAtIndex(address, index, status); } } void loop(){ byte all[8]; byte scroll = 0b00000001; for(int index=0; index < 32; index++){ setWiper(0, index, true, true); delay(wait); } }
#include "code_generator.h" #include "html.h" #include "html_print.h" #include "css_print.h" #include "file.h" HTML_Element* compileLayout(Compiler* compiler, AST_Layout* layout, CompilerParameters* properties = NULL); CompilerValue evaluateExpression(Compiler* compiler, AST_Expression* expression); inline AST_ComponentDefinition* findComponentDefinition(Compiler* compiler, String name) { TemporaryPoolScope tempPool(compiler->poolTransient); Array<AST_ComponentDefinition*> definitions(256, tempPool); for (s32 i = 0; i < compiler->astFiles->used; ++i) { AST_File* ast_file = &compiler->astFiles->data[i]; if (ast_file->components != NULL) { for (s32 j = 0; j < ast_file->components->used; ++j) { AST_ComponentDefinition* definition = &ast_file->components->data[j]; if (name.cmp(definition->name)) { definitions.push(definition); } } } } if (definitions.used > 0) { if (definitions.used == 1) { AST_ComponentDefinition* definition = definitions.data[0]; return definition; } else { compiler->hasError = true; // Detect multiple definitions error compileError("Multiple definitions of '%s' found.", &name); for (s32 i = 0; i < definitions.used; ++i) { AST_ComponentDefinition* definition = definitions.data[i]; String basename = definition->name.pathName.basename(); compileErrorSub("Definition #%d found on Line %d on file '%s'.", i, definition->name.lineNumber, &basename); compileErrorSubSub("(%s)", &definition->name.pathName); } } } return NULL; } CompilerValue evaluateIdentifier(Compiler* compiler, Token identifierName, AST_Expression* context) { assert(context != NULL); assert(context->parent != NULL); if (identifierName.isBackend()) { // Handled in other codepath in evaluateExpression(), // if its needed here again, move the code back here. assert(false); } if (compiler->stack->used > 0) { CompilerParameters* stackParameters = compiler->stack->top(); if (stackParameters != NULL) { assert(stackParameters->names != NULL && stackParameters->names->used > 0); assert(stackParameters->names->used == stackParameters->values->used); s32 findIndex = stackParameters->names->find(identifierName); if (findIndex != -1) { CompilerValue result = stackParameters->values->data[findIndex]; return result; } /*for (s32 i = 0; i < stackParameters->names->used; ++i) { Token name = stackParameters->names->data[i]; if (name.cmp(identifierName)) { CompilerValue result = stackParameters->values->data[i]; return result; } }*/ } } AST* current = context; while (current = current->parent) { switch (current->type) { case AST_COMPONENTDEFINITION: { // NOTE(Jake): Component 'properties' are now added to compiler->stack, this isnt necessary for the // time being. (2016-03-21) // /*AST_ComponentDefinition* definition = (AST_ComponentDefinition*)current; assert(definition != NULL); if (definition->properties != NULL && definition->properties->names != NULL && definition->properties->values != NULL) { Array<Token>* names = definition->properties->names; for (s32 i = 0; i < names->used; ++i) { Token name = names->data[i]; if (name.cmp(identifierName)) { AST_Expression* expr = definition->properties->values->data[i]; assert(expr != NULL); CompilerValue result = evaluateExpression(compiler, expr); return result; } } }*/ } break; case AST_LAYOUT: // todo(Jake): Get variables from this scope break; case AST_PARAMETERS: case AST_IF: case AST_TAG: // no-op break; default: { assert(false); } break; } } // DEBUG TOOL: Immediately know where to code identifier issues //compileError("Unable to find variable \"%s\"", &identifierName); assert(false); CompilerValue nullResult; zeroMemory(&nullResult, sizeof(nullResult)); compiler->hasError = true; compileError("Unable to find identifier '%s'.", &identifierName); return nullResult; } CompilerValue compute(Compiler* compiler, CompilerValue lval, CompilerValue rval, AST_Expression_Token op) { CompilerValue nullResult; zeroMemory(&nullResult, sizeof(nullResult)); if ((lval.type == COMPILER_VALUE_TYPE_STRING && rval.type == COMPILER_VALUE_TYPE_STRING)) { assert(false); return nullResult; } CompilerValue result = {}; switch (lval.type) { case COMPILER_VALUE_TYPE_DOUBLE: { result.type = COMPILER_VALUE_TYPE_DOUBLE; f64& resultVal = result.valueDouble; if (rval.type == lval.type) { f64 lreal = lval.valueDouble; f64 rreal = rval.valueDouble; switch (op.name.type) { case TOKEN_PLUS: {resultVal = lreal + rreal; } break; case TOKEN_MULTIPLY: {resultVal = lreal * rreal; } break; case TOKEN_COND_AND: {resultVal = lreal && rreal; } break; case TOKEN_COND_OR: { resultVal = lreal || rreal; } break; default: { assert(false); } break; } } else { s8 numberEvaluatesTrue = -1; s8 stringEvaluatesTrue = -1; switch (lval.type) { case COMPILER_VALUE_TYPE_DOUBLE: { numberEvaluatesTrue = (lval.valueDouble != 0); } break; case COMPILER_VALUE_TYPE_STRING: { stringEvaluatesTrue = (lval.valueString.length != 0); } break; default: { assert(false); } break; } switch (rval.type) { case COMPILER_VALUE_TYPE_DOUBLE: { numberEvaluatesTrue = (rval.valueDouble != 0); } break; case COMPILER_VALUE_TYPE_STRING: { stringEvaluatesTrue = (rval.valueString.length != 0); } break; default: { assert(false); } break; } assert(numberEvaluatesTrue != -1 && stringEvaluatesTrue != -1); switch (op.name.type) { // Comparing different types conditionally like so: // - if ("myString" && 120) -- returns true // - if ("" && 120) -- returns false, as an empty string returns false. case TOKEN_COND_AND: { resultVal = numberEvaluatesTrue && stringEvaluatesTrue; } break; case TOKEN_COND_OR: { resultVal = numberEvaluatesTrue || stringEvaluatesTrue; } break; // Error cases // - You cannot add/subtract/mult/divide/etc a string and a number case TOKEN_PLUS: { compileError("Cannot add a string and number together on Line %d", op.name.lineNumber); assert(false); } break; default: { compileError("Attempted to modify two different data types together on Line %d", op.name.lineNumber); assert(false); } break; } } } break; default: { assert(false); } break; } assert(result.type != COMPILER_VALUE_TYPE_UNKNOWN); return result; } CompilerValue evaluateExpression(Compiler* compiler, AST_Expression* expression) { assert(expression != NULL); assert(expression->tokens != NULL); assert(expression->tokens->used > 0); TemporaryPoolScope tempPool(compiler->poolTransient); // CompilerValue nullResult; zeroMemory(&nullResult, sizeof(nullResult)); // Used for storing values until an operator is found, then right and left values are popped and // operated on with +, /, *, -. Array<CompilerValue> stack(expression->tokens->used, tempPool); // Get strings count used in expression s32 stringEstimateCount = 0; bool allocatedStringBuilder = false; for (s32 i = 0; i < expression->tokens->used; ++i) { AST_Expression_Token it = expression->tokens->data[i]; stringEstimateCount += (int)(it.name.type == TOKEN_STRING || it.name.type == TOKEN_IDENTIFIER); } // Stores raw values as their processed in the expression Array<CompilerValue> tempBackendValues(255, tempPool); s32 tokenIndex; for (tokenIndex = 0; tokenIndex < expression->tokens->used; ++tokenIndex) { AST_Expression_Token it = expression->tokens->data[tokenIndex]; Token token = it.name; if (token.isOperator()) { if (stack.used == 0) { compileError("Operator \"%s\" found at end of statement, no number or identifier after it at Line %d.", &token, token.lineNumber); return nullResult; } CompilerValue rval = stack.pop(); if (stack.used == 0) { if (tempBackendValues.used == 0) { assert(false); } CompilerValue op; zeroMemory(&op, sizeof(op)); op.type = COMPILER_VALUE_TYPE_BACKEND_OPERATOR; op.valueToken.name = token; tempBackendValues.push(rval); tempBackendValues.push(op); continue; } CompilerValue lval = stack.pop(); if (lval.type == COMPILER_VALUE_TYPE_BACKEND_IDENTIFIER || rval.type == COMPILER_VALUE_TYPE_BACKEND_IDENTIFIER || lval.type == COMPILER_VALUE_TYPE_BACKEND_EXPRESSION || rval.type == COMPILER_VALUE_TYPE_BACKEND_EXPRESSION) { CompilerValue op; zeroMemory(&op, sizeof(op)); op.type = COMPILER_VALUE_TYPE_BACKEND_OPERATOR; op.valueToken.name = token; tempBackendValues.push(lval); tempBackendValues.push(rval); tempBackendValues.push(op); } else if (lval.type == COMPILER_VALUE_TYPE_STRING || lval.type == COMPILER_VALUE_TYPE_STRING_BUILDER) { assert(lval.valueStringBuilder != NULL); if (rval.type != COMPILER_VALUE_TYPE_STRING && rval.type != COMPILER_VALUE_TYPE_STRING_BUILDER) { compileError("Cannot compare string to numeric on Line %d", token.lineNumber); assert(false); } // Convert string to string builder if (lval.type == COMPILER_VALUE_TYPE_STRING && it.name.type == TOKEN_PLUS) { String str = lval.valueString; lval.type = COMPILER_VALUE_TYPE_STRING_BUILDER; lval.valueStringBuilder = StringBuilder::create(stringEstimateCount, tempPool); lval.valueStringBuilder->add(str); } CompilerValue result = lval; String rstr; if (rval.type == COMPILER_VALUE_TYPE_STRING) { rstr = rval.valueString; } else if (rval.type == COMPILER_VALUE_TYPE_STRING_BUILDER) { rstr = rval.valueStringBuilder->toString(tempPool); } else { assert(false); } switch (it.name.type) { case TOKEN_PLUS: { assert(result.type == COMPILER_VALUE_TYPE_STRING_BUILDER); result.valueStringBuilder->add(rstr); } break; case TOKEN_COND_EQUAL: { s8 isTrue = -1; if (result.type == COMPILER_VALUE_TYPE_STRING_BUILDER) { if (result.valueStringBuilder->totalLength != rstr.length) { isTrue = false; } else { TemporaryPoolScope tempStrPool(compiler->pool); String lcurrVal = result.valueStringBuilder->toString(tempStrPool); isTrue = lcurrVal.cmp(rstr); } } else if (result.type == COMPILER_VALUE_TYPE_STRING) { isTrue = result.valueString.cmp(rstr); } else { assert(false); } assert(isTrue != -1); result.type = COMPILER_VALUE_TYPE_DOUBLE; result.valueDouble = isTrue; } break; default: { assert(false); } break; } stack.push(result); } else { assert(rval.type != COMPILER_VALUE_TYPE_STRING_BUILDER); CompilerValue result = compute(compiler, lval, rval, it); stack.push(result); } } else { // Determine the identifier if (token.type == TOKEN_IDENTIFIER) { if (token.isBackend()) { CompilerValue backendResult; zeroMemory(&backendResult, sizeof(backendResult)); backendResult.type = COMPILER_VALUE_TYPE_BACKEND_IDENTIFIER; backendResult.valueToken = it; backendResult.valueToken.name.data += 1; backendResult.valueToken.name.length -= 1; stack.push(backendResult); } else if (it.isFunction == false) { CompilerValue newValue = evaluateIdentifier(compiler, token, expression); if (compiler->hasError) { assert(false); } stack.push(newValue); } else { assert(false); } } else if (token.type == TOKEN_NUMBER) { CompilerValue newValue = {}; newValue.type = COMPILER_VALUE_TYPE_DOUBLE; newValue.valueDouble = token.toDouble(); stack.push(newValue); } else if (token.type == TOKEN_STRING) { CompilerValue newValue = {}; newValue.type = COMPILER_VALUE_TYPE_STRING; newValue.valueString = token; stack.push(newValue); } else { assert(false); } } } // If one identifier and its backend based, coerce into to backend expression. if (stack.used == 1 && stack.top().type == COMPILER_VALUE_TYPE_BACKEND_IDENTIFIER) { tempBackendValues.push(stack.pop()); } // If using any backend identifiers, return it as a backend expression. if (tempBackendValues.used > 0) { if (stack.used > 0) { compileError("Invalid items in backend expression"); for (s32 i = 0; i < stack.used; ++i) { //compileErrorSub(stack.data[i]); } return nullResult; } CompilerValue result; zeroMemory(&result, sizeof(result)); result.type = COMPILER_VALUE_TYPE_BACKEND_EXPRESSION; result.valueExpression = tempBackendValues.createCopyShrinkToFit(compiler->pool); return result; } // Expression should only have one value left, the result. // NOTE(Jake): This is subject to change with 'backend expressions' assert(stack.used == 1); CompilerValue result = stack.pop(); if (result.type == COMPILER_VALUE_TYPE_STRING_BUILDER) { assert(result.valueStringBuilder->used == result.valueStringBuilder->size); String str = result.valueStringBuilder->toString(compiler->pool); result.type = COMPILER_VALUE_TYPE_STRING; result.valueString = str; } assert(result.type != COMPILER_VALUE_TYPE_STRING_BUILDER); return result; } CompilerParameters* evaluateParameters(Compiler* compiler, AST_Parameters* parameters) { assert(parameters != NULL); CompilerParameters* result = pushStruct(CompilerParameters, compiler->pool); result->names = parameters->names; result->values = Array<CompilerValue>::create(parameters->values->used, compiler->pool); for (s32 i = 0; i < parameters->values->used; ++i) { AST_Expression* it = parameters->values->data[i]; assert(it->tokens != NULL); CompilerValue value = evaluateExpression(compiler, it); result->values->push(value); } return result; } void evaluateParametersAndModifyExistingParameters(Compiler* compiler, AST_Parameters* parameters, CompilerParameters* existingParameters) { assert(existingParameters != NULL); if (parameters == NULL) { return; } for (s32 i = 0; i < parameters->names->used; ++i) { Token& it = parameters->names->data[i]; s32 findIndex = existingParameters->names->find(it); if (findIndex != -1) { // If found property AST_Expression* expression = parameters->values->data[i]; existingParameters->values->data[findIndex] = evaluateExpression(compiler, expression); } else { // If haven't found property AST* parentLoose = parameters->parent; compiler->hasError = true; switch (parentLoose->type) { case AST_COMPONENT: { AST_Identifier* parent = (AST_Identifier*)parentLoose; compileError("Unable to override property '%s' in component '%s' on Line %d as it does not exist.", &it, &parent->definition->name, it.lineNumber); assert(false); } break; default: assert(false); break; } } /*bool foundProperty = false; for (s32 j = 0; j < existingParameters->names->used; ++j) { Token& innerIt = existingParameters->names->data[j]; if (it.cmp(innerIt)) { AST_Expression* expression = parameters->values->data[i]; existingParameters->values->data[j] = evaluateExpression(compiler, expression); foundProperty = true; break; } } if (!foundProperty) { AST* parentLoose = parameters->parent; compiler->hasError = true; switch (parentLoose->type) { case AST_COMPONENT: { AST_Identifier* parent = (AST_Identifier*)parentLoose; compileError("Unable to override property '%s' in component '%s' on Line %d as it does not exist.", &it, &parent->definition->name, it.lineNumber); assert(false); } break; default: assert(false); break; } }*/ } } inline HTML_Element* compileLayout(Compiler* compiler, AST_Layout* layout, CompilerParameters* parameters) { assert(layout != NULL); TemporaryPoolScope tempPool(compiler->poolTransient); Array<AST*> stack(256, tempPool); for (s32 i = layout->childNodes->used - 1; i >= 0; --i) { stack.push(layout->childNodes->data[i]); } // // Setup variables in this scope // CompilerParameters* variableStack = NULL; if ((layout->variables != NULL && layout->variables->used > 0) || (parameters != NULL && parameters->values->used > 0)) { s32 variableCount = 0; if (layout->variables != NULL) { variableCount += layout->variables->used; } if (parameters != NULL) { assert(parameters->names->used == parameters->values->used); variableCount += parameters->values->used; } variableStack = pushStruct(CompilerParameters, tempPool); variableStack->names = Array<Token>::create(variableCount, tempPool._allocator); variableStack->values = Array<CompilerValue>::create(variableCount, tempPool._allocator); compiler->stack->push(variableStack); if (layout->variables == NULL) { // If no statements in this 'layout' block then simply // add passed in parameters for the component identifier. for (s32 i = 0; i < parameters->names->used; ++i) { variableStack->names->push(parameters->names->data[i]); variableStack->values->push(parameters->values->data[i]); } } else { CompilerValue undefValue = {}; undefValue.type = COMPILER_VALUE_TYPE_UNDEFINED; // Setup the variables in scope (based off AST_STATEMENT count) for (s32 i = 0; i < layout->variables->used; ++i) { variableStack->names->push(layout->variables->data[i]); variableStack->values->push(undefValue); } if (parameters != NULL && parameters->names->used > 0) { // Override the variables in scope initial value with the passed in // component properties. If they don't exist as an AST_STATEMENT then // just simply add them in. for (s32 i = 0; i < parameters->names->used; ++i) { Token& name = parameters->names->data[i]; for (s32 j = 0; j < variableStack->names->used; ++j) { if (name.cmp(variableStack->names->data[j])) { variableStack->values->data[j] = parameters->values->data[i]; continue; } } variableStack->names->push(name); variableStack->values->push(parameters->values->data[i]); } } } } // Get context (ie. root or under component layout) // NOTE(Jake): This can probably be simplified by just passing 'ast->definition' to the function // will wait to see if that's the best idea. AST_ComponentDefinition* component = NULL; if (layout->parent != NULL) { switch (layout->parent->type) { case AST_COMPONENTDEFINITION: { AST_Identifier* ast = (AST_Identifier*)layout->parent; component = ast->definition; } break; default: assert(false); break; } } // Current top element Array<HTML_Block*> elementTopStack(256, tempPool); HTML_Root* elementResult = pushHTML(HTML_Root, HTML_ROOT, compiler->pool); elementResult->component = component; elementTopStack.push(elementResult); AST_Expression_Block* loopElement = NULL; s32 loopCount = 0; while (stack.used > 0) { AST* ast_top = stack.top(); if (ast_top == NULL) { stack.pop(); elementTopStack.pop(); continue; } HTML* newElement = NULL; if (ast_top->type == AST_TAG) { AST_Identifier* ast = (AST_Identifier*)ast_top; HTML_Element* element = pushHTML(HTML_Element, HTML_ELEMENT, compiler->pool); element->name = ast->name; element->component = component; if (ast->parameters != NULL) { element->parameters = evaluateParameters(compiler, ast->parameters); } newElement = element; } else if (ast_top->type == AST_BACKEND_IDENTIFIER) { AST_Identifier* ast = (AST_Identifier*)ast_top; HTML* element = pushHTML(HTML, HTML_BACKEND_IDENTIFIER, compiler->pool); element->name = ast->name; element->component = component; newElement = element; } else if (ast_top->type == AST_BACKEND_FUNCTION) { AST_Identifier* ast = (AST_Identifier*)ast_top; HTML_Backend_Function* element = pushHTML(HTML_Backend_Function, HTML_BACKEND_FUNCTION, compiler->pool); element->name = ast->name; element->component = component; if (ast->parameters != NULL) { element->parameters = evaluateParameters(compiler, ast->parameters); } newElement = element; } else if (ast_top->type == AST_IF || ast_top->type == AST_LOOP || ast_top->type == AST_WHILE) { AST_Expression_Block* ast = (AST_Expression_Block*)ast_top; CompilerValue value = evaluateExpression(compiler, &ast->expression); assert(value.type == COMPILER_VALUE_TYPE_DOUBLE || value.type == COMPILER_VALUE_TYPE_STRING || value.type == COMPILER_VALUE_TYPE_BACKEND_EXPRESSION); if (value.type == COMPILER_VALUE_TYPE_BACKEND_EXPRESSION) { HTML_Backend_Expression_Block* element = NULL; if (ast_top->type == AST_IF) { element = pushHTML(HTML_Backend_Expression_Block, HTML_BACKEND_IF, compiler->pool); } else if (ast_top->type == AST_WHILE) { element = pushHTML(HTML_Backend_Expression_Block, HTML_BACKEND_WHILE, compiler->pool); } else { assert(false); } element->expression = value.valueExpression; newElement = element; } else { if (ast_top->type == AST_IF) { if (!value.isTrue()) { // If false, skip adding the children and stop processing this. stack.pop(); continue; } } else if (ast_top->type == AST_WHILE) { if (!value.isTrue()) { // If false, skip adding the children and stop processing this. stack.pop(); continue; } else { ++loopCount; if (loopElement != ast) { loopElement = ast; loopCount = 0; } if (loopCount > 500) { compileError("Reached loop limit of 500"); stack.pop(); continue; } // Add children and keep this AST element on the stack for (s32 i = ast_top->childNodes->used - 1; i >= 0; --i) { stack.push(ast_top->childNodes->data[i]); } continue; } } else { assert(false); } } } else if (ast_top->type == AST_COMPONENT) { AST_Identifier* ast = (AST_Identifier*)ast_top; // // compileComponentLayout // assert(ast->definition != NULL); AST_Parameters* parameters = ast->parameters; if (parameters != NULL && parameters->values != NULL && parameters->values->used > 0) { if (parameters->names == NULL || parameters->names->used == 0) { AST_Identifier* parent = (AST_Identifier*)parameters->parent; assert(parent->type == AST_COMPONENT); compiler->hasError = true; compileError("Component '%s' requires named parameters on Line %d.", &parent->name, parent->name.lineNumber); return NULL; } } AST_Layout* layout = ast->definition->layout; if (layout != NULL) { CompilerParameters* evaluatedParameters = NULL; if (ast->definition->properties != NULL) { // Evaluate the 'properties' of the component being referenced in the 'layout' evaluatedParameters = evaluateParameters(compiler, ast->definition->properties); } if (ast->parameters != NULL) { if (evaluatedParameters == NULL) { compileError("Cannot pass parameters to component that doesn't have any properties."); return NULL; } // Override the default 'properties' with parameters provided (ie. Banner(IsAtTop = 1), will modify 'evaluatedParameters' to have 'IsAtTop' to be equal to 1) evaluateParametersAndModifyExistingParameters(compiler, ast->parameters, evaluatedParameters); } if (compiler->hasError) { return NULL; } newElement = compileLayout(compiler, ast->definition->layout, evaluatedParameters); } } else if (ast_top->type == AST_IDENTIFIER) { // // Determine what this identifier is, is it a component, a function, or what? // AST_Identifier* ast = (AST_Identifier*)ast_top; if (ast->name.isBackend()) { if (ast->isFunction) { ast->type = AST_BACKEND_FUNCTION; } else { ast->type = AST_BACKEND_IDENTIFIER; } ast->name.data += 1; ast->name.length -= 1; continue; // re-iterate over this 'ast' } else if (ast->name.cmp("children")) { if (component == NULL) { compiler->hasError = true; compileError("Cannot use 'children' keyword in this context. It's reserved for component layouts."); return NULL; } HTML_Element* element = pushHTML(HTML_Element, HTML_ELEMENT_VIRTUAL, compiler->pool); element->name = ast->name; element->component = component; newElement = element; elementResult->childInsertionElement = element; } else { AST_ComponentDefinition* definition = findComponentDefinition(compiler, ast->name); if (compiler->hasError) { return NULL; } if (definition == NULL) { // todo(Jake): Check for 'func [name]' when that's parsed/implemented, if it has 'childNodes', then it // cannot be a function. // If no definition, assume HTML tag ast->type = AST_TAG; } else { ast->type = AST_COMPONENT; ast->definition = definition; // Add component to list of used components if (compiler->componentsUsed->find(ast->definition) == -1) { compiler->componentsUsed->push(ast->definition); } } if (ast->expression.tokens != NULL && ast->expression.tokens->used > 0) { CompilerValue value = evaluateExpression(compiler, &ast->expression); if (value.isTrue()) { continue; // re-iterate over this 'ast' } // if false, drop down below, remove this element from the stack but add // its children } else { continue; // re-iterate over this 'ast' } } } else if (ast_top->type == AST_STATEMENT) { AST_Statement* ast = (AST_Statement*)ast_top; CompilerParameters* stackVariables = compiler->stack->top(); assert(stackVariables != NULL); assert(ast->op.type == TOKEN_EQUAL); s32 findIndex = stackVariables->names->find(ast->name); assert(findIndex != -1); // can't find variable if (findIndex != -1) { // NOTE: Setting values array as the names/values arrays should be linked. stackVariables->values->data[findIndex] = evaluateExpression(compiler, &ast->expression); } /*bool foundName = false; for (s32 i = 0; i < stackVariables->names->used; ++i) { if (ast->name.cmp(stackVariables->names->data[i])) { stackVariables->values->data[i] = evaluateExpression(compiler, &ast->expression); foundName = true; break; } } assert(foundName);*/ } else { // Unknown ast type in 'layout' block assert(false); } // Add this element to the parent if (newElement != NULL) { HTML_Block* elementTop = elementTopStack.top(); if (elementTop->childNodes->used == elementTop->childNodes->size) { // Increase child element array size if (ast_top->parent != NULL && ast_top->parent->type == AST_LOOP) { // NOTE(Jake): A bit of a hack to decrease resizes underneath loops elementTop->childNodes->resize(elementTop->childNodes->size * 32); // approx ~500 } else { elementTop->childNodes->resize(elementTop->childNodes->size * 4); } } elementTop->childNodes->push(newElement); } stack.pop(); if (ast_top->childNodes->used > 0) { if (newElement != NULL) { // Add NULL which represents end of this block, this is used to detect when the current // top level element should be popped off the end. This ensures HTML elements are properly // nested. stack.push(NULL); if (newElement->type == HTML_ROOT) { // Inserts future elements underneath whatever element the 'children' keyword was found in. HTML_Root* element = (HTML_Root*)newElement; if (element->childInsertionElement == NULL) { compileError("Missing 'children' keyword in component layout. (%s)", &element->name); return NULL; } elementTopStack.push(element->childInsertionElement); } else if (newElement->type == HTML_ELEMENT || newElement->type == HTML_BACKEND_IF || newElement->type == HTML_BACKEND_WHILE) { HTML_Block* element = (HTML_Block*)newElement; elementTopStack.push(element); } else { // NOTE(Jake): If on this code path, then the 'newElement' should not have childNodes assert(newElement->type == HTML_TEXT || newElement->type == HTML_BACKEND_FUNCTION); elementTopStack.push(elementTopStack.top()); } } // Add children in reverse so that they're processed from first to last // (as this loop pops values off the end of the array) for (s32 i = ast_top->childNodes->used - 1; i >= 0; --i) { stack.push(ast_top->childNodes->data[i]); } } } if (variableStack != NULL) { compiler->stack->pop(); } return elementResult; } inline CSS_Rule* compileStyle(Compiler* compiler, CSS_Rule* styleBlockRule) { if (styleBlockRule->properties->used > 0) { CSS_Property* prop = &styleBlockRule->properties->data[0]; compileError("No properties should exist outside a selector rule on Line %d.", prop->name.lineNumber); return NULL; } // Setup flat array of CSS rules TemporaryPoolScope tempPoolFnScope(compiler->poolTransient); Array<CSS_Rule*>* flatCSSRuleArray = Array<CSS_Rule*>::create(1024, tempPoolFnScope); // Recursively iterate through and add to flat array { TemporaryPoolScope stackTempPool(compiler->poolTransient); Array<CSS_Rule*>* stack = Array<CSS_Rule*>::create(256, stackTempPool); stack->push(styleBlockRule); while (stack->used > 0) { CSS_Rule* stackTop = stack->pop(); flatCSSRuleArray->push(stackTop); for (s32 i = stackTop->childRules->used - 1; i >= 0; --i) { stack->push(stackTop->childRules->data[i]); } } } // NOTE(Jake): Skip item 0 as the first CSS_Rule will never have a parent. for (s32 i = 1; i < flatCSSRuleArray->used; ++i) { CSS_Rule* rule = flatCSSRuleArray->data[i]; assert(rule->parent != NULL); if (rule->type == CSS_RULE_MEDIAQUERY) { if (rule->parent != styleBlockRule) { /* Handle @media query underneath CSS rule case --------------------------------------------- .test { .banner { @media screen and (max-width: 1140px) { color: #000; } } } */ CSS_Rule* parent = rule->parent; while (parent->parent != styleBlockRule) { parent = parent->parent; } //rule->parent = styleBlockRule; //parent->parent = rule; /*CSS_Rule* newRule = pushStruct(CSS_Rule, compiler->pool); *newRule = *rule->parent; newRule->properties = rule->properties; newRule->parent = rule; // Move CSS rule to be underneath this @media query flatCSSRuleArray->push(newRule);*/ } continue; } // Go up parent tree TemporaryPoolScope tempPool(compiler->poolTransient); Array<CSS_Rule*>* treeStack = Array<CSS_Rule*>::create(512, tempPool); Array<s32>* treeIndexStack = Array<s32>::create(512, tempPool); CSS_Rule* parent = rule; CSS_Rule* newParent = styleBlockRule; // default to expanding to top 'style' block while (parent != NULL && parent->parent != NULL) { if (parent->type == CSS_RULE_MEDIAQUERY) { // Switch to expanding inside media query newParent = parent; break; } treeStack->push(parent); treeIndexStack->push(0); parent = parent->parent; } if (treeStack->used > 1 && rule->properties != NULL && rule->properties->used > 0) { TemporaryPoolScope tempSelectorSetsPool(compiler->poolTransient); Array<Array<CSS_Selector>>* newSelectorSets = Array<Array<CSS_Selector>>::create(255, tempSelectorSetsPool); s32 ridiculousIterationCounter = 0; for (;;) { { TemporaryPoolScope tempSelectorsPool(compiler->poolTransient); Array<CSS_Selector>* newSelectors = Array<CSS_Selector>::create(512, tempSelectorsPool); for (s32 i = treeStack->used - 1; i >= 0; --i) { CSS_Rule* rule = treeStack->data[i]; s32 selectorSetIndex = treeIndexStack->data[i]; Array<CSS_Selector>* selectors = &rule->selectorSets->data[selectorSetIndex]; for (s32 i = 0; i < selectors->used; ++i) { newSelectors->push(selectors->data[i]); } } newSelectors = newSelectors->createCopyShrinkToFit(compiler->pool); newSelectorSets->push(*newSelectors); } // Increment index, if index becomes bigger then array, bump up the index // of the next item in the tree. // -- parentIndexStack->data[0] == 1 // -- parentIndexStack->data[1] == 0 // -- parentIndexStack->data[2] == 0 treeIndexStack->data[0] += 1; for (s32 i = 0; i < treeStack->used - 1; ++i) { CSS_Rule* rule = treeStack->data[i]; if (treeIndexStack->data[i] >= rule->selectorSets->used) { treeIndexStack->data[i+1] += 1; treeIndexStack->data[i] = 0; } } if (treeIndexStack->data[treeStack->used - 1] >= treeStack->data[treeStack->used - 1]->selectorSets->used) { break; } ++ridiculousIterationCounter; assert(ridiculousIterationCounter <= 1000000); } rule->selectorSets = newSelectorSets->createCopyShrinkToFit(compiler->pool); rule->parent = newParent; // Debug /*CSS_Rule tempRule = {}; tempRule.type = CSS_RULE_SELECTOR; tempRule.selectorSets = newSelectorSets; printCSSRule(&tempRule, compiler->poolTransient);*/ } } // Put into hierarchy // NOTE(Jake): Skip item 0 as the first CSS_Rule will never have a parent. for (s32 i = 1; i < flatCSSRuleArray->used; ++i) { CSS_Rule* rule = flatCSSRuleArray->data[i]; assert(rule->parent != NULL); rule->childRules->used = 0; if (rule->properties != NULL && rule->properties->used > 0) { if (rule->parent->type == CSS_RULE_MEDIAQUERY) { TemporaryPoolScope tempPoolScope(compiler->poolTransient); Buffer buffer((s32)Kilobytes(1), tempPoolScope); printCSSRuleOpen(buffer, rule->parent); printCSSRule(buffer, rule); printCSSRuleClose(buffer); buffer.print(); } else if (rule->parent->type != CSS_RULE_MEDIAQUERY) { if (rule->type != CSS_RULE_MEDIAQUERY) { printCSSRule(rule, compiler->poolTransient); } } else { assert(false); } } } assert(false); return styleBlockRule; } void compile(Compiler* compiler) { // Compile HTML for (s32 i = 0; i < compiler->astFiles->used; ++i) { AST_File* ast_file = &compiler->astFiles->data[i]; if (ast_file->layouts != NULL) { for (s32 j = 0; j < ast_file->layouts->used; ++j) { AST_Layout* layout = &ast_file->layouts->data[j]; HTML_Element* html = compileLayout(compiler, layout); if (compiler->hasError) { assert(false); return; } if (html != NULL) { TemporaryPoolScope tempPoolScope(compiler->poolTransient); Buffer buffer((s32)Megabytes(4), tempPoolScope); printHTML(buffer, html); // Trim the target path from pathname String partialPath = ast_file->pathname.substring(compiler->targetDirectory.length); if (partialPath.data[0] == '\\' || partialPath.data[0] == '/') { ++partialPath.data; --partialPath.length; } partialPath.length -= 4; // remove '.fel' // StringBuilder builder(10, tempPoolScope); builder.add(compiler->outputDirectory); builder.add(partialPath); builder.add(".php"); String outputPath = builder.toString(compiler->pool); // todo(Jake): Decide to make transient or keep // show output print("\n------------------------\n"); print("Compiled From: %s", &ast_file->pathname); print("\nCompiled To: %s", &outputPath); print("\n------------------------\n"); buffer.print(); print("\n"); //File::writeEntireFile(outputPath, &buffer); } } } } // Compile CSS for (s32 i = 0; i < compiler->componentsUsed->used; ++i) { AST_ComponentDefinition* componentDefintion = compiler->componentsUsed->data[i]; if (componentDefintion->style != NULL && componentDefintion->style->rule != NULL) { CSS_Rule* topRule = componentDefintion->style->rule; topRule = compileStyle(compiler, topRule); if (compiler->hasError) { assert(false); return; } TemporaryPoolScope tempPoolScope(compiler->poolTransient); Buffer buffer((s32)Megabytes(4), tempPoolScope); for (s32 i = 0; i < topRule->childRules->used; ++i) { CSS_Rule* rule = topRule->childRules->data[i]; printCSSRule(buffer, rule); buffer.add("\n"); } if (buffer.used > 0) { print("\n------------------------\n"); print("CSS From: %s\n", &componentDefintion->name); print("\n------------------------\n"); buffer.print(); print("\n\n"); } } } }
#ifndef ENTT_LIB_EMITTER_PLUGIN_STD_PROXY_H #define ENTT_LIB_EMITTER_PLUGIN_STD_PROXY_H #include "types.h" struct proxy: emitter_proxy { proxy(test_emitter &); void publish(message) override; void publish(event) override; private: test_emitter *emitter; }; #endif
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once WINRT_EXPORT namespace winrt { namespace ABI::Windows::UI::Notifications { struct IAdaptiveNotificationContent; struct IAdaptiveNotificationText; struct IBadgeNotification; struct IBadgeNotificationFactory; struct IBadgeUpdateManagerForUser; struct IBadgeUpdateManagerStatics; struct IBadgeUpdateManagerStatics2; struct IBadgeUpdater; struct IKnownAdaptiveNotificationHintsStatics; struct IKnownAdaptiveNotificationTextStylesStatics; struct IKnownNotificationBindingsStatics; struct INotification; struct INotificationBinding; struct INotificationData; struct INotificationDataFactory; struct INotificationVisual; struct IScheduledTileNotification; struct IScheduledTileNotificationFactory; struct IScheduledToastNotification; struct IScheduledToastNotification2; struct IScheduledToastNotification3; struct IScheduledToastNotificationFactory; struct IShownTileNotification; struct ITileFlyoutNotification; struct ITileFlyoutNotificationFactory; struct ITileFlyoutUpdateManagerStatics; struct ITileFlyoutUpdater; struct ITileNotification; struct ITileNotificationFactory; struct ITileUpdateManagerForUser; struct ITileUpdateManagerStatics; struct ITileUpdateManagerStatics2; struct ITileUpdater; struct ITileUpdater2; struct IToastActivatedEventArgs; struct IToastCollection; struct IToastCollectionFactory; struct IToastCollectionManager; struct IToastDismissedEventArgs; struct IToastFailedEventArgs; struct IToastNotification; struct IToastNotification2; struct IToastNotification3; struct IToastNotification4; struct IToastNotificationActionTriggerDetail; struct IToastNotificationFactory; struct IToastNotificationHistory; struct IToastNotificationHistory2; struct IToastNotificationHistoryChangedTriggerDetail; struct IToastNotificationHistoryChangedTriggerDetail2; struct IToastNotificationManagerForUser; struct IToastNotificationManagerForUser2; struct IToastNotificationManagerStatics; struct IToastNotificationManagerStatics2; struct IToastNotificationManagerStatics4; struct IToastNotificationManagerStatics5; struct IToastNotifier; struct IToastNotifier2; struct IUserNotification; struct IUserNotificationChangedEventArgs; struct AdaptiveNotificationText; struct BadgeNotification; struct BadgeUpdateManagerForUser; struct BadgeUpdater; struct Notification; struct NotificationBinding; struct NotificationData; struct NotificationVisual; struct ScheduledTileNotification; struct ScheduledToastNotification; struct ShownTileNotification; struct TileFlyoutNotification; struct TileFlyoutUpdater; struct TileNotification; struct TileUpdateManagerForUser; struct TileUpdater; struct ToastActivatedEventArgs; struct ToastCollection; struct ToastCollectionManager; struct ToastDismissedEventArgs; struct ToastFailedEventArgs; struct ToastNotification; struct ToastNotificationActionTriggerDetail; struct ToastNotificationHistory; struct ToastNotificationHistoryChangedTriggerDetail; struct ToastNotificationManagerForUser; struct ToastNotifier; struct UserNotification; struct UserNotificationChangedEventArgs; } namespace Windows::UI::Notifications { struct IAdaptiveNotificationContent; struct IAdaptiveNotificationText; struct IBadgeNotification; struct IBadgeNotificationFactory; struct IBadgeUpdateManagerForUser; struct IBadgeUpdateManagerStatics; struct IBadgeUpdateManagerStatics2; struct IBadgeUpdater; struct IKnownAdaptiveNotificationHintsStatics; struct IKnownAdaptiveNotificationTextStylesStatics; struct IKnownNotificationBindingsStatics; struct INotification; struct INotificationBinding; struct INotificationData; struct INotificationDataFactory; struct INotificationVisual; struct IScheduledTileNotification; struct IScheduledTileNotificationFactory; struct IScheduledToastNotification; struct IScheduledToastNotification2; struct IScheduledToastNotification3; struct IScheduledToastNotificationFactory; struct IShownTileNotification; struct ITileFlyoutNotification; struct ITileFlyoutNotificationFactory; struct ITileFlyoutUpdateManagerStatics; struct ITileFlyoutUpdater; struct ITileNotification; struct ITileNotificationFactory; struct ITileUpdateManagerForUser; struct ITileUpdateManagerStatics; struct ITileUpdateManagerStatics2; struct ITileUpdater; struct ITileUpdater2; struct IToastActivatedEventArgs; struct IToastCollection; struct IToastCollectionFactory; struct IToastCollectionManager; struct IToastDismissedEventArgs; struct IToastFailedEventArgs; struct IToastNotification; struct IToastNotification2; struct IToastNotification3; struct IToastNotification4; struct IToastNotificationActionTriggerDetail; struct IToastNotificationFactory; struct IToastNotificationHistory; struct IToastNotificationHistory2; struct IToastNotificationHistoryChangedTriggerDetail; struct IToastNotificationHistoryChangedTriggerDetail2; struct IToastNotificationManagerForUser; struct IToastNotificationManagerForUser2; struct IToastNotificationManagerStatics; struct IToastNotificationManagerStatics2; struct IToastNotificationManagerStatics4; struct IToastNotificationManagerStatics5; struct IToastNotifier; struct IToastNotifier2; struct IUserNotification; struct IUserNotificationChangedEventArgs; struct AdaptiveNotificationText; struct BadgeNotification; struct BadgeUpdateManager; struct BadgeUpdateManagerForUser; struct BadgeUpdater; struct KnownAdaptiveNotificationHints; struct KnownAdaptiveNotificationTextStyles; struct KnownNotificationBindings; struct Notification; struct NotificationBinding; struct NotificationData; struct NotificationVisual; struct ScheduledTileNotification; struct ScheduledToastNotification; struct ShownTileNotification; struct TileFlyoutNotification; struct TileFlyoutUpdateManager; struct TileFlyoutUpdater; struct TileNotification; struct TileUpdateManager; struct TileUpdateManagerForUser; struct TileUpdater; struct ToastActivatedEventArgs; struct ToastCollection; struct ToastCollectionManager; struct ToastDismissedEventArgs; struct ToastFailedEventArgs; struct ToastNotification; struct ToastNotificationActionTriggerDetail; struct ToastNotificationHistory; struct ToastNotificationHistoryChangedTriggerDetail; struct ToastNotificationManager; struct ToastNotificationManagerForUser; struct ToastNotifier; struct UserNotification; struct UserNotificationChangedEventArgs; } namespace Windows::UI::Notifications { template <typename T> struct impl_IAdaptiveNotificationContent; template <typename T> struct impl_IAdaptiveNotificationText; template <typename T> struct impl_IBadgeNotification; template <typename T> struct impl_IBadgeNotificationFactory; template <typename T> struct impl_IBadgeUpdateManagerForUser; template <typename T> struct impl_IBadgeUpdateManagerStatics; template <typename T> struct impl_IBadgeUpdateManagerStatics2; template <typename T> struct impl_IBadgeUpdater; template <typename T> struct impl_IKnownAdaptiveNotificationHintsStatics; template <typename T> struct impl_IKnownAdaptiveNotificationTextStylesStatics; template <typename T> struct impl_IKnownNotificationBindingsStatics; template <typename T> struct impl_INotification; template <typename T> struct impl_INotificationBinding; template <typename T> struct impl_INotificationData; template <typename T> struct impl_INotificationDataFactory; template <typename T> struct impl_INotificationVisual; template <typename T> struct impl_IScheduledTileNotification; template <typename T> struct impl_IScheduledTileNotificationFactory; template <typename T> struct impl_IScheduledToastNotification; template <typename T> struct impl_IScheduledToastNotification2; template <typename T> struct impl_IScheduledToastNotification3; template <typename T> struct impl_IScheduledToastNotificationFactory; template <typename T> struct impl_IShownTileNotification; template <typename T> struct impl_ITileFlyoutNotification; template <typename T> struct impl_ITileFlyoutNotificationFactory; template <typename T> struct impl_ITileFlyoutUpdateManagerStatics; template <typename T> struct impl_ITileFlyoutUpdater; template <typename T> struct impl_ITileNotification; template <typename T> struct impl_ITileNotificationFactory; template <typename T> struct impl_ITileUpdateManagerForUser; template <typename T> struct impl_ITileUpdateManagerStatics; template <typename T> struct impl_ITileUpdateManagerStatics2; template <typename T> struct impl_ITileUpdater; template <typename T> struct impl_ITileUpdater2; template <typename T> struct impl_IToastActivatedEventArgs; template <typename T> struct impl_IToastCollection; template <typename T> struct impl_IToastCollectionFactory; template <typename T> struct impl_IToastCollectionManager; template <typename T> struct impl_IToastDismissedEventArgs; template <typename T> struct impl_IToastFailedEventArgs; template <typename T> struct impl_IToastNotification; template <typename T> struct impl_IToastNotification2; template <typename T> struct impl_IToastNotification3; template <typename T> struct impl_IToastNotification4; template <typename T> struct impl_IToastNotificationActionTriggerDetail; template <typename T> struct impl_IToastNotificationFactory; template <typename T> struct impl_IToastNotificationHistory; template <typename T> struct impl_IToastNotificationHistory2; template <typename T> struct impl_IToastNotificationHistoryChangedTriggerDetail; template <typename T> struct impl_IToastNotificationHistoryChangedTriggerDetail2; template <typename T> struct impl_IToastNotificationManagerForUser; template <typename T> struct impl_IToastNotificationManagerForUser2; template <typename T> struct impl_IToastNotificationManagerStatics; template <typename T> struct impl_IToastNotificationManagerStatics2; template <typename T> struct impl_IToastNotificationManagerStatics4; template <typename T> struct impl_IToastNotificationManagerStatics5; template <typename T> struct impl_IToastNotifier; template <typename T> struct impl_IToastNotifier2; template <typename T> struct impl_IUserNotification; template <typename T> struct impl_IUserNotificationChangedEventArgs; } namespace Windows::UI::Notifications { enum class AdaptiveNotificationContentKind { Text = 0, }; enum class BadgeTemplateType { BadgeGlyph = 0, BadgeNumber = 1, }; enum class NotificationKinds : unsigned { Unknown = 0x0, Toast = 0x1, }; DEFINE_ENUM_FLAG_OPERATORS(NotificationKinds) enum class NotificationMirroring { Allowed = 0, Disabled = 1, }; enum class NotificationSetting { Enabled = 0, DisabledForApplication = 1, DisabledForUser = 2, DisabledByGroupPolicy = 3, DisabledByManifest = 4, }; enum class NotificationUpdateResult { Succeeded = 0, Failed = 1, NotificationNotFound = 2, }; enum class PeriodicUpdateRecurrence { HalfHour = 0, Hour = 1, SixHours = 2, TwelveHours = 3, Daily = 4, }; enum class TileFlyoutTemplateType { TileFlyoutTemplate01 = 0, }; enum class TileTemplateType { TileSquareImage [[deprecated("TileSquareImage may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Image.")]] = 0, TileSquareBlock [[deprecated("TileSquareBlock may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Block.")]] = 1, TileSquareText01 [[deprecated("TileSquareText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Text01.")]] = 2, TileSquareText02 [[deprecated("TileSquareText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Text02.")]] = 3, TileSquareText03 [[deprecated("TileSquareText03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Text03.")]] = 4, TileSquareText04 [[deprecated("TileSquareText04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150Text04.")]] = 5, TileSquarePeekImageAndText01 [[deprecated("TileSquarePeekImageAndText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150PeekImageAndText01.")]] = 6, TileSquarePeekImageAndText02 [[deprecated("TileSquarePeekImageAndText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150PeekImageAndText02.")]] = 7, TileSquarePeekImageAndText03 [[deprecated("TileSquarePeekImageAndText03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150PeekImageAndText03.")]] = 8, TileSquarePeekImageAndText04 [[deprecated("TileSquarePeekImageAndText04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileSquare150x150PeekImageAndText04.")]] = 9, TileWideImage [[deprecated("TileWideImage may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Image.")]] = 10, TileWideImageCollection [[deprecated("TileWideImageCollection may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150ImageCollection.")]] = 11, TileWideImageAndText01 [[deprecated("TileWideImageAndText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150ImageAndText01.")]] = 12, TileWideImageAndText02 [[deprecated("TileWideImageAndText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150ImageAndText02.")]] = 13, TileWideBlockAndText01 [[deprecated("TileWideBlockAndText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150BlockAndText01.")]] = 14, TileWideBlockAndText02 [[deprecated("TileWideBlockAndText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150BlockAndText02.")]] = 15, TileWidePeekImageCollection01 [[deprecated("TileWidePeekImageCollection01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection01.")]] = 16, TileWidePeekImageCollection02 [[deprecated("TileWidePeekImageCollection02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection02.")]] = 17, TileWidePeekImageCollection03 [[deprecated("TileWidePeekImageCollection03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection03.")]] = 18, TileWidePeekImageCollection04 [[deprecated("TileWidePeekImageCollection04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection04.")]] = 19, TileWidePeekImageCollection05 [[deprecated("TileWidePeekImageCollection05 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection05.")]] = 20, TileWidePeekImageCollection06 [[deprecated("TileWidePeekImageCollection06 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageCollection06.")]] = 21, TileWidePeekImageAndText01 [[deprecated("TileWidePeekImageAndText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageAndText01.")]] = 22, TileWidePeekImageAndText02 [[deprecated("TileWidePeekImageAndText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImageAndText02.")]] = 23, TileWidePeekImage01 [[deprecated("TileWidePeekImage01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage01.")]] = 24, TileWidePeekImage02 [[deprecated("TileWidePeekImage02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage02.")]] = 25, TileWidePeekImage03 [[deprecated("TileWidePeekImage03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage03.")]] = 26, TileWidePeekImage04 [[deprecated("TileWidePeekImage04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage04.")]] = 27, TileWidePeekImage05 [[deprecated("TileWidePeekImage05 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage05.")]] = 28, TileWidePeekImage06 [[deprecated("TileWidePeekImage06 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150PeekImage06.")]] = 29, TileWideSmallImageAndText01 [[deprecated("TileWideSmallImageAndText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150SmallImageAndText01.")]] = 30, TileWideSmallImageAndText02 [[deprecated("TileWideSmallImageAndText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150SmallImageAndText02.")]] = 31, TileWideSmallImageAndText03 [[deprecated("TileWideSmallImageAndText03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150SmallImageAndText03.")]] = 32, TileWideSmallImageAndText04 [[deprecated("TileWideSmallImageAndText04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150SmallImageAndText04.")]] = 33, TileWideSmallImageAndText05 [[deprecated("TileWideSmallImageAndText05 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150SmallImageAndText05.")]] = 34, TileWideText01 [[deprecated("TileWideText01 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text01.")]] = 35, TileWideText02 [[deprecated("TileWideText02 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text02.")]] = 36, TileWideText03 [[deprecated("TileWideText03 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text03.")]] = 37, TileWideText04 [[deprecated("TileWideText04 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text04.")]] = 38, TileWideText05 [[deprecated("TileWideText05 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text05.")]] = 39, TileWideText06 [[deprecated("TileWideText06 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text06.")]] = 40, TileWideText07 [[deprecated("TileWideText07 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text07.")]] = 41, TileWideText08 [[deprecated("TileWideText08 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text08.")]] = 42, TileWideText09 [[deprecated("TileWideText09 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text09.")]] = 43, TileWideText10 [[deprecated("TileWideText10 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text10.")]] = 44, TileWideText11 [[deprecated("TileWideText11 may be altered or unavailable for releases after Windows 8.1. Instead, use TileWide310x150Text11.")]] = 45, TileSquare150x150Image = 0, TileSquare150x150Block = 1, TileSquare150x150Text01 = 2, TileSquare150x150Text02 = 3, TileSquare150x150Text03 = 4, TileSquare150x150Text04 = 5, TileSquare150x150PeekImageAndText01 = 6, TileSquare150x150PeekImageAndText02 = 7, TileSquare150x150PeekImageAndText03 = 8, TileSquare150x150PeekImageAndText04 = 9, TileWide310x150Image = 10, TileWide310x150ImageCollection = 11, TileWide310x150ImageAndText01 = 12, TileWide310x150ImageAndText02 = 13, TileWide310x150BlockAndText01 = 14, TileWide310x150BlockAndText02 = 15, TileWide310x150PeekImageCollection01 = 16, TileWide310x150PeekImageCollection02 = 17, TileWide310x150PeekImageCollection03 = 18, TileWide310x150PeekImageCollection04 = 19, TileWide310x150PeekImageCollection05 = 20, TileWide310x150PeekImageCollection06 = 21, TileWide310x150PeekImageAndText01 = 22, TileWide310x150PeekImageAndText02 = 23, TileWide310x150PeekImage01 = 24, TileWide310x150PeekImage02 = 25, TileWide310x150PeekImage03 = 26, TileWide310x150PeekImage04 = 27, TileWide310x150PeekImage05 = 28, TileWide310x150PeekImage06 = 29, TileWide310x150SmallImageAndText01 = 30, TileWide310x150SmallImageAndText02 = 31, TileWide310x150SmallImageAndText03 = 32, TileWide310x150SmallImageAndText04 = 33, TileWide310x150SmallImageAndText05 = 34, TileWide310x150Text01 = 35, TileWide310x150Text02 = 36, TileWide310x150Text03 = 37, TileWide310x150Text04 = 38, TileWide310x150Text05 = 39, TileWide310x150Text06 = 40, TileWide310x150Text07 = 41, TileWide310x150Text08 = 42, TileWide310x150Text09 = 43, TileWide310x150Text10 = 44, TileWide310x150Text11 = 45, TileSquare310x310BlockAndText01 = 46, TileSquare310x310BlockAndText02 = 47, TileSquare310x310Image = 48, TileSquare310x310ImageAndText01 = 49, TileSquare310x310ImageAndText02 = 50, TileSquare310x310ImageAndTextOverlay01 = 51, TileSquare310x310ImageAndTextOverlay02 = 52, TileSquare310x310ImageAndTextOverlay03 = 53, TileSquare310x310ImageCollectionAndText01 = 54, TileSquare310x310ImageCollectionAndText02 = 55, TileSquare310x310ImageCollection = 56, TileSquare310x310SmallImagesAndTextList01 = 57, TileSquare310x310SmallImagesAndTextList02 = 58, TileSquare310x310SmallImagesAndTextList03 = 59, TileSquare310x310SmallImagesAndTextList04 = 60, TileSquare310x310Text01 = 61, TileSquare310x310Text02 = 62, TileSquare310x310Text03 = 63, TileSquare310x310Text04 = 64, TileSquare310x310Text05 = 65, TileSquare310x310Text06 = 66, TileSquare310x310Text07 = 67, TileSquare310x310Text08 = 68, TileSquare310x310TextList01 = 69, TileSquare310x310TextList02 = 70, TileSquare310x310TextList03 = 71, TileSquare310x310SmallImageAndText01 = 72, TileSquare310x310SmallImagesAndTextList05 = 73, TileSquare310x310Text09 = 74, TileSquare71x71IconWithBadge = 75, TileSquare150x150IconWithBadge = 76, TileWide310x150IconWithBadgeAndText = 77, TileSquare71x71Image = 78, TileTall150x310Image = 79, }; enum class ToastDismissalReason { UserCanceled = 0, ApplicationHidden = 1, TimedOut = 2, }; enum class ToastHistoryChangedType { Cleared = 0, Removed = 1, Expired = 2, Added = 3, }; enum class ToastNotificationPriority { Default = 0, High = 1, }; enum class ToastTemplateType { ToastImageAndText01 = 0, ToastImageAndText02 = 1, ToastImageAndText03 = 2, ToastImageAndText04 = 3, ToastText01 = 4, ToastText02 = 5, ToastText03 = 6, ToastText04 = 7, }; enum class UserNotificationChangedKind { Added = 0, Removed = 1, }; } }
// // Copyright Jason Rice 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_BINDER_JS_HPP #define NBDL_BINDER_JS_HPP #include <nbdl/bind_map.hpp> #include <nbdl/bind_sequence.hpp> #include <nbdl/bind_variant.hpp> #include <nbdl/concept/BindableMap.hpp> #include <nbdl/concept/BindableSequence.hpp> #include <nbdl/concept/BindableVariant.hpp> #include <nbdl/concept/String.hpp> #include <nbdl/detail/js_val.hpp> #include <nbdl/js.hpp> #include <nbdl/string.hpp> #include <nbdl/util/base64_encode.hpp> #include <nbdl/util/base64_decode.hpp> #include <nbdl/variant.hpp> #include <boost/hana/ext/std/tuple.hpp> #include <emscripten.h> #include <string> #include <type_traits> #include <utility> namespace nbdl::binder::js { namespace hana = boost::hana; using js_val = nbdl::detail::js_val; struct bind_to_fn { template <typename X> void operator()(nbdl::js::val&, X const&) const; template <typename X> void operator()(js_val&, X const&) const; }; constexpr bind_to_fn bind_to{}; struct bind_from_fn { template <typename X> void operator()(nbdl::js::val const&, X&) const; template <typename X> void operator()(js_val const&, X&) const; }; constexpr bind_from_fn bind_from{}; namespace detail { template <typename T> struct bind_to_impl; template <typename T> struct bind_from_impl; } template <typename X> void bind_to_fn::operator()(nbdl::js::val& v, X const& x) const { (*this)(reinterpret_cast<js_val&>(v), x); } template <typename X> void bind_to_fn::operator()(js_val& val, X const& x) const { using Tag = hana::tag_of_t<X>; using Impl = detail::bind_to_impl<Tag>; Impl::apply(val, x); } template <typename X> void bind_from_fn::operator()(nbdl::js::val const& v, X& x) const { (*this)(reinterpret_cast<js_val const&>(v), x); } template <typename X> void bind_from_fn::operator()(js_val const& val, X& x) const { using Tag = hana::tag_of_t<X>; using Impl = detail::bind_from_impl<Tag>; Impl::apply(val, x); } namespace detail { int get_variant_type_id(js_val const& val) { return EM_ASM_INT( { var v = Module.NBDL_DETAIL_JS_GET($0); if (Array.isArray(v)) { return v[0]; } else { return v; } } , val.handle() ); } // // bind_to_impl // template <nbdl::String T> struct bind_to_impl<T> { template <typename X> static void apply(js_val& val, X const& x) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($0, UTF8ToString($1, $2)); } , val.handle() , x.data() , x.size() ); } }; template <typename T> requires std::is_integral<T>::value struct bind_to_impl<T> { template <typename X> static void apply(js_val& val, X x) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($0, $1); } , val.handle() , x ); } }; template <typename T> requires std::is_enum<T>::value struct bind_to_impl<T> { template <typename X> static void apply(js_val& val, X x) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($0, $1); } , val.handle() , static_cast<std::underlying_type_t<X>>(x) ); } }; template <nbdl::BindableSequence T> requires (!nbdl::BindableMap<T>) struct bind_to_impl<T> { template <typename Sequence> static void apply(js_val& val, Sequence const& sequence) { js_val child_val{}; EM_ASM_({ Module.NBDL_DETAIL_JS_SET($0, []); }, val.handle()); nbdl::bind_sequence(sequence, hana::overload( []() { // no members... do nothing } , [&](auto& x) { // singleton does not need to be wrapped in array bind_to(val, x); } , [&](auto& x1, auto& x2, auto& ...xs) { hana::for_each(std::forward_as_tuple(x1, x2, xs...), [&](auto& x) { bind_to(child_val, x); EM_ASM_( { Module.NBDL_DETAIL_JS_GET($0).push( Module.NBDL_DETAIL_JS_GET($1) ); } , val.handle() , child_val.handle() ); }); } )); } }; template <nbdl::Container T> struct bind_to_impl<T> { template <typename Xs> static void apply(js_val& val, Xs const& xs) { js_val child_val{}; EM_ASM_({ Module.NBDL_DETAIL_JS_SET($0, []); }, val.handle()); for (auto const& x: xs) { bind_to(child_val, x); EM_ASM_( { Module.NBDL_DETAIL_JS_GET($0).push( Module.NBDL_DETAIL_JS_GET($1) ); } , val.handle() , child_val.handle() ); }; } }; template <ContiguousByteContainer T> struct bind_to_impl<T> { template <typename Xs> static void apply(js_val& val, Xs const& xs) { nbdl::string temp = nbdl::string(nbdl::util::base64_encode(xs)); bind_to(val, temp); } }; template <BindableMap T> struct bind_to_impl<T> { template <typename Xs> static void apply(js_val& val, Xs const& xs) { js_val child_val{}; EM_ASM_({ Module.NBDL_DETAIL_JS_SET($0, {}); }, val.handle()); nbdl::bind_map(xs, [&](auto const& ...y) { hana::for_each(std::forward_as_tuple(y...), [&](auto& pair) { bind_to(child_val, hana::second(pair).get()); EM_ASM_( { var key = UTF8ToString($1, $2); Module.NBDL_DETAIL_JS_GET($0)[key] = Module.NBDL_DETAIL_JS_GET($3); } , val.handle() , hana::first(pair).c_str() , decltype(hana::size(hana::first(pair)))::value , child_val.handle() ); }); }); } }; template <nbdl::BindableVariant T> struct bind_to_impl<T> { template <typename Variant> static void apply(js_val& val, Variant const& v) { nbdl::bind_variant(v, [&](auto const& ...x) { auto refs = std::forward_as_tuple(x...); bind_to(val, refs); }); } }; // // bind_from_impl // template <nbdl::String T> struct bind_from_impl<T> { template <typename X> static void apply(js_val const& val, X& x) { using String = std::decay_t<X>; int length = EM_ASM_INT( { return Module.NBDL_DETAIL_JS_GET($0).length; } , val.handle() ); String temp(length, '\0'); EM_ASM_( { var v = Module.NBDL_DETAIL_JS_GET($0); if (typeof v === 'string') { Module.stringToAscii(v, $1); } else // assume its an ArrayBuffer { var heap = new Uint8Array(Module.HEAPU8.buffer, $1, v.length); heap.set(v); } } , val.handle() , temp.data() ); x = std::move(temp); } }; template <typename T> requires std::is_integral<T>::value struct bind_from_impl<T> { template <typename X> static void apply(js_val const& val, X& x) { x = EM_ASM_INT( { return Module.NBDL_DETAIL_JS_GET($0); } , val.handle() ); } }; template <typename T> requires std::is_enum<T>::value struct bind_from_impl<T> { template <typename X> static void apply(js_val const& val, X& x) { x = static_cast<X>(EM_ASM_INT( { return Module.NBDL_DETAIL_JS_GET($0); } , val.handle() )); } }; template <nbdl::BindableSequence T> requires (!nbdl::BindableMap<T>) struct bind_from_impl<T> { template <typename Sequence> static void apply(js_val const& val, Sequence& sequence) { js_val child_val{}; int i = 0; nbdl::bind_sequence(sequence, hana::overload( []() { // no members... do nothing } , [&](auto& x) { // singleton does not need to be wrapped in array bind_from(val, x); } , [&](auto& x1, auto& x2, auto& ...xs) { hana::for_each(std::forward_as_tuple(x1, x2, xs...), [&](auto& x) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($1, Module.NBDL_DETAIL_JS_GET($0)[$2] ); } , val.handle() , child_val.handle() , i ); bind_from(child_val, x); ++i; }); } )); } }; template <nbdl::Container T> struct bind_from_impl<T> { template <typename Xs> static void apply(js_val const& val, Xs& xs) { using Container = std::decay_t<Xs>; int length = EM_ASM_INT( { return Module.NBDL_DETAIL_JS_GET($0).length; } , val.handle() ); Container container(length); int i = 0; js_val child_val{}; for (auto& x : container) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($1, Module.NBDL_DETAIL_JS_GET($0)[$2] ); } , val.handle() , child_val.handle() , i ); bind_from(child_val, x); ++i; }; xs = std::move(container); } }; template <nbdl::ContiguousByteContainer T> struct bind_from_impl<T> { template <typename Xs> static void apply(js_val const& val, Xs& xs) { nbdl::string temp{}; bind_from(val, temp); // TODO actually check for error nbdl::util::base64_decode(temp, xs); } }; template <nbdl::BindableMap T> struct bind_from_impl<T> { template <typename Xs> static void apply(js_val const& val, Xs& xs) { js_val child_val{}; nbdl::bind_map(xs, [&](auto ...y) { hana::for_each(std::forward_as_tuple(y...), [&](auto pair) { EM_ASM_( { Module.NBDL_DETAIL_JS_SET($1, Module.NBDL_DETAIL_JS_GET($0)[UTF8ToString($2, $3)] ); } , val.handle() , child_val.handle() , hana::first(pair).c_str() , decltype(hana::size(hana::first(pair)))::value ); bind_from(child_val, hana::second(pair).get()); }); }); } }; template <nbdl::BindableVariant T> struct bind_from_impl<T> { template <typename Variant> static void apply(js_val const& val, Variant& var) { js_val child_val{}; int type_id = get_variant_type_id(val); nbdl::bind_variant(type_id, var, [&](auto& ...x) { auto refs = std::forward_as_tuple(x...); bind_from(val, refs); }); } }; } } #endif
#include<bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ int n,sum;cin>>n>>sum; vector<vector<int>>a(n,vector<int>(2)); for(int i=0;i<n;i++){ cin>>a[i][0]; a[i][1]=i; } sort(a.begin(),a.end()); int l=0,r=n-1; while(l<r){ if(a[l][0]+a[r][0]==sum){ cout<<a[l][1]+1<<" "<<a[r][1]+1; return; } else if(a[l][0]+a[r][0]>sum){ r--; } else l++; } cout<<"IMPOSSIBLE"; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("op.txt","w",stdout); #endif int t=1; //cin>>t; while(t--){ solve(); } }
/*MetaNodeTest.cpp MetaNode copyright Vixac Ltd. All Rights Reserved */ #include "MetaNode.h" #include <gtest/gtest.h> namespace VI = vixac; namespace IN = VI::inout; TEST(MetaNode, aTest) { /// EXPECT_STREQ( "write some tests for MetaNode", "TODO"); }
#pragma once #include <iostream> class ArcParse { public: ArcParse(); ArcParse(int argc, char **argv); ~ArcParse(); char *input_file = NULL; int width = 100; int height = 100; char *output_file = NULL; float depth_min = 0; float depth_max = 1; char *depth_file = NULL; char *normal_file = NULL; bool shade_back = false; };
#include <iostream> using namespace std; int main() { string jenjang, program, kode_fti; int kode_prodi, tahun; cout << "Jenjang Studi : "; getline(cin, jenjang); if(jenjang == "S1"){ cout << "Program Studi : "; getline(cin, program); kode_fti = "12"; if(program == "Teknik Kimia"){ kode_prodi = 1; } else if(program == "Teknik Industri"){ kode_prodi = 2; } else if(program == "Informatika"){ kode_prodi = 3; } else if(program == "Sistem Informasi"){ kode_prodi = 4; } } else if(jenjang == "D3 TK"){ kode_fti = "02"; kode_prodi = 1; } cout << "Tahun Masuk : "; cin >> tahun; tahun=tahun%100; if(tahun >= 1 && tahun <= 9){ cout << "NIM Anda : " << kode_fti << kode_prodi << 0 << tahun << 0; }else{ cout << "NIM Anda : " << kode_fti << kode_prodi << tahun << 0; if(tahun==0){ cout << 0; } } return 0; }
#include <Wifi_S08_v2.h> #define SSID "ESPeezy" #define PASSWD "MOMENTUM" #define POLLPERIOD 1000 ESP8266 wifi = ESP8266(0,false); String MAC; unsigned long lastRequest = 0; void setup() { Serial.begin(115200); wifi.begin(); MAC = wifi.getMAC(); wifi.connectWifi(SSID, PASSWD); while (!wifi.isConnected()); //wait for connection } int count = 0; void loop() { if (wifi.hasResponse()) { String response = wifi.getResponse(); Serial.print("RESPONSE: "); Serial.println(response); count++; Serial.println(count); } if (!wifi.isBusy() && millis()-lastRequest > POLLPERIOD) { String domain = "192.168.4.1"; String path = "/"; //String domain = "iesc-s2.mit.edu"; //String path = "/hello.html"; wifi.sendRequest(GET, domain, 80, path, ""); lastRequest = millis(); } }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/Format> #include <flux/meta/JsonWriter> namespace flux { namespace meta { Ref<JsonWriter> JsonWriter::create(Format format, String indent) { return new JsonWriter(format, indent); } JsonWriter::JsonWriter(Format format, String indent): format_(format), indent_(indent) {} void JsonWriter::write(Variant value) { writeValue(value, 0); format_ << nl; } void JsonWriter::writeValue(Variant value, int depth) { if ( type(value) == Variant::IntType || type(value) == Variant::BoolType || type(value) == Variant::FloatType ) { format_ << value; } else if (type(value) == Variant::StringType) { String s = value; if (s->contains("\"")) s = s->replace("\"", "\\\""); s = s->escape(); format_ << "\"" << s << "\""; } else if (type(value) == Variant::ListType) { writeList(value, depth); } else if (type(value) == Variant::ObjectType) { writeObject(value, depth); } } void JsonWriter::writeList(Variant value, int depth) { if (itemType(value) == Variant::IntType) writeTypedList<int>(value, depth); else if (itemType(value) == Variant::BoolType) writeTypedList<bool>(value, depth); else if (itemType(value) == Variant::FloatType) writeTypedList<float>(value, depth); else if (itemType(value) == Variant::StringType) writeTypedList<String>(value, depth); else writeTypedList<Variant>(value, depth); } void JsonWriter::writeObject(Variant value, int depth) { Ref<MetaObject> object = cast<MetaObject>(value); if (object->className() != "") { format_ << object->className(); format_ << " "; } if (object->count() == 0) { format_ << "{}"; return; } format_ << "{\n"; writeIndent(depth + 1); for (int i = 0; i < object->count(); ++i) { String memberName = object->keyAt(i); Variant memberValue = object->valueAt(i); format_ << "\"" << memberName << "\": "; writeValue(memberValue, depth + 1); if (i < object->count() - 1) { format_ << ",\n"; writeIndent(depth + 1); } else { format_ << "\n"; writeIndent(depth); } } format_ << "}"; } void JsonWriter::writeIndent(int depth) { for (int i = 0; i < depth; ++i) format_ << indent_; } template<class T> void JsonWriter::writeTypedList(Variant value, int depth) { List<T> *list = cast< List<T> >(value); if (list->count() == 0) { format_ << "[]"; return; } format_ << "[ "; for (int i = 0; i < list->count(); ++i) { writeValue(list->at(i), depth); if (i < list->count() - 1) format_ << ", "; } format_ << " ]"; } }} // namespace flux::meta
#include "wrapper.h" hCAnimBlendHierarchy_Constructor OLD_CAnimBlendHierarchy_Constructor = (hCAnimBlendHierarchy_Constructor)0x4CF270; void CAnimBlendHierarchy_Constructor ( CAnimBlendHierarchy * pAnimHierarchy ) { int pThis = (int)pAnimHierarchy; *(DWORD *)(pThis + 4) = 0; *(WORD *)(pThis + 8) = 0; *(BYTE *)(pThis + 10) = 0; *(BYTE *)(pThis + 11) = 0; *(DWORD *)(pThis + 12) = -1; *(DWORD *)(pThis + 16) = 0; *(DWORD *)(pThis + 20) = 0; }
#pragma once #include "../MetaMorpheusEngineResults.h" #include <string> #include <unordered_map> #include <unordered_set> #include <tuple> #include "stringbuilder.h" //C# TO C++ CONVERTER NOTE: Forward class declarations: namespace EngineLayer { class MetaMorpheusEngine; } using namespace Proteomics; namespace EngineLayer { namespace Gptmd { class GptmdResults : public MetaMorpheusEngineResults { private: std::unordered_map<std::string, std::unordered_set<std::tuple<int, Modification*>>> privateMods; const int ModsAdded; public: GptmdResults(MetaMorpheusEngine *s, std::unordered_map<std::string, std::unordered_set<std::tuple<int, Modification*>>> &mods, int modsAdded); std::unordered_map<std::string, std::unordered_set<std::tuple<int, Modification*>>> getMods() const; void setMods(const std::unordered_map<std::string, std::unordered_set<std::tuple<int, Modification*>>> &value); std::string ToString(); }; } }
// OnHScrollPageLeft.h #ifndef _ONHSCROLLPAGELEFT_H #define _ONHSCROLLPAGELEFT_H #include "HorizontalScroll.h" #include "ScrollAction.h" class OnHScrollPageLeft : public ScrollAction { public: OnHScrollPageLeft(HorizontalScroll *horizontalScroll); OnHScrollPageLeft(const OnHScrollPageLeft& source); virtual ~OnHScrollPageLeft(); OnHScrollPageLeft& operator=(const OnHScrollPageLeft& source); virtual void Action(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); private: HorizontalScroll *horizontalScroll; }; #endif //_ONHSCROLLPAGELEFT_H
/* The MIT License (MIT) Copyright 2016 Luca Beldi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "abstractsingleroleserialiser.h" #include "private/abstractsingleroleserialiser_p.h" /*! \class AbstractSingleRoleSerialiser \brief The interface for model serialisers saving only one role. */ AbstractSingleRoleSerialiserPrivate::AbstractSingleRoleSerialiserPrivate(AbstractSingleRoleSerialiser* q) : AbstractModelSerialiserPrivate(q) , m_roleToSave(Qt::DisplayRole) { Q_ASSERT(q_ptr); } #ifdef Q_COMPILER_RVALUE_REFS /*! Creates a serialiser moving \a other. */ AbstractSingleRoleSerialiser::AbstractSingleRoleSerialiser(AbstractSingleRoleSerialiser&& other) Q_DECL_NOEXCEPT :AbstractModelSerialiser(static_cast<AbstractModelSerialiser&&>(other)) {} //! Move assignment AbstractSingleRoleSerialiser& AbstractSingleRoleSerialiser::operator=(AbstractSingleRoleSerialiser&& other) { AbstractModelSerialiser::operator=(static_cast<AbstractModelSerialiser&&>(other)); return *this; } #endif // Q_COMPILER_RVALUE_REFS /*! Constructs a serialiser operating over \a model \sa isEmpty() */ AbstractSingleRoleSerialiser::AbstractSingleRoleSerialiser(QAbstractItemModel* model) : AbstractModelSerialiser(*new AbstractSingleRoleSerialiserPrivate(this)) { setModel(model); } /*! \overload loadModel will always fail as the model is not editable */ AbstractSingleRoleSerialiser::AbstractSingleRoleSerialiser(const QAbstractItemModel* model) : AbstractModelSerialiser(*new AbstractSingleRoleSerialiserPrivate(this)) { setModel(model); } /*! \internal */ AbstractSingleRoleSerialiser::AbstractSingleRoleSerialiser(AbstractSingleRoleSerialiserPrivate& d) :AbstractModelSerialiser(d) {} /*! Creates a copy of \a other. */ AbstractSingleRoleSerialiser::AbstractSingleRoleSerialiser(const AbstractSingleRoleSerialiser& other) : AbstractModelSerialiser(*new AbstractSingleRoleSerialiserPrivate(this)) { operator=(other); } /*! Destroys the object. */ AbstractSingleRoleSerialiser::~AbstractSingleRoleSerialiser() QT_MODEL_SERIALISATION_DEFAULT_DESTRUCT /*! Assigns \a other to this object. */ AbstractSingleRoleSerialiser& AbstractSingleRoleSerialiser::operator=(const AbstractSingleRoleSerialiser& other) { if (!d_ptr) d_ptr = new AbstractSingleRoleSerialiserPrivate(this); Q_D(AbstractSingleRoleSerialiser); Q_ASSERT_X(other.d_func(), "AbstractSingleRoleSerialiser", "Trying to access data on moved object"); d->m_roleToSave = other.d_func()->m_roleToSave; AbstractModelSerialiser::operator=(other); return *this; } /*! \property AbstractSingleRoleSerialiser::roleToSave \brief the role that will be serialised by default this property is set to Qt::DisplayRole */ /*! \brief getter of roleToSave property */ int AbstractSingleRoleSerialiser::roleToSave() const { Q_D(const AbstractSingleRoleSerialiser); Q_ASSERT_X(d, "AbstractSingleRoleSerialiser", "Trying to access data on moved object"); return d->m_roleToSave; } /*! \brief setter of roleToSave property */ void AbstractSingleRoleSerialiser::setRoleToSave(int val) { Q_D(AbstractSingleRoleSerialiser); Q_ASSERT_X(d, "AbstractSingleRoleSerialiser", "Trying to access data on moved object"); d->m_roleToSave = val; }
#pragma once #include "VulkanWrapper/VulkanBaseApp.h" class App : vkw::VulkanBaseApp { public: App(vkw::VulkanDevice* pDevice):VulkanBaseApp(pDevice, "App"){}; ~App() {}; void Init(uint32_t width, uint32_t height) override; bool Update(float dTime) override; void Render() override; void Cleanup() override; protected: void AllocateDrawCommandBuffers() override; void BuildDrawCommandBuffers() override; void FreeDrawCommandBuffers() override; };
/* * File: CrazyRandomSword.cpp * Author: Cody * */ #include "CrazyRandomSword.h" //Sword randomly ignores armor from 0 to half of current armor. double CrazyRandomSword::hit(double armor){ double damage = hitPoints - (rand() % int(.5 * armor)); return damage; }
#pragma once #ifndef _DTL_SIMD_INCLUDED #error "Never use <dtl/simd/vec.hpp> directly; include <dtl/simd.hpp> instead." #endif #include "../adept.hpp" #include "../math.hpp" #include <array> #include <bitset> #include <functional> #include <type_traits> namespace dtl { namespace simd { /// Base class for a vector consisting of N primitive values of type Tp template<typename Tp, u64 N> struct base { using type = Tp; static constexpr u64 value = N; static constexpr u64 length = N; }; /// Recursive template to find the largest possible (native) vector implementation. template<typename Tp, u64 N> struct vs : vs<Tp, N / 2> { static_assert(is_power_of_two(N), "Template parameter 'N' must be a power of two."); }; } // namespace simd } // namespace dtl // include architecture dependent implementations... #include "intrinsics.hpp" namespace dtl { namespace simd { /* /// smallest vector type, consisting of 1 component (used when no specialization is found) template<typename T> struct vs<T, 1> { static constexpr u64 value = 1; using type = vec<T, 1>; type data; }; */ /* template<typename T> struct vs<T, 32> { static constexpr u64 value = 32; using type = vec<T, 32>; type data; }; */ struct v_base {}; template<class T> struct is_vector { static constexpr bool value = std::is_base_of<v_base, T>::value; }; /// The general vector class with N components of the (primitive) type Tp. /// /// If there exists a native vector type that can hold N values of type Tp, e.g. __m256i, /// then an instance makes direct use of it. If the N exceeds the size of the largest /// available native vector type an instance will be a composition of multiple (smaller) /// native vectors. template<typename Tp, u64 N> struct v : v_base { static_assert(is_power_of_two(N), "Template parameter 'N' must be a power of two."); // TODO assert fundamental type // TODO unroll loops in compound types - __attribute__((optimize("unroll-loops"))) /// The scalar type using scalar_type = typename std::remove_cv<Tp>::type; /// The overall length of the vector, in terms of number of elements. static constexpr u64 length = N; /// The native vector wrapper that is used under the hood. /// Note: The wrapper determines the largest available native vector type. using nested_vector = vs<scalar_type, N>; // TODO (maybe) make it a template parameter. give the user the possibility to specify the native vector type /// The alignment of the vector. static constexpr std::size_t byte_alignment = std::alignment_of<typename nested_vector::type>::value; /// The length of the native vector, in terms of number of elements. static constexpr u64 nested_vector_length = nested_vector::value; /// The number of nested native vectors, if the vector is a composition of multiple smaller vectors, 1 otherwise. static constexpr u64 nested_vector_cnt = N / nested_vector_length; /// True, if the vector is a composition of multiple native vectors, false otherwise. static constexpr u1 is_compound = (nested_vector_cnt != 1); /// The native vector type (e.g., __m256i). using nested_type = typename nested_vector::type; /// Helper to typedef a compound type. template<typename T_inner, u64 Cnt> using make_compound = typename std::array<T_inner, Cnt>; /// The compound vector type. Note: Is the same as nested_type, if not compound. using compound_type = typename std::conditional<is_compound, make_compound<nested_type, nested_vector_cnt>, nested_type>::type; /// The actual vector data. (the one and only non-static member variable of this class). compound_type data; /// The native 'mask' type of the surrounding vector. using nested_mask_type = typename nested_vector::mask_type; /// The 'mask' type is a composition if the surrounding vector is also a composition. using compound_mask_type = typename std::conditional<is_compound, make_compound<nested_mask_type, nested_vector_cnt>, nested_mask_type>::type; //===----------------------------------------------------------------------===// /// The mask type (template) of the surrounding vector. /// /// As the vector can be a composition of multiple (smaller) native /// vectors, the same applies for the mask type. /// Note, that the mask implementations are architecture dependent. /// /// General rules for working with masks: /// 1) Mask are preferably created by comparison operations and used /// with masked vector operations. Manual construction should be avoided. /// 2) Avoid materialization. Instances should have a very short lifetime /// and are not supposed to be stored in main-memory. Use the 'to_int' /// function to obtain a bitmask represented as an integer. /// 3) Avoid (costly) direct access through the set/get functions. On pre-KNL /// architectures this has a severe performance impact. /// 4) The special functions 'all', 'any' and 'none' are supposed to be /// fast and efficient on all architectures. - Semantics are equal to /// the std::bitset implementations. /// 5) Bitwise operations are supposed to be fast and efficient on all /// architectures. struct m { /// The actual mask data. (the one and only non-static member variable of this class) compound_mask_type data; m() { set<is_compound>(this->data, false); } m(u32 i) { set<is_compound>(this->data, i); } m(const m&) = default; m(m&&) = default; m(compound_mask_type&& d) : data { std::move(d) } {}; m& operator=(const m&) = default; m& operator=(m&&) = default; struct all_fn { constexpr u1 operator()(const nested_mask_type& mask) const { return mask.all(); } constexpr u1 aggr(u1 a, u1 b) const { return a & b; }; }; struct any_fn { constexpr u1 operator()(const nested_mask_type& mask) const { return mask.any(); } constexpr u1 aggr(u1 a, u1 b) const { return a | b; }; }; struct none_fn { constexpr u1 operator()(const nested_mask_type& mask) const { return mask.none(); } constexpr u1 aggr(u1 a, u1 b) const { return a & b; }; }; template<u1 Compound = false, typename Fn> static __forceinline__ u1 op(Fn fn, const nested_mask_type& mask) { return fn(mask); } template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ u1 op(Fn fn, const compound_mask_type& masks) { $u1 result = op<!Compound>(fn, masks[0]); for ($u64 i = 0; i < nested_vector_cnt; i++) { result = fn.aggr(result, op<!Compound>(fn, masks[i])); } return result; } /// Returns true if all boolean values in the mask are true, false otherwise. u1 all() const { return op<is_compound>(all_fn(), data); } /// Returns true if at least one boolean value in the mask is true, false otherwise. u1 any() const { return op<is_compound>(any_fn(), data); } /// Returns true if all boolean values in the mask are false, false otherwise. u1 none() const { return op<is_compound>(none_fn(), data); } /// Sets the bit a position 'idx' to the given 'value'. template<u1 Compound = false> static __forceinline__ void set(nested_mask_type& mask, u64 idx, u1 value) { return mask.set(idx, value); } /// Sets the bit a position 'idx' to the given 'value'. template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ void set(compound_mask_type& masks, u64 idx, u1 value) { u64 m_idx = idx / nested_vector_length; u64 n_idx = idx % nested_vector_length; return set<!Compound>(masks[m_idx], n_idx, value); } /// Sets ALL bits to the given 'value'. template<u1 Compound = false> static __forceinline__ void set(nested_mask_type& mask, u1 value) { mask.set(value); } /// Sets ALL bits to the given 'value'. template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ void set(compound_mask_type& masks, u1 value) { for ($u64 i = 0; i < nested_vector_cnt; i++) { set<!Compound>(masks[i], value); } } template<u1 Compound = false> static __forceinline__ u1 get(const nested_mask_type& mask, u64 idx) { return mask.get(idx); } template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ u1 get(const compound_mask_type& masks, u64 idx) { u64 m_idx = idx / nested_vector_length; u64 n_idx = idx % nested_vector_length; return get<!Compound>(masks[m_idx], n_idx); } /// Sets the mask at position 'idx' to 'true'. Use with caution as this operation might be very expensive. __forceinline__ void set(u64 idx, u1 value) { set<is_compound>(data, idx, value); } /// Gets the boolean value from the mask at position 'idx'. Use with caution as this operation might be very expensive. __forceinline__ u1 get(u64 idx) const { return get<is_compound>(data, idx); } struct bit_and_fn { constexpr nested_mask_type operator()(const nested_mask_type& a, const nested_mask_type& b) const { return a.bit_and(b); } }; struct bit_or_fn { constexpr nested_mask_type operator()(const nested_mask_type& a, const nested_mask_type& b) const { return a.bit_or(b); } }; struct bit_xor_fn { constexpr nested_mask_type operator()(const nested_mask_type& a, const nested_mask_type& b) const { return a.bit_xor(b); } }; struct bit_not_fn { constexpr nested_mask_type operator()(const nested_mask_type& a) const { return a.bit_not(); } }; // binary functions template<u1 Compound = false, typename Fn> static __forceinline__ nested_mask_type bit_op(Fn fn, const nested_mask_type& a, const nested_mask_type& b) { return fn(a, b); } // binary functions template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_mask_type bit_op(Fn fn, const compound_mask_type& a, const compound_mask_type& b) { compound_mask_type result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = bit_op<!Compound>(fn, a[i], b[i]); } return result; } // unary functions template<u1 Compound = false, typename Fn> static __forceinline__ nested_mask_type bit_op(Fn fn, const nested_mask_type& a) { return fn(a); } // unary functions template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_mask_type bit_op(Fn fn, const compound_mask_type& a) { compound_mask_type result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = bit_op<!Compound>(fn, a[i]); } return result; } /// Performs a bitwise AND. __forceinline__ m operator&(const m& o) const { return m { bit_op<is_compound>(bit_and_fn(), data, o.data) }; } __forceinline__ m& operator&=(const m& o) { data = bit_op<is_compound>(bit_and_fn(), data, o.data); return (*this); } /// Performs a bitwise OR. __forceinline__ m operator|(const m& o) const { return m { bit_op<is_compound>(bit_or_fn(), data, o.data) }; } __forceinline__ m& operator|=(const m& o) { data = bit_op<is_compound>(bit_or_fn(), data, o.data); return (*this); } /// Performs a bitwise XOR. __forceinline__ m operator^(const m& o) const { return m { bit_op<is_compound>(bit_xor_fn(), data, o.data) }; } __forceinline__ m& operator^=(const m& o) { data = bit_op<is_compound>(bit_xor_fn(), data, o.data); return (*this); } /// Performs a bitwise negation. __forceinline__ m operator!() const { return m { bit_op<is_compound>(bit_not_fn(), data) }; } /// Returns a mask instance where all components are set to 'true'. static __forceinline__ m make_all_mask() { m result; set<is_compound>(result.data, true); return result; }; /// Returns a mask instance where all components are set to 'false'. static __forceinline__ m make_none_mask() { m result; set<is_compound>(result.data, false); return result; }; /// Converts the mask into a position list and returns the number of elements. (the size of the position list must be at least N) template<u1 Compound = false> static __forceinline__ $u64 to_positions(const nested_mask_type& mask, $u32* position_list, u32 offset) { return mask.to_positions(position_list, offset); } /// Converts the mask into a position list and returns the number of elements. (the size of the position list must be at least N) template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ $u64 to_positions(const compound_mask_type& compound_mask, $u32* position_list, u32 offset) { $u32 match_cnt = 0; $u32* match_writer = position_list; for ($u64 i = 0; i < nested_vector_cnt; i++) { u64 cnt = to_positions<!Compound>(compound_mask[i], match_writer, offset + (nested_vector_length * i)); match_cnt += cnt; match_writer += cnt; } return match_cnt; } /// Converts the mask into a position list and returns the number of elements. (the size of the position list must be at least N) __forceinline__ $u64 to_positions($u32* position_list, u32 offset = 0) const { return to_positions<is_compound>(data, position_list, offset); } /// Converts the mask into an integer. template<u1 Compound = false> static __forceinline__ $u64 to_int(const nested_mask_type& mask) { return mask.to_int(); } /// Converts the mask into an integer. template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ $u64 to_int(const compound_mask_type& compound_mask) { $u64 int_bitmask = 0; for ($u64 i = 0; i < nested_vector_cnt; i++) { u64 t = to_int<!Compound>(compound_mask[i]); int_bitmask |= t << ((N/nested_vector_cnt) * i); } return int_bitmask; } /// Converts the mask into an integer. __forceinline__ $u64 to_int() const { static_assert(N <= 64, "Mask to integer conversion requires the vector length to be less or equal to 64."); return to_int<is_compound>(data); } /// Initializes the mask according to the bits set in the integer. template<u1 Compound = false> static __forceinline__ void from_int(nested_mask_type& mask, u64 int_bitmask) { mask.set_from_int(int_bitmask); } /// Converts the mask into an integer. template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ void from_int(compound_mask_type& compound_mask, u64 int_bitmask) { for ($u64 i = 0; i < nested_vector_cnt; i++) { from_int<!Compound>(compound_mask[i], int_bitmask >> ((N/nested_vector_cnt) * i)); } } /// Creates a mask from an integer. static __forceinline__ m from_int(u64 int_bitmask) { m result; from_int<is_compound>(result.data, int_bitmask); return result; } // // Creates a mask instance from a bitset // template<std::size_t Nb> // static __forceinline__ m // make_from_bitset(const dtl::simd::bitset<Nb> bs) { // static_assert(Nb >= N, "The size of the bitset must greater or equal than the vector length."); // return from_bitset(bs); // } // template<u1 Compound = false, std::size_t Nb> // static __forceinline__ nested_mask_type // from_bitset(const dtl::simd::bitset<Nb>& bs, u64 offset) { // nested_mask_type mask; // mask.set(bs.get(offset, nested_vector_length)); // return mask; // } // template<u1 Compound, std::size_t Nb, typename = std::enable_if_t<Compound>> // static __forceinline__ compound_mask_type // from_bitset(const dtl::simd::bitset<Nb>& bs, u64 offset = 0ull) { // compound_mask_type result; // for ($u64 i = 0; i < length; i += nested_vector_length) { // result[i] = from_bitset<!Compound>(bs, i); // } // return result; // } }; // Public mask API /// The mask type of the surrounding vector. using mask_t = m; using mask = m; // alias for those who don't like '_t's /// Returns a mask instance where all components are set to 'true'. static mask_t make_all_mask() { return mask_t::make_all_mask(); }; /// Returns a mask instance where all components are set to 'false'. static mask_t make_none_mask() { return mask_t::make_none_mask(); }; // --- end of mask //===----------------------------------------------------------------------===// // Specialize function objects for the current native vector type. (reduces verboseness later on) struct op { // template parameters are // 1) primitive type // 2) native vector type // 3) argument type // 4) return type (defaults to vector type) using broadcast = dtl::simd::broadcast<scalar_type, nested_type, scalar_type>; using set = dtl::simd::set<scalar_type, nested_type, nested_type>; using blend = dtl::simd::blend<scalar_type, nested_type, nested_type>; using compress = dtl::simd::compress<scalar_type, nested_type>; using store = dtl::simd::store<scalar_type, nested_type>; using storeu = dtl::simd::storeu<scalar_type, nested_type>; using plus = dtl::simd::plus<scalar_type, nested_type>; using minus = dtl::simd::minus<scalar_type, nested_type>; using multiplies = dtl::simd::multiplies<scalar_type, nested_type>; using shift_left = dtl::simd::shift_left<scalar_type, nested_type, i32>; using shift_left_var = dtl::simd::shift_left_var<scalar_type, nested_type, nested_type>; using shift_right = dtl::simd::shift_right<scalar_type, nested_type, i32>; using shift_right_var = dtl::simd::shift_right_var<scalar_type, nested_type, nested_type>; using bit_and = dtl::simd::bit_and<scalar_type, nested_type>; using bit_or = dtl::simd::bit_or<scalar_type, nested_type>; using bit_xor = dtl::simd::bit_xor<scalar_type, nested_type>; using bit_not = dtl::simd::bit_not<scalar_type, nested_type>; using less = dtl::simd::less<scalar_type, nested_type, nested_type, nested_mask_type>; using less_equal = dtl::simd::less_equal<scalar_type, nested_type, nested_type, nested_mask_type>; using equal = dtl::simd::equal<scalar_type, nested_type, nested_type, nested_mask_type>; using not_equal = dtl::simd::not_equal<scalar_type, nested_type, nested_type, nested_mask_type>; using greater = dtl::simd::greater<scalar_type, nested_type, nested_type, nested_mask_type>; // TODO remove }; //===----------------------------------------------------------------------===// // C'tors //===----------------------------------------------------------------------===// v() = default; __forceinline__ v(const scalar_type scalar_value) { *this = make(scalar_value); } v(compound_type&& d) : data { std::move(d) } {}; v(const v& other) = default; v(v&& other) = default; // template<typename Tp_other> // explicit // v(const v<Tp_other, N>& other) { // for (auto ) // } // brace-initializer list c'tor // template<typename ...T> // explicit // v(T&&... t) : data { std::forward<T>(t)... } { } // // explicit // v(v&& other) : data(std::move(other.data)) { } //===----------------------------------------------------------------------===// /// Assignment __forceinline__ v& operator=(const v& other) = default; __forceinline__ v& operator=(v&& other) = default; /// Assigns the given scalar value to all vector components. __forceinline__ v& operator=(const scalar_type& scalar_value) noexcept { data = unary_op<is_compound>(typename op::broadcast(), data, scalar_value); return *this; } /// Assigns the given scalar value to the vector components specified by the mask. __forceinline__ v& mask_assign(const scalar_type& scalar_value, const m& mask) noexcept { data = unary_op<is_compound>(typename op::blend(), /*data,*/ make(scalar_value).data, data, (!mask).data); return *this; } __forceinline__ v& mask_assign(const v& other, const m& mask) noexcept { data = unary_op<is_compound>(typename op::blend(), /*data,*/ other.data, data, (!mask).data); return *this; } //===----------------------------------------------------------------------===// /// Creates a vector where all components are set to the given scalar value. static __forceinline__ v make(const scalar_type& scalar_value) { v result; result = scalar_value; return std::move(result); } /// Creates a copy of the given vector. static __forceinline__ v make(const v& other) { v result; result.data = other.data; return result; } /// Creates a nested vector with all components set to the given scalar value. /// In other words, the given value is broadcasted to all vector components. static __forceinline__ nested_type make_nested(const scalar_type& scalar_value) { auto fn = typename op::broadcast(); return fn(scalar_value); } //===----------------------------------------------------------------------===// // Unary functions //===----------------------------------------------------------------------===// template<u1 Compound = false, typename Fn> static __forceinline__ nested_type unary_op(Fn op, const nested_type& type_selector, const typename Fn::argument_type& a) noexcept { return op(a); } template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_type unary_op(Fn op, const compound_type& type_selector, const typename Fn::argument_type& a) noexcept { compound_type result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = unary_op<!Compound>(op, result[i], a); } return result; } /// Unary operation: op(native vector) template<u1 Compound = false, typename Fn> static __forceinline__ nested_type unary_op(Fn op, // const nested_type& type_selector, const nested_type& a) noexcept { return op(a); } /// Unary operation (merge masked): op(native vector) template<u1 Compound = false, typename Fn> static __forceinline__ nested_type unary_op(Fn op, // const nested_type& type_selector, const nested_type& a, // merge masking const nested_type& src, const nested_mask_type& mask) noexcept { return op(a, src, mask); } /// Unary operation: op(compound vector) template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_type unary_op(Fn op, // const compound_type& type_selector, const compound_type& a) noexcept { compound_type result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = unary_op<!Compound>(op, a[i]); } return result; } /// Unary operation (merge masked): op(compound vector) template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_type unary_op(Fn op, // const compound_type& type_selector, const compound_type& a, // merge masking const compound_type& src, const compound_mask_type& mask) noexcept { compound_type result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = unary_op<!Compound>(op, a[i], src[i], mask[i]); } return result; } // // optimization // template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> // static __forceinline__ compound_type // unary_op(Fn op, // const compound_type& type_selector, // const nested_type& a) noexcept { // compound_type result; // result[0] = op(a); // for ($u64 i = 1; i < nested_vector_cnt; i++) { // result[i] = result[0]; // } // return result; // } // // optimization // template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> // static __forceinline__ compound_type // unary_op(Fn op, // const compound_type& type_selector, // const nested_type& a, // // merge masking // const compound_type& src, // const m& mask) noexcept { // compound_type result; // for ($u64 i = 0; i < nested_vector_cnt; i++) { // result[i] = op(a, src[i], mask.data[i]); // } // return result; // } //===----------------------------------------------------------------------===// // Binary functions //===----------------------------------------------------------------------===// /// Applies a binary operation to a NON-compound (native) vector type. template<u1 Compound = false, typename Fn> static __forceinline__ typename Fn::result_type binary_op(Fn op, const typename Fn::vector_type& lhs, const typename Fn::vector_type& rhs) noexcept { return op(lhs, rhs); } template<u1 Compound = false, typename Fn> static __forceinline__ typename Fn::result_type binary_op(Fn op, const typename Fn::vector_type& lhs, const typename Fn::vector_type& rhs, // merge masking const typename Fn::vector_type& src, const nested_mask_type& mask) noexcept { return op(lhs, rhs, src, mask); } /// Applies a binary operation to a compound vector type. template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> binary_op(Fn op, const compound_type& lhs, const compound_type& rhs) noexcept { make_compound<typename Fn::result_type, nested_vector_cnt> result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = binary_op<!Compound>(op, lhs[i], rhs[i]); } return result; } template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> binary_op(Fn op, const compound_type& lhs, const compound_type& rhs, // merge masking const compound_type& src, const compound_mask_type& mask) noexcept { make_compound<typename Fn::result_type, nested_vector_cnt> result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = binary_op<!Compound>(op, lhs[i], rhs[i], src[i], mask[i]); } return result; } // // optimization // template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> // static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> // binary_op(Fn op, const nested_type& lhs, // const compound_type& rhs) noexcept { // make_compound<typename Fn::result_type, nested_vector_cnt> result; // for ($u64 i = 0; i < nested_vector_cnt; i++) { // result[i] = binary_op(op, lhs, rhs[i]); // } // return result; // } // template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> // static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> // binary_op(Fn op, const nested_type& lhs, // const compound_type& rhs, // // merge masking // const compound_type& src, // const compound_mask_type& mask) noexcept { // make_compound<typename Fn::result_type, nested_vector_cnt> result; // for ($u64 i = 0; i < nested_vector_cnt; i++) { // result[i] = binary_op(op, lhs, rhs[i], src[i], mask[i]); // } // return result; // } /// Applies an operation of type: vector op scalar /// The scalar value needs to be broadcasted to all SIMD lanes first. /// Note: This is an optimization for compound vectors. template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>, typename = std::enable_if_t<Compound>> // TODO why twice? static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> binary_op(Fn op, const compound_type& lhs, const nested_type& rhs) noexcept { make_compound<typename Fn::result_type, nested_vector_cnt> result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = binary_op(op, lhs[i], rhs); } return result; } template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>, typename = std::enable_if_t<Compound>> // TODO why twice? static __forceinline__ make_compound<typename Fn::result_type, nested_vector_cnt> binary_op(Fn op, const compound_type& lhs, const nested_type& rhs, // merge masking const compound_type& src, const compound_mask_type& mask) noexcept { make_compound<typename Fn::result_type, nested_vector_cnt> result; for ($u64 i = 0; i < nested_vector_cnt; i++) { result[i] = binary_op(op, lhs[i], rhs, src[i], mask[i]); } return result; } // template<typename Fn> // static __forceinline__ nested_type // binary_op(Fn op, const nested_type& lhs, i32& rhs) noexcept { // return op(lhs, rhs); // } // /// Applies an operation of type: vector op scalar (w/o broadcasting the value to all SIMD lanes) // template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> // static __forceinline__ compound_type // binary_op(Fn op, const compound_type& lhs, i32& rhs) noexcept { // compound_type result; // for ($u64 i = 0; i < nested_vector_cnt; i++) { // result[i] = binary_op(op, lhs[i], rhs); // } // return result; // } //===----------------------------------------------------------------------===// // Compress (aka left-pack) //===----------------------------------------------------------------------===// template<u1 Compound = false, typename Fn> static __forceinline__ nested_type compress_op(Fn fn, const nested_type& a, const nested_mask_type& m) noexcept { return fn(a, m); } template<u1 Compound, typename Fn, typename = std::enable_if_t<Compound>> static __forceinline__ compound_type compress_op(Fn fn, const compound_type& a, const compound_mask_type m) noexcept { compound_type result; scalar_type* writer = reinterpret_cast<scalar_type*>(&result); uint32_t pop_cnt_0 = 0; nested_type r_0 = fn(a[0], m[0], pop_cnt_0); auto store_fn = typename op::store(); store_fn(reinterpret_cast<nested_type*>(writer), r_0); // first store is aligned writer += pop_cnt_0; for ($u64 i = 1; i < nested_vector_cnt; i++) { uint32_t pop_cnt = 0; nested_type r = fn(a[i], m[i], pop_cnt); auto storeu_fn = typename op::storeu(); storeu_fn(writer, r); writer += pop_cnt; } return result; } v compress(const m& mask) { return compress_op<is_compound>(typename op::compress(), data, mask.data); } //===----------------------------------------------------------------------===// template<typename VECTOR_FN> __forceinline__ v map(const v& o) const noexcept { return v { binary_op<is_compound, VECTOR_FN>(VECTOR_FN(), data, o.data) }; } template<typename VECTOR_FN> __forceinline__ v map(const scalar_type& s) const noexcept { return v { binary_op<is_compound, VECTOR_FN>(VECTOR_FN(), data, make_nested(s)) }; } __forceinline__ v operator+(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, o.data) }; } __forceinline__ v operator+(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, make_nested(s)) }; } __forceinline__ v operator+() const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, make_nested(0)) }; } __forceinline__ v& operator+=(const v& o) noexcept { data = binary_op<is_compound>(typename op::plus(), data, o.data); return *this; } __forceinline__ v& operator+=(const scalar_type& s) noexcept { data = binary_op<is_compound>(typename op::plus(), data, make_nested(s)); return *this; } __forceinline__ v mask_plus(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_plus(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v mask_plus(const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::plus(), data, make_nested(0), data, op_mask.data) }; } __forceinline__ v& mask_assign_plus(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::plus(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_plus(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::plus(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator-(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::minus(), data, o.data) }; } __forceinline__ v operator-(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::minus(), data, make_nested(s)) }; } __forceinline__ v operator-() const noexcept { return v { binary_op<is_compound>(typename op::minus(), make_nested(0), data) }; } __forceinline__ v& operator-=(const v& o) noexcept { data = binary_op<is_compound>(typename op::minus(), data, o.data); return (*this); } __forceinline__ v& operator-=(const scalar_type& s) noexcept { data = binary_op<is_compound>(typename op::minus(), data, make_nested(s)); return (*this); } __forceinline__ v mask_minus(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::minus(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_minus(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::minus(), data, make_nested(s), data, op_mask.data) }; } // __forceinline__ v mask_minus(const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::minus(), make_nested(0), data, data, op_mask.data) }; } __forceinline__ v mask_minus(const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::minus(), make(0).data, data, data, op_mask.data) }; } __forceinline__ v& mask_assign_minus(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::minus(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_minus(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::minus(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator*(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::multiplies(), data, o.data) }; } __forceinline__ v operator*(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::multiplies(), data, make_nested(s)) }; } __forceinline__ v& operator*=(const v& o) noexcept { data = binary_op<is_compound>(typename op::multiplies(), data, o.data); return (*this); } __forceinline__ v& operator*=(const scalar_type& s) noexcept { data = binary_op<is_compound>(typename op::multiplies(), data, make_nested(s)); return (*this); } __forceinline__ v mask_multiplies(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::multiplies(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_multiplies(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::multiplies(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_multiplies(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::multiplies(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_multiplies(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::multiplies(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator<<(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::shift_left_var(), data, o.data) }; } __forceinline__ v operator<<(const i32& s) const noexcept { return v { binary_op<is_compound>(typename op::shift_left_var(), data, make_nested(s)) }; } // TODO optimize __forceinline__ v& operator<<=(const v& o) noexcept { data = binary_op<is_compound>(typename op::shift_left_var(), data, o.data); return (*this); } __forceinline__ v& operator<<=(const i32& s) noexcept { data = binary_op<is_compound>(typename op::shift_left_var(), data, make_nested(s)); return (*this); } template<typename Trhs, typename = std::enable_if_t<is_vector<Trhs>::value>> __forceinline__ v operator<<(const Trhs& o) const noexcept { v rhs; for ($u64 i = 0; i < N; i++) { rhs.insert(o[i], i); } return v { binary_op<is_compound>(typename op::shift_left_var(), data, rhs.data) }; } __forceinline__ v mask_shift_left(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::shift_left_var(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_shift_left(const i32& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::shift_left(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_shift_left(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::shift_left_var(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_shift_left(const i32& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::shift_left(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator>>(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::shift_right_var(), data, o.data) }; } __forceinline__ v operator>>(const i32& s) const noexcept { return v { binary_op<is_compound>(typename op::shift_right_var(), data, make_nested(s)) }; } // TODO optimize __forceinline__ v& operator>>=(const v& o) noexcept { data = binary_op<is_compound>(typename op::shift_right_var(), data, o.data); return (*this); } __forceinline__ v& operator>>=(const i32& s) noexcept { data = binary_op<is_compound>(typename op::shift_right(), data, make_nested(s)); return (*this); } __forceinline__ v mask_shift_right(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::shift_right_var(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_shift_right(const i32& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::shift_right(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_shift_right(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::shift_right_var(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_shift_right(const i32& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::shift_right(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator&(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::bit_and(), data, o.data) }; } __forceinline__ v operator&(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::bit_and(), data, make_nested(s)) }; } __forceinline__ v& operator&=(const v& o) noexcept { data = binary_op<is_compound>(typename op::bit_and(), data, o.data); return (*this); } __forceinline__ v& operator&=(const scalar_type& s) noexcept { data = binary_op<is_compound>(typename op::bit_and(), data, make_nested(s)); return (*this); } __forceinline__ v mask_bit_and(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_and(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_bit_and(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_and(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_bit_and(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_and(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_bit_and(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_and(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator|(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::bit_or(), data, o.data) }; } __forceinline__ v operator|(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::bit_or(), data, make_nested(s)) }; } __forceinline__ v& operator|=(const v& o) noexcept { data = binary_op<is_compound>(typename op::bit_or(), data, o.data); return (*this); } __forceinline__ v& operator|=(const i32& s) noexcept { data = binary_op<is_compound>(typename op::bit_or(), data, make_nested(s)); return (*this); } __forceinline__ v mask_bit_or(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_or(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_bit_or(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_or(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_bit_or(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_or(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_bit_or(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_or(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v operator^(const v& o) const noexcept { return v { binary_op<is_compound>(typename op::bit_xor(), data, o.data) }; } __forceinline__ v operator^(const scalar_type& s) const noexcept { return v { binary_op<is_compound>(typename op::bit_xor(), data, make_nested(s)) }; } __forceinline__ v& operator^=(const v& o) noexcept { data = binary_op<is_compound>(typename op::bit_xor(), data, o.data); return (*this); } __forceinline__ v& operator^=(const scalar_type& s) noexcept { data = binary_op<is_compound>(typename op::bit_xor(), data, make_nested(s)); return (*this); } __forceinline__ v mask_bit_xor(const v& o, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_xor(), data, o.data, data, op_mask.data) }; } __forceinline__ v mask_bit_xor(const scalar_type& s, const m& op_mask) const noexcept { return v { binary_op<is_compound>(typename op::bit_xor(), data, make_nested(s), data, op_mask.data) }; } __forceinline__ v& mask_assign_bit_xor(const v& o, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_xor(), data, o.data, data, op_mask.data ); return *this; } __forceinline__ v& mask_assign_bit_xor(const scalar_type& s, const m& op_mask) noexcept { data = binary_op<is_compound>(typename op::bit_xor(), data, make_nested(s), data, op_mask.data ); return *this; } __forceinline__ v zero_mask(const m& mask) { return v {unary_op<is_compound>(typename op::blend(), /*data,*/ make(0).data, data, (!mask).data) }; } __forceinline__ v operator~() const noexcept { return v { unary_op<is_compound>(typename op::bit_not(), data) }; } static __forceinline__ scalar_type extract(const nested_type& native_vector, u64 idx) noexcept { return reinterpret_cast<const scalar_type*>(&native_vector)[idx]; // TODO improve performance } template<typename T, typename = std::enable_if_t<(sizeof(T), is_compound)>> static __forceinline__ scalar_type extract(const T& compound_vector, u64 idx) noexcept { return extract(compound_vector[idx / nested_vector_length], idx % nested_vector_length); } template<u1 Compound = false> static __forceinline__ void insert(nested_type& native_vector, const scalar_type& value, u64 idx) noexcept { reinterpret_cast<scalar_type*>(&native_vector)[idx] = value; // TODO improve performance } template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ void insert(compound_type& compound_vector, const scalar_type& value, u64 idx) noexcept { insert<!Compound>(compound_vector[idx / nested_vector_length], value, idx % nested_vector_length); } __forceinline__ void insert(const scalar_type& value, u64 idx) noexcept { insert<is_compound>(data, value, idx); } /// Read-only access to the individual vector components scalar_type operator[](u64 idx) const noexcept { return extract(data, idx); } // --- // Comparisons __forceinline__ m operator<(const v& o) const noexcept { return m { binary_op<is_compound>(typename op::less(), data, o.data) }; } __forceinline__ m operator<(const scalar_type& s) const noexcept { return m { binary_op<is_compound>(typename op::less(), data, make_nested(s)) }; } __forceinline__ m operator<=(const v& o) const noexcept { return m { binary_op<is_compound>(typename op::less_equal(), data, o.data) }; } __forceinline__ m operator<=(const scalar_type& s) const noexcept { return m { binary_op<is_compound>(typename op::less_equal(), data, make_nested(s)) }; } __forceinline__ m operator>(const v& o) const noexcept { return m { binary_op<is_compound>(typename op::greater(), data, o.data) }; } __forceinline__ m operator>(const scalar_type& s) const noexcept { return m { binary_op<is_compound>(typename op::greater(), data, make_nested(s)) }; } __forceinline__ m operator==(const v& o) const noexcept { return m { binary_op<is_compound>(typename op::equal(), o.data, data) }; } __forceinline__ m operator==(const scalar_type& s) const noexcept { return m { binary_op<is_compound>(typename op::equal(), data, make_nested(s)) }; } __forceinline__ m operator!=(const v& o) const noexcept { return m { binary_op<is_compound>(typename op::not_equal(), o.data, data) }; } __forceinline__ m operator!=(const scalar_type& s) const noexcept { return m { binary_op<is_compound>(typename op::not_equal(), data, make_nested(s)) }; } // --- // load // TODO rename to gather // template<u1 Compound, typename scalar_type> // static __forceinline__ nested_type // __gather__(const scalar_type* const base_addr, // const typename Tiv& idxs) { // return gather<scalar_type, typename Tiv::nested_type, typename Tiv::nested_type>()(base_addr, idxs.data); // } // // template<u1 Compound, typename Tiv, typename = std::enable_if_t<Compound>> // static __forceinline__ compound_type // __gather__(const scalar_type* const base_addr, // const typename Tiv::compound_type& idxs) { // compound_type result; // for ($u64 i = 0; i < nested_vector_cnt; i++) { // result[i] = __gather<!Compound, Tiv>(base_addr, idxs.data[i]); // } // return result; // } // // template<typename Trv, typename Tiv> // result vector type, index vector type // static __forceinline__ Trv // __gather(const typename Trv::scalar_type* const base_addr, // const typename Tiv& idxs) { // return Trv { Trv::__gather__<Tiv::is_compound, Trv::scalar_type>(base_addr, idxs.data) }; // } // // // template<typename T> // v<T, N> load(const T* const base_addr) const { // using result_t = v<T, N>; // static_assert(result_t::nested_vector_length == nested_vector_length, "BAM"); // static_assert(result_t::nested_vector_cnt == nested_vector_cnt, "BAM"); // return result_t { load<is_compound, T>(base_addr, data) }; // } // // template<typename T> //// v<T, N, vs<T, nested_vector_length>> // v<T, N> load() const { // using result_t = v<T, N>; // static_assert(result_t::nested_vector_length == nested_vector_length, "BAM"); // static_assert(result_t::nested_vector_cnt == nested_vector_cnt, "BAM"); // return result_t { load<is_compound, T>(nullptr, data) }; // } // --- // store template<u1 Compound = false, typename T> static __forceinline__ typename v<T, N>::nested_type store(T* const base_addr, const nested_type& where_idxs, const typename v<T, N>::nested_type what) { return scatter<scalar_type, nested_type, T>()(base_addr, where_idxs, what); } template<u1 Compound = false, typename T> static __forceinline__ typename v<T, N>::nested_type store(T* const base_addr, const nested_type& where_idxs, const typename v<T, N>::nested_type what, const nested_mask_type& mask) { return scatter<scalar_type, nested_type, T>()(base_addr, where_idxs, what, mask); } template<u1 Compound, typename T, typename = std::enable_if_t<Compound>> static __forceinline__ void store(T* const base_addr, const compound_type& where_idxs, const typename v<T, N>::compound_type& what) { for ($u64 i = 0; i < nested_vector_cnt; i++) { store<is_compound>(base_addr, where_idxs[i], what[i]); } } template<u1 Compound, typename T, typename = std::enable_if_t<Compound>> static __forceinline__ void store(T* const base_addr, const compound_type& where_idxs, const typename v<T, N>::compound_type& what, const compound_mask_type& mask) { for ($u64 i = 0; i < nested_vector_cnt; i++) { store<is_compound>(base_addr, where_idxs[i], what[i], mask[i]); } } template<typename T> __forceinline__ void store(T* const base_address, const v<T, N>& what) { store<is_compound>(base_address, data, what.data); } template<typename T> __forceinline__ void store(T* const base_address, const v<T, N>& what, const m& mask) { store<is_compound>(base_address, data, what.data, mask.data); } /// Unaligned store template<u1 Compound = false> static __forceinline__ void storeu(Tp* const address, const nested_type& what) noexcept { typename op::storeu fn; return fn(address, what); } template<u1 Compound, typename = std::enable_if_t<Compound>> static __forceinline__ void storeu(Tp* const address, const compound_type& what) noexcept { for ($u64 i = 0; i < nested_vector_cnt; i++) { storeu<!Compound>(address, what[i]); } } __forceinline__ void storeu(Tp* const address) const { storeu<is_compound>(address, data); } // --- // helper void print(std::ostream& os) const { os << "[" << (*this)[0]; for ($u64 i = 1; i < length; i++) { os << ", "; os << (*this)[i]; } os << "]"; } template<u64... Idxs> static constexpr v make_index_vector(std::array<scalar_type, N>* const arr, integer_sequence<Idxs...>) { *arr = { Idxs... }; } static constexpr v make_index_vector() { v result = make(0); std::array<scalar_type, N>* const arr = reinterpret_cast<std::array<scalar_type, N>*>(&result.data); make_index_vector(arr, make_integer_sequence<N>()); return result; }; //TODO implement casts in SIMD template<typename Tp_target> __forceinline__ v<Tp_target, N> cast() const { v<Tp_target, N> result; for ($u64 i = 0; i < N; i++) { result.insert((*this)[i], i); } return result; } // --- syntactic sugar for masked operations struct masked_reference { v& vector; m mask; // m(u32 i) { // set<is_compound>(this->data, i); // } // masked_reference(const masked_reference&) = default; // masked_reference(masked_reference&&) = default; // masked_reference(compound_mask_type&& d) : data { std::move(d) } {}; // masked_reference& operator=(const masked_reference&) = default; // masked_reference& operator=(masked_reference&&) = default; __forceinline__ v& operator=(const v& o) { vector.mask_assign(o, mask); return vector; } __forceinline__ v& operator=(const scalar_type& s) { vector.mask_assign(s, mask); return vector; } __forceinline__ v operator+(const v& o) const noexcept { return vector.mask_plus(o, mask); } __forceinline__ v operator+(const scalar_type& s) const noexcept { return vector.mask_plus(s, mask); } __forceinline__ v operator+() const noexcept { return vector.mask_plus(mask); } __forceinline__ v& operator+=(const v& o) noexcept { vector.mask_assign_plus(o,mask); return vector; } __forceinline__ v& operator+=(const scalar_type& s) noexcept { vector.mask_assign_plus(s,mask); return vector; } __forceinline__ v operator-(const v& o) const noexcept { return vector.mask_minus(o, mask); } __forceinline__ v operator-(const scalar_type& s) const noexcept { return vector.mask_minus(s, mask); } __forceinline__ v operator-() const noexcept { return vector.mask_minus(mask); } __forceinline__ v& operator-=(const v& o) noexcept { vector.mask_assign_minus(o, mask); return vector; } __forceinline__ v& operator-=(const scalar_type& s) noexcept { vector.mask_assign_minus(s, mask); return vector; } __forceinline__ v operator*(const v& o) const noexcept { return vector.mask_multiplies(o, mask); } __forceinline__ v operator*(const scalar_type& s) const noexcept { return vector.mask_multiplies(s, mask); } __forceinline__ v& operator*=(const v& o) noexcept { vector.mask_assign_multiplies(o, mask); return vector; } __forceinline__ v& operator*=(const scalar_type& s) noexcept { vector.mask_assign_multiplies(s, mask); return vector; } __forceinline__ v operator<<(const v& o) const noexcept { return vector.mask_shift_left(o, mask); } __forceinline__ v operator<<(const scalar_type& s) const noexcept { return vector.mask_shift_left(s, mask); } __forceinline__ v& operator<<=(const v& o) noexcept { vector.mask_assign_shift_left(o, mask); return vector; } __forceinline__ v& operator<<=(const scalar_type& s) noexcept { vector.mask_assign_shift_left(s, mask); return vector; } __forceinline__ v operator>>(const v& o) const noexcept { return vector.mask_shift_right(o, mask); } __forceinline__ v operator>>(const scalar_type& s) const noexcept { return vector.mask_shift_right(s, mask); } __forceinline__ v& operator>>=(const v& o) noexcept { vector.mask_assign_shift_right(o, mask); return vector; } __forceinline__ v& operator>>=(const scalar_type& s) noexcept { vector.mask_assign_shift_right(s, mask); return vector; } __forceinline__ v operator&(const v& o) const noexcept { return vector.mask_bit_and(o, mask); } __forceinline__ v operator&(const scalar_type& s) const noexcept { return vector.mask_bit_and(s, mask); } __forceinline__ v& operator&=(const v& o) noexcept { vector.mask_assign_bit_and(o, mask); return vector; } __forceinline__ v& operator&=(const scalar_type& s) noexcept { vector.mask_assign_bit_and(s, mask); return vector; } __forceinline__ v operator|(const v& o) const noexcept { return vector.mask_bit_or(o, mask); } __forceinline__ v operator|(const scalar_type& s) const noexcept { return vector.mask_bit_or(s, mask); } __forceinline__ v& operator|=(const v& o) noexcept { vector.mask_assign_bit_or(o, mask); return vector; } __forceinline__ v& operator|=(const scalar_type& s) noexcept { vector.mask_assign_bit_or(s, mask); return vector; } __forceinline__ v operator^(const v& o) const noexcept { return vector.mask_bit_xor(o, mask); } __forceinline__ v operator^(const scalar_type& s) const noexcept { return vector.mask_bit_xor(s, mask); } __forceinline__ v& operator^=(const v& o) noexcept { vector.mask_assign_bit_xor(o, mask); return vector; } __forceinline__ v& operator^=(const scalar_type& s) noexcept { vector.mask_assign_bit_xor(s, mask); return vector; } }; __forceinline__ masked_reference operator[](const m& op_mask) noexcept { // return masked_reference{ *this, m{op_mask.data} }; return masked_reference{ *this, op_mask }; } // __forceinline__ masked_reference // operator[](const typename v<$u32, N>::m op_mask) noexcept { // //static_assert(std::is_same<typename v<$u32, N>::m::type, m::type>::value, "Mask is not compatible with this vector."); // return masked_reference{ *this, m{op_mask.data} }; // } // // __forceinline__ masked_reference // operator[](const typename v<$u64, N>::m op_mask) noexcept { // //static_assert(std::is_same<typename v<$u32, N>::m::type, m::type>::value, "Mask is not compatible with this vector."); // return masked_reference{ *this, m{op_mask.data} }; // } // TODO specialize for all valid primitive types // --- }; /// left shift of the form of: scalar << vector template<typename T, u64 N> v<T, N> operator<<(const T& lhs, const v<T, N>& rhs) { v<T, N> lhs_vec = v<T, N>::make(lhs); return lhs_vec << rhs; } template<typename Tlhs, typename Trhs, typename = std::enable_if_t<is_vector<Trhs>::value>> __forceinline__ Tlhs operator<<(const Tlhs& lhs, const Trhs& o) noexcept { Tlhs rhs; for ($u64 i = 0; i < Tlhs::length; i++) { rhs.insert(o[i], i); } return lhs << rhs; } // not sure if this is causing problems... template<typename Tl, typename T, u64 N> v<T, N> operator<<(const Tl& lhs, const v<T, N>& rhs) { v<T, N> lhs_vec = v<T, N>::make(Tl(lhs)); return lhs_vec << rhs; } } // namespace simd // --- Gather --- namespace { template<u1 Compound = false, typename Tp, // the primitive data type typename Trv, // the return vector type typename Tiv> // the index vector type static __forceinline__ typename Trv::nested_type __gather(const Tp* const base_addr, const typename Tiv::nested_type& idxs) { return simd::gather<Tp, typename Tiv::nested_type, typename Tiv::nested_type>()(base_addr, idxs); } template<u1 Compound, typename Tp, // the primitive data type typename Trv, // the return vector type typename Tiv, // the index vector type typename = std::enable_if_t<Compound>> static __forceinline__ typename Trv::compound_type __gather(const Tp* const base_addr, const typename Tiv::compound_type& idxs) { typename Trv::compound_type result; for ($u64 i = 0; i < Tiv::nested_vector_cnt; i++) { result[i] = __gather<!Compound, Tp, Trv, Tiv>(base_addr, idxs[i]); } return result; } } // anonymous namespace /// Gathers values of primitive type Tp from the /// base address + offsets stored in vector Tiv template<typename Tp, // primitive value type typename Tiv> // index vector static __forceinline__ simd::v<Tp, Tiv::length> gather(const Tp* const base_addr, const Tiv& idxs) { using return_vec_t = simd::v<Tp, Tiv::length>; using index_vec_t = Tiv; auto data = __gather<index_vec_t::is_compound, Tp, return_vec_t, index_vec_t>(base_addr, idxs.data); return return_vec_t { data }; } /// Gathers values of primitive type Tp from the /// absolute addresses stored in vector Tiv template<typename Tp, // primitive value type typename Tiv> // index vector static __forceinline__ simd::v<Tp, Tiv::length> gather(const Tiv& idxs) { using return_vec_t = simd::v<Tp, Tiv::length>; using index_vec_t = Tiv; auto data = __gather<index_vec_t::is_compound, Tp, return_vec_t, index_vec_t>(0, idxs.data); return return_vec_t { data }; } // --- Scatter --- namespace { template<u1 Compound = false, typename Tp, // the primitive data type typename Tiv, // the index vector type typename Tvv> // the value vector type static __forceinline__ void __scatter(Tp* base_addr, const typename Tiv::nested_type& idxs, const typename Tvv::nested_type& vals) { simd::scatter<Tp, typename Tiv::nested_type, typename Tvv::nested_type>()(base_addr, idxs, vals); } template<u1 Compound, typename Tp, // the primitive data type typename Tiv, // the index vector type typename Tvv, // the value vector type typename = std::enable_if_t<Compound>> static __forceinline__ void __scatter(Tp* base_addr, const typename Tiv::compound_type& idxs, const typename Tvv::compound_type& vals) { for ($u64 i = 0; i < Tiv::nested_vector_cnt; i++) { __scatter<!Compound, Tp, Tiv, Tvv>(base_addr, idxs[i], vals[i]); } } } // anonymous namespace /// Scatters values of primitive type Tp to /// base address + offsets stored in vector Tiv template<typename Tp, // primitive value type typename Tiv, // index vector typename Tvv> // value vector static __forceinline__ void scatter(const Tvv& vals, Tp* base_addr, const Tiv& idxs) { using index_vec_t = Tiv; using value_vec_t = Tvv; __scatter<index_vec_t::is_compound, Tp, index_vec_t, value_vec_t>(base_addr, idxs.data, vals.data); } //===----------------------------------------------------------------------===// // Type conversion //===----------------------------------------------------------------------===// //TODO implement casts in SIMD template<typename Tp_target, typename Tp_source, std::size_t N> __forceinline__ dtl::simd::v<Tp_target, N> cast(const dtl::simd::v<Tp_source, N> src) { dtl::simd::v<Tp_target, N> result; for ($u64 i = 0; i < N; i++) { result.insert(src[i], i); } return result; } template<typename Tm_dst, typename Tm_src> __forceinline__ Tm_dst cast_mask(const Tm_src& src_mask) { return Tm_dst::from_int(src_mask.to_int()); }; //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Type support //===----------------------------------------------------------------------===// template<class T> struct is_vector { static constexpr bool value = std::is_base_of<dtl::simd::v_base, T>::value; }; namespace internal { template<typename Tv, std::size_t _vector_length = Tv::length> struct vector_len_helper { static constexpr std::size_t value = _vector_length; }; } // namespace internal template<typename Tv> struct vector_length { static_assert(is_vector<Tv>::value, "The given type is not a vector."); static constexpr std::size_t value = internal::vector_len_helper<Tv>::value; }; //===----------------------------------------------------------------------===// } // namespace dtl
#include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> #include <string> using namespace std; int main() { srand(19910724); for (int testcase = 0; testcase < 10; ++ testcase) { char filename[100]; sprintf(filename, "test/%d.in", testcase); FILE* out = fopen(filename, "w"); int n = testcase < 5 ? 1000 : 100000; int vocab = testcase < 6 ? rand() % 26 + 1 : 10 - testcase; string s = ""; for (int i = 0; i < n; ++ i) { char x = rand() % vocab + 'a'; s += x; } fprintf(out, "%s\n", s.c_str()); int m = 10000; fprintf(out, "%d\n", m); for (int i = 0; i < m; ++ i) { int length = rand() % 50 + 51; int start = rand() % (s.size() - length + 1); for (int j = 0; j < length; ++ j) { fprintf(out, "%c", s[start + j]); } fprintf(out, "\n"); } fclose(out); char ansfilename[100]; sprintf(ansfilename, "test/%d.ans", testcase); char command[200]; sprintf(command, "./string < %s > %s", filename, ansfilename); system(command); } return 0; }
/* CAN Receive and Decode Line Follower message created 2/17/19 BD */ #include <mcp_can.h> #include <SPI.h> long unsigned int rxId; unsigned char len = 0; unsigned char rxBuf[8]; char msgString[128]; // Array to store serial string unsigned long prevTX = 0; // Variable to store last execution time const unsigned int invlTX = 1000; // One second interval constant #define CAN0_INT 30 // Set INT to pin PB22 (TXD for Arduino, RXD_INT for mine) MCP_CAN CAN0(8); // Set CS to pin 8 // MCP25625 RESET #define TXD_RST 31 #define LED 13 int loop_cnt = 0; byte data[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; /* Calculate CAN ID for Line Follower msg transmission The Manufacturer (8 bits) The Device Type (5 bits) An API ID (10 bits) The Device ID (6 bits) For Team created modules, FIRST says that Manufacturer - HAL_CAN_Man_kTeamUse = 8 Device Type - HAL_CAN_Dev_kMiscellaneous = 10 API ID is up to us Device ID is unique to each module of a specific type (e.g., we can have more than 1 line follower) CAN ID: (Mfr ID): 0000 1000 (Device Type): 01010 (API ID): 00 0000 0000 (Device ID):00 0001 CAN ID: 0 0001 0000 1010 0000 0000 0000 0001 which is: 0x010a0001 */ #define CAN_ID 0x010a0001 // CAN MASK is 1 bits in all 29 bit positions, except for the Device ID #define CAN_MASK 0x01ffffc0 // all CAN followers will have the following result when ANDed with the CAN_MASK #define CAN_FOLLOWER 0x010a0000 #define NUM_SENSORS 32 // number of sensors used int sensorOutput[NUM_SENSORS]; // 1 or 0 // position of center of tape in inches float fpos = 0; // TOF sensor distance int tof_distance = 0; void decodeLineFollowerMsg() { int i; int j; char stemp[80]; int16_t i16; // decode sensorOutput[] from bytes 0-3 for(i = 0; i < 4; i++) { // get 8 sensor values from each byte for(j = 0; j < 8; j++) { sensorOutput[i * 8 + j] = (rxBuf[i] >> (7 - j)) & 0x01; } } for(i = 0; i < NUM_SENSORS; i++) { Serial.print(sensorOutput[i]); Serial.print(" "); } Serial.println(); // decode position // first, get the value as sent i16 = (rxBuf[4] << 8) | rxBuf[5]; sprintf(stemp, "pos (as sent): %d", i16); Serial.println(stemp); fpos = (i16 * 8.0)/25.4; // convert to inches - 8mm per sensor Serial.print("pos (inches): "); Serial.println(fpos); // decode time of flight distance tof_distance = (rxBuf[6] << 8) | rxBuf[7]; sprintf(stemp, "tof_distance: %d", tof_distance); Serial.println(stemp); Serial.println(); } void setup() { pinMode(LED, OUTPUT); digitalWrite(LED, 1); Serial.begin(115200); // so we can see the startup messages while(!Serial) ; Serial.println("starting..."); // CAN chip RESET line pinMode(TXD_RST, OUTPUT); // reset CAN chip digitalWrite(TXD_RST, 0); delay(100); digitalWrite(TXD_RST, 1); delay(500); // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled. if(CAN0.begin(MCP_ANY, CAN_1000KBPS, MCP_16MHZ) == CAN_OK) Serial.println("MCP2515 Initialized Successfully!"); else Serial.println("Error Initializing MCP2515..."); CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks to received data. // CAN0.setMode(MCP_LISTENONLY); // enable SOF output on CLKOUT for logic analyzer CAN0.setSOF_output(); pinMode(CAN0_INT, INPUT_PULLUP); // Configuring pin for /INT input Serial.println("CAN receive and decode line follower msg..."); Serial.print("CAN0_INT: "); Serial.println(digitalRead(CAN0_INT)); delay(1000); digitalWrite(LED, 0); } void loop() { int ret; // Serial.print("REC: "); // Serial.println(CAN0.errorCountRX()); // Serial.print("CAN0_INT: "); // Serial.println(digitalRead(CAN0_INT)); ret = digitalRead(CAN0_INT); // if(ret == CAN_OK) if(ret == 0) { // Serial.println("msg recvd"); CAN0.readMsgBuf(&rxId, &len, rxBuf); // Read data: len = data length, buf = data byte(s) if(rxId != 0x00000000) { // got something if((rxId & 0x80000000) == 0x80000000) { // Determine if ID is standard (11 bits) or extended (29 bits) sprintf(msgString, "Extended ID: 0x%.8lX DLC: %1d Data:", (rxId & 0x1FFFFFFF), len); } else { sprintf(msgString, "Standard ID: 0x%.3lX DLC: %1d Data:", rxId, len); } Serial.print(msgString); if((rxId & 0x40000000) == 0x40000000) { // Determine if message is a remote request frame. sprintf(msgString, " REMOTE REQUEST FRAME"); Serial.print(msgString); } else { for(byte i = 0; i<len; i++) { sprintf(msgString, " 0x%.2X", rxBuf[i]); Serial.print(msgString); } } Serial.println(); if(((rxId & CAN_ID) & CAN_MASK) == CAN_FOLLOWER) { // message from a line follower decodeLineFollowerMsg(); } } } } /********************************************************************************************************* END FILE *********************************************************************************************************/
#include "func.h" void gen_key(unsigned char *k, int r){ for(int i = 0; i < r; ++i) k[i] = rand() % 255; } void init(unsigned char *s, unsigned char *k, const int r){ unsigned char q = 0, temp; for(unsigned char i = 0; i < 255; ++i) s[i] = i; s[255] = 255; for(unsigned char i = 0; i < 255; ++i){ q += s[i] + k[i % r] ; temp = s[i]; s[i] = s[q]; s[q] = temp; } q += s[255] + k[255] % r; temp = s[255]; s[255] = s[q]; s[q] = temp; } unsigned char get_gamma(unsigned char *q1, unsigned char *q2, unsigned char *s){ unsigned char temp; ++(*q1); *q2 += s[*q1]; temp = s[*q1]; s[*q1] = s[*q2]; s[*q2] = temp; return s[s[*q1] + s[*q2]]; } void encode(unsigned char *plain_text, int size, unsigned char *k, int r){ unsigned char s[256]; unsigned char q1 = 0, q2 = 0; init(s, k, r); for(int i = 0; i < 768; ++i) get_gamma(&q1, &q2, s); for(int i = 0; i < size; ++i) plain_text[i] ^= get_gamma(&q1, &q2, s); } void decode(unsigned char *plain_text, int size, unsigned char *k, int r){ encode(plain_text, size, k, r); }
/* * 부분 문자열 길이가 고정이므로 a,c,g 세개의 빈도수가 같으면 t는 당연히 같으므로 * a,c,g 의 개수로만 처리해도 된다. */ #include<iostream> #include<unordered_map> #include<string> using namespace std; //전체 개수 중 T는 나머지가 같으면 같은거니 계산 제외함 (성능 업) //3개만 1001진법 이상으로 하면 overflow 가능성 줄어드니. struct Data { int a, c, g; //bool operator==(const Data&r) const { // return a == r.a && c == r.c && g == r.g; //} }; struct MyHash { size_t operator()(const Data& d) const { return d.a * 1001 * 1001 + d.c * 1001 + d.g; } }; struct MyEqual { bool operator()(const Data& l, const Data& r) const { return l.a == r.a && l.c == r.c && l.g == r.g; } }; unordered_map<Data, int, MyHash, MyEqual> htab; // a,c,g ºóµµ¼ö / cnt // unordered_map<Data, int, MyHash> htab; // KeyEqual : operator overloading int K; Data cur; void update(char c, int p) { if (c == 'A') cur.a += p; if (c == 'C') cur.c += p; if (c == 'G') cur.g += p; } int main() { freopen("input.txt", "r", stdin); string str; int ret = 0; cin >> K >> str; for (int i = 0; i < str.size(); i++) { update(str[i], 1); if (i >= K) update(str[i - K], -1); if (i + 1 >= K) ret = max(ret, ++htab[cur]); } cout << ret << endl; return 0; }
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 10229 - Modular Fibonacci */ #include <iostream> /* ModAdd v1.0 */ /*************************************************************/ template <typename T, typename U> U Add(const T tA, const T tB) { U tResult = static_cast<U>(tA); tResult += static_cast<U>(tB); return tResult; } template <typename T, typename U> T ModAdd(const T tA, const T tB, const T tR) { U tAdd = Add<T, U>(tA, tB); T tResult = static_cast<T>(tAdd % tR); return tResult; } /*************************************************************/ /* ModMult v1.0 */ /*************************************************************/ template <typename T, typename U> U Mult(const T tA, const T tB) { U tResult = static_cast<U>(tA); tResult *= static_cast<U>(tB); return tResult; } template <typename T, typename U> T ModMult(const T tA, const T tB, const T tR) { U tMult = Mult<T, U>(tA, tB); T tResult = static_cast<T>(tMult % tR); return tResult; } /*************************************************************/ /* Mat2x2Mod v1.0 */ /*************************************************************/ template <typename T, typename U, typename V> class Mat2x2Mod { protected: Mat2x2Mod(const T &tA, const T &tR); Mat2x2Mod(const T &tA11, const T &tA12, const T &tA21, const T &tA22, const T &tR); Mat2x2Mod(const Mat2x2Mod& roRhs); Mat2x2Mod& operator = (const Mat2x2Mod &roRhs); Mat2x2Mod& operator *= (const Mat2x2Mod &roRhs); Mat2x2Mod& operator += (const Mat2x2Mod &roRhs); public: T GetAtPos11() const { return m_tM11; } T GetAtPos12() const { return m_tM12; } T GetAtPos21() const { return m_tM21; } T GetAtPos22() const { return m_tM22; } static Mat2x2Mod ZERO, ONE; private: T m_tM11, m_tM12, m_tM21, m_tM22; const T m_tR; }; template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>::Mat2x2Mod(const T &tA, const T &tR) : m_tM11(tA), m_tM12(0), m_tM21(0), m_tM22(tA), m_tR(tR) { } template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>::Mat2x2Mod(const T &tA11, const T &tA12, const T &tA21, const T &tA22, const T &tR) : m_tM11(tA11), m_tM12(tA12), m_tM21(tA21), m_tM22(tA22), m_tR(tR) { } template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>::Mat2x2Mod(const Mat2x2Mod& roRhs) : m_tM11(roRhs.m_tM11), m_tM12(roRhs.m_tM12), m_tM21(roRhs.m_tM21), m_tM22(roRhs.m_tM22), m_tR(roRhs.m_tR) { } template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>& Mat2x2Mod<T, U, V>::operator =(const Mat2x2Mod& roRhs) { m_tM11 = roRhs.m_tM11; m_tM12 = roRhs.m_tM12; m_tM21 = roRhs.m_tM21; m_tM22 = roRhs.m_tM22; return *this; } template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>& Mat2x2Mod<T, U, V>::operator *= (const Mat2x2Mod &roRhs) { Mat2x2Mod<T, U, V> tResult(*this); tResult.m_tM11 = ModAdd<T, U>(ModMult<T, V>(this->m_tM11, roRhs.m_tM11, this->m_tR), ModMult<T, V>(this->m_tM12, roRhs.m_tM21, this->m_tR), this->m_tR); tResult.m_tM12 = ModAdd<T, U>(ModMult<T, V>(this->m_tM11, roRhs.m_tM12, this->m_tR), ModMult<T, V>(this->m_tM12, roRhs.m_tM22, this->m_tR), this->m_tR); tResult.m_tM21 = ModAdd<T, U>(ModMult<T, V>(this->m_tM21, roRhs.m_tM11, this->m_tR), ModMult<T, V>(this->m_tM22, roRhs.m_tM21, this->m_tR), this->m_tR); tResult.m_tM22 = ModAdd<T, U>(ModMult<T, V>(this->m_tM21, roRhs.m_tM12, this->m_tR), ModMult<T, V>(this->m_tM22, roRhs.m_tM22, this->m_tR), this->m_tR); *this = tResult; return *this; } template <typename T, typename U, typename V> Mat2x2Mod<T, U, V>& Mat2x2Mod<T, U, V>::operator += (const Mat2x2Mod &roRhs) { this->m_tM11 = ModAdd<T, U>(this->m_tM11, roRhs.m_tM11, this->m_tR); this->m_tM12 = ModAdd<T, U>(this->m_tM12, roRhs.m_tM12, this->m_tR); this->m_tM21 = ModAdd<T, U>(this->m_tM21, roRhs.m_tM21, this->m_tR); this->m_tM22 = ModAdd<T, U>(this->m_tM22, roRhs.m_tM22, this->m_tR); return *this; } /*************************************************************/ /* Mat2x2ModR v1.0 */ /*************************************************************/ template <typename T, typename U, typename V, int R> class Mat2x2ModR : public Mat2x2Mod<T, U, V> { public: Mat2x2ModR(const T &tA); Mat2x2ModR(const T &tA11, const T &tA12, const T &tA21, const T &tA22); Mat2x2ModR& operator = (const Mat2x2ModR &roRhs); Mat2x2ModR& operator += (const Mat2x2ModR &roRhs); Mat2x2ModR& operator *= (const Mat2x2ModR &roRhs); static Mat2x2ModR ZERO, ONE; }; template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R>::Mat2x2ModR(const T &tA) : Mat2x2Mod<T, U, V>(tA, R) { } template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R>::Mat2x2ModR(const T &tA11, const T &tA12, const T &tA21, const T &tA22) : Mat2x2Mod<T, U, V>(tA11, tA12, tA21, tA22, R) { } template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R>& Mat2x2ModR<T, U, V, R>::operator =(const Mat2x2ModR<T, U, V, R> &roRhs) { Mat2x2Mod<T, U, V>::operator =(roRhs); return *this; } template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R>& Mat2x2ModR<T, U, V, R>::operator +=(const Mat2x2ModR<T, U, V, R> &roRhs) { Mat2x2Mod<T, U, V>::operator +=(roRhs); return *this; } template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R>& Mat2x2ModR<T, U, V, R>::operator *=(const Mat2x2ModR<T, U, V, R> &roRhs) { Mat2x2Mod<T, U, V>::operator *=(roRhs); return *this; } template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R> Mat2x2ModR<T, U, V, R>::ZERO(T(0), T(0), T(0), T(0)); template <typename T, typename U, typename V, int R> Mat2x2ModR<T, U, V, R> Mat2x2ModR<T, U, V, R>::ONE(T(1), T(0), T(0), T(1)); /*************************************************************/ /* Pow v1.1 */ /*************************************************************/ template <typename T> T Pow(const T tBase, unsigned int nExponent) { T tSum(1); T tExp(tBase); for (; nExponent; nExponent >>= 1) { if (nExponent & 0x1) tSum *= tExp; tExp *= tExp; } return tSum; } /*************************************************************/ template <typename T, typename U, typename V, int R> int Solve1(unsigned int nN) { typedef Mat2x2ModR<T, U, V, R> Mat; Mat oF(1, 1, 1, 0); oF = Pow<Mat>(oF, nN); return oF.GetAtPos12();; } int Solve(unsigned int nN, unsigned int nM) { switch (nM) { case 0: return Solve1<int, int, int, 1 << 0>(nN); case 1: return Solve1<int, int, int, 1 << 1>(nN); case 2: return Solve1<int, int, int, 1 << 2>(nN); case 3: return Solve1<int, int, int, 1 << 3>(nN); case 4: return Solve1<int, int, int, 1 << 4>(nN); case 5: return Solve1<int, int, int, 1 << 5>(nN); case 6: return Solve1<int, int, int, 1 << 6>(nN); case 7: return Solve1<int, int, int, 1 << 7>(nN); case 8: return Solve1<int, int, int, 1 << 8>(nN); case 9: return Solve1<int, int, int, 1 << 9>(nN); case 10: return Solve1<int, int, int, 1 << 10>(nN); case 11: return Solve1<int, int, int, 1 << 11>(nN); case 12: return Solve1<int, int, int, 1 << 12>(nN); case 13: return Solve1<int, int, int, 1 << 13>(nN); case 14: return Solve1<int, int, int, 1 << 14>(nN); case 15: return Solve1<int, int, int, 1 << 15>(nN); case 16: return Solve1<int, int, long long, 1 << 16>(nN); case 17: return Solve1<int, int, long long, 1 << 17>(nN); case 18: return Solve1<int, int, long long, 1 << 18>(nN); case 19: return Solve1<int, int, long long, 1 << 19>(nN); case 20: return Solve1<int, int, long long, 1 << 20>(nN); default: return -1; } } int main() { unsigned int nN, nM; while (std::cin >> nN >> nM) { std::cout << Solve(nN, nM) << std::endl; } return 0; }
#include <iostream> using std::cout; using std::endl; void Swap(int a, int b); void Swap(int* a, int* b); int main() { int x = 10; int y = 15; cout << "x = " << x << " y = " << y << endl; Swap(x, y); cout << "x = " << x << " y = " << y << endl; Swap(&x, &y); cout << "x = " << x << " y = " << y << endl; system("pause"); return 0; } void Swap(int a, int b) { int temp = a; a = b; b = temp; } void Swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
class Solution { public: int minFlipsMonoIncr(string s) { int n = s.size(), res = INT_MAX; // cnt1[i]: num flipping 1 to 0 in s[0:i-1] to make monotone increasing // cnt2[j]: num flipping 0 to 1 in s[j:n-1] to make monotone increasing vector<int> cnt1(n + 1), cnt2(n + 1); for (int i = 1, j = n - 1; j >= 0; i++, j--) { cnt1[i] = cnt1[i - 1] + ((s[i - 1] == '1') ? 1 : 0); cnt2[j] = cnt2[j + 1] + ((s[j] == '0') ? 1 : 0); } // at some pos, (cnt1[i] + cnt2[i]) get minimum flippings for (int i = 0; i <= n; i++) res = min(res, cnt1[i] + cnt2[i]); return res; } };
/** * Print functions for the Header part of a generated proto message. */ #ifndef FISHY_PROTO_PRINTER_HEADER_H #define FISHY_PROTO_PRINTER_HEADER_H #include <CORE/TYPES/protobuf.h> #include <string> bool PrintHeader(const core::types::ProtoDef &def, const std::string &fileName); #endif
// // Created by 王润基 on 2017/4/19. // #ifndef INC_2RAYTRACE_OBJECTMATERIAL_H #define INC_2RAYTRACE_OBJECTMATERIAL_H #include "Material.h" class ObjectMaterial { public: std::string name; shared_ptr<Texture> diffuse = nullptr; // 漫反射 shared_ptr<Texture> ambient = nullptr; // 环境光 Material m; public: Material getMaterial (Vector3f const& uv) const; }; #endif //INC_2RAYTRACE_OBJECTMATERIAL_H
#include <iostream> #include <string> #include "../Headers/Fight.h" fight::fight() { round = 1; } void fight::YourTurn(Player &p, Status &s, weapon &w, opponent& a) const { if (round % 2 == 1) { int dmg = w.ReturnDmg(); std::cout << "You have attacked the " << a.ReturnName() << " and dealt " << dmg << " dmg." << '\n'; w.UseNotBroken(); a.TakeDmg(dmg); if (a.ReturnEnemyHealth() > 0) std::cout << "The " << a.ReturnName() << " has " << a.ReturnEnemyHealth() << " life points left." << '\n'; } } void fight::OpponentTurn(Player &p, Status &s, opponent & a) const { if (round % 2 == 0) { std::cout << '\n' << a.ReturnName() << " has attacked you and dealt " << a.ReturnEnemyDmg() << " dmg." << '\n'; s.LoseHealth(a.ReturnEnemyDmg()); std::cout << "Your life is " << s.ReturnHealth() << "." << '\n'; } } void fight::Attack(Player &p, Status &z, weapon &w) { std::cout << '\n' << "Would you like to fight this opponent? [y/n]" << '\n'; char option; std::cin >> option; if (tolower(option) != 'y' && tolower(option) != 'n') { option = 'n'; std::cout << '\n' << "You did not select the right option! So you will just missed the opportunity to fight the enemy!" << '\n'; } if (tolower(option) == 'y') { opponent a(y); while (a.ReturnEnemyHealth() > 0 && z.ReturnHealth() > 0) { std::cout << '\n' << "~~~~~Round " << round << "~~~~~~~" << '\n'; YourTurn(p,z,w,a); OpponentTurn(p,z,a); round++; } } else if (tolower(option) == 'n') std::cout << "You decided not to attack the " << y.ReturnName(); z.Died(p); if (p.IsDead()) throw (std::runtime_error("DEAD")); }
#include <Windows.h> #include <tchar.h> #define IDS_APP_TITLE 103 #define IDR_MAINFRAME 128 #define IDD_LAB2_DIALOG 102 #define IDD_ABOUTBOX 103 #define IDM_ABOUT 104 #define IDM_EXIT 105 #define IDI_LAB2 107 #define IDI_SMALL 108 #define IDC_LAB2 109 #define IDC_MYICON 2 #ifndef IDC_STATIC #define IDC_STATIC -1 #endif // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 130 #define _APS_NEXT_RESOURCE_VALUE 129 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif #define MAX_LOADSTRING 100 HINSTANCE hInst; TCHAR szTitle[MAX_LOADSTRING] = _T("Title1"); TCHAR szWindowClass[MAX_LOADSTRING] = _T("Windowclass1"); TCHAR szTitle2[MAX_LOADSTRING] = _T("Title2"); TCHAR szWindowClass2[MAX_LOADSTRING] = _T("Windowclass2"); ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); MSG msg; HACCEL hAccelTable; MyRegisterClass(hInstance); if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB2)); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB2)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_LAB2); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; HWND h = FindWindow(szWindowClass2, szTitle2); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Разобрать выбор в меню: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_LBUTTONDOWN: if (h) { WinExec("C:\\Windows\\system32\\notepad.exe", 1); int success = MessageBox(hWnd, _T("Окно 2 открыто!"), _T("Сообщение"), MB_OK); if (success) { SendMessage(h, WM_USER + 1, WPARAM(hWnd), 0); } } else { MessageBox(hWnd, _T("Окно 2 закрыто!"), _T("Сообщение"), MB_OK); } break; case WM_RBUTTONDOWN: { SendMessage(h, WM_USER + 2, WPARAM(hWnd), 0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
#include"iostream" using namespace std; struct node{ int data; node *ptr; }; node *head; node *tail; void insert(int x){ node *temp=new node; temp->data=x; temp->ptr=NULL; if(head==NULL){ head=temp; tail=temp; } else{ tail->ptr=temp; tail=tail->ptr; } } void display(){ node *temp=head; while(temp!=NULL){ cout<<temp->data<<endl; temp=temp->ptr; } } void insert_at_start(int x){ node *temp=new node; temp->data=x; if(head!=NULL){ temp->ptr=head; head=temp; } else{ head=temp; tail=temp; } } void sort(){ node *temp; node *temp1; temp=head; int t; while(temp!=NULL){ temp1=head; while(temp1!=NULL){ if(temp->data<(temp1->data)) { t=temp1->data; temp1->data=(temp->data); temp->data=t; } temp1=temp1->ptr; } temp=temp->ptr; } } void find_it(int f){ int count; node *temp=new node; temp=head; while(temp!=NULL){ count++; if(temp->data==f){ cout<<"this value is at "<<count<<endl; } temp=temp->ptr; } } void insert_at_pos(int ele,int pos){ node *temp1=new node; node *temp=new node; node *t=new node; temp->data=ele; temp->ptr=NULL; temp1=head; t=head; int count=0; while(temp1!=NULL){ count++; if(pos==count){ t->ptr=temp; temp->ptr=temp1; break; } t=temp1; temp1=temp1->ptr; } } void delete_it(int del){ node *temp=new node; node *temp1=new node; temp1=head; temp=head; while(temp1!=NULL){ if(temp1->data==del){ temp->ptr=temp1->ptr; } temp=temp1; temp1=temp1->ptr; } } int main(){ head=NULL; tail=NULL; int n,a,f,b; cout<<"enter the number of elents you want to list in series"; cin>>n; for(int i=0;i<n;i++){ cin>>a; insert(a); } cout<<endl; cout<<"enter the amount of number you want to add in front"; cin>>b; for(int i=0;i<b;i++){ cin>>a; insert_at_start(a); } cout<<endl; display(); sort(); cout<<endl; display(); cout<<"enter the element to find:"<<endl; cin>>f; find_it(f); cout<<"enter the number of elements you want to enter"; int l,ele,pos; cin>>l; for(int i=0;i<l;i++){ cout<<"enter element "; cin>>ele; cout<<"enter position "; cin>>pos; insert_at_pos(ele,pos); } display(); int del; cout<<"enter the element you want to delete"; cin>>del; delete_it(del); display(); return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ long a,c,b,r; cin>>a>>b>>c>>r; long total = 0; long s = c-r; long e= c+r; if(b>a){ if( (s<a && e<a) || (s>b && e>b)){ total = abs(b-a); cout<<total<<"\n"; continue; } if(s>=a && e<=b){ total = abs(b-a)- (2*r); } else if(s>=a && e>b){ total = abs(a-b)-(b-s); } else if(s<a && e<=b){ total = abs(a-b)-(e-a); } cout<<total<<"\n"; }else{ if( (s>a && e>a) || (s<b && e<b)){ total = abs(b-a); cout<<total<<"\n"; continue; } if(s>=b && e<=a){ total = abs(b-a)-(2*r); } else if(s>=b && e>a){ total = abs(a-b)-(a-s); } else if(s<b && e<=a){ total = abs(a-b)-(e-b); } cout<<total<<"\n"; } } return 0; }
/* Copyright (c) 2008 NVIDIA CORPORATION Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MX_OBJECTS_H #define MX_OBJECTS_H #include <vector> #include <list> #include <map> #include <iterator> class MxActor; //class MxShape; class MxJoint; class MxMaterial; class MxFluid; class MxFluidEmitter; class MxCloth; class MxSoftBody; class MxForceField; class MxPluginData; class MxMesh; class MxCompartment; enum MxObjectType { MX_OBJECTTYPE_BASEOBJECT = 0, MX_OBJECTTYPE_ACTOR = 1, MX_OBJECTTYPE_SHAPE = 2, MX_OBJECTTYPE_JOINT = 3, MX_OBJECTTYPE_MATERIAL = 4, MX_OBJECTTYPE_FLUID = 5, MX_OBJECTTYPE_FLUIDEMITTER = 6, MX_OBJECTTYPE_CLOTH = 7, MX_OBJECTTYPE_SOFTBODY = 8, MX_OBJECTTYPE_MESH = 9, MX_OBJECTTYPE_COMPARTMENT = 10, MX_OBJECTTYPE_FORCEFIELD = 11 }; class MxObject; typedef std::map<INode*, MxObject*> ccPhysXMapContainer; typedef std::vector<MxObject*> ccPhysXNodeContainer; typedef std::vector<INode*> ccMaxNodeContainer; struct MxPhysXObjectRegsiter { ccPhysXNodeContainer physXNodes; // store physics nodes ccMaxNodeContainer maxNodes; // store all max nodes ccPhysXMapContainer quickTable; void loadMaxNodes(); void registerObject(MxObject *); void unregisterObject(MxObject *); void arrange(); void clear(); }; class MxObject { public: MxObject(const char* name, INode* node, NxU32 id=0xFFFFFFFF) { m_refcount = 0; m_name = TSTR(name); m_node = node; if (id == 0xFFFFFFFF) { m_currentID++; m_id = m_currentID; } else { m_id = id; } // m_ObjectType = MX_OBJECTTYPE_BASEOBJECT; // PhysXObjects.registerObject(this); } virtual ~MxObject() { assert(m_refcount == 0); PhysXObjects.unregisterObject(this); } NxU32 getRefCount() { return m_refcount; } NxU32 getID() { return m_id; } TSTR getName() { return m_name; } INode* getNode() { return m_node; } /** Resets the object as it was when it was added to the simulation */ virtual void resetObject() {} virtual void* isType(MxObjectType type) { if (type == MX_OBJECTTYPE_BASEOBJECT) return this; return NULL; } virtual MxActor* isActor() { return NULL; } //virtual MxShape* isShape(){ return NULL; } virtual MxJoint* isJoint() { return NULL; } virtual MxMaterial* isMaterial() { return NULL; } virtual MxFluid* isFluid() { return NULL; } virtual MxFluidEmitter* isFluidEmitter() { return NULL; } virtual MxCloth* isCloth() { return NULL; } virtual MxSoftBody* isSoftBody() { return NULL; } virtual MxForceField* isForceField() { return NULL; } virtual MxMesh* isMesh() { return NULL; } virtual MxCompartment* isCompartment() { return NULL; } MxObjectType getType() { return m_ObjectType; } public: static MxPhysXObjectRegsiter PhysXObjects; protected: friend class MxPluginData; void decRef() { assert(m_refcount > 0); m_refcount--; } void incRef() { m_refcount++; } TSTR m_name; INode* m_node; NxU32 m_id; NxU32 m_refcount; MxObjectType m_ObjectType; private: static NxU32 m_currentID; }; class MxCompartment : public MxObject { public: virtual MxCompartment* isCompartment() { return this; } virtual void* isType(MxObjectType type) { if (type == MX_OBJECTTYPE_COMPARTMENT) return this; return NULL; } NxCompartmentType getCompartmentType() { return m_compartmentType; } NxU32 getCompartmentID() { return m_compartmentID; } NxCompartment* getNxCompartment() { return m_compartment; } protected: friend class MxPluginData; MxCompartment(const char* name, NxCompartmentType type, NxU32 compartmentID, NxCompartment* compartment) : MxObject(name, NULL), m_compartmentType(type), m_compartmentID(compartmentID), m_compartment(compartment) { m_ObjectType = MX_OBJECTTYPE_COMPARTMENT; } virtual ~MxCompartment() {} NxCompartmentType m_compartmentType; NxU32 m_compartmentID; NxCompartment* m_compartment; }; #endif //MX_OBJECTS_H
#include "ColorVertex.h" std::vector<Gx::VertexElement> ColorVertex::declaration() { return { Gx::VertexElement::Position, Gx::VertexElement::Color }; }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #ifndef FLUX_TIMER_H #define FLUX_TIMER_H #include <flux/Thread> #include <flux/Channel> #include <flux/System> namespace flux { /** \brief interval timer thread * * A Timer is a thread that writes tick objects into a channel in a fixed time interval. * The time interval may not be hit exactly for each tick, but the overall time scale * is maintained. In other words an individual tick may be delivered unprecisely due * to the uncertainty of thread scheduling, but there is no error accumulated in the * process. * * \see Channel, Thread, System::now() */ template<class T> class Timer: public Thread { public: static Ref<Timer> start(double startTime, double interval, Channel<T> *triggered = 0, T tick = T()) { return new Timer(startTime, interval, triggered, tick); } inline double startTime() const { return startTime_; } inline double interval() const { return interval_; } inline Channel<T> *triggered() const { return triggered_; } inline T tick() const { return tick_; } protected: Timer(double startTime, double interval, Channel<T> *triggered, T tick): startTime_(startTime), interval_(interval), triggered_(triggered), shutdown_(Channel<bool>::create()), tick_(tick) { if (!triggered_) triggered_ = Channel<T>::create(); Thread::start(); } ~Timer() { shutdown_->push(true); Thread::wait(); } virtual void writeTick(double timeout, bool shutdown) { if (!shutdown) triggered()->push(tick()); } private: virtual void run() { double timeout = startTime_; while (!shutdown_->popBefore(timeout)) { writeTick(timeout, false); timeout += interval_; } writeTick(timeout, true); } double startTime_; double interval_; Ref< Channel<T> > triggered_; Ref< Channel<bool> > shutdown_; T tick_; }; } // namespace flux #endif // FLUX_TIMER_H
#include "serial.h" #include <Arduino.h> #include <VescUart.h> #include <datatypes.h> #include <driver/uart.h> #include "analog.h" #include "mpu.h" #include <PID_v1.h> double Setpoint, Input, Output; double Kp=1, Ki=3, Kd=4; PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT); struct bldcMeasure measuredVal; //unsigned long count=20; HardwareSerial Serial1(1); HardwareSerial Serial2(2); //uint8_t mc_payload[512]; int dir=0; int lastdir=0; long ago(long a){ return millis()-a; } double mapf(double val, double in_min, double in_max, double out_min, double out_max) { return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } uint32_t lastmove=0; bool brake(){ return 0; if(leftnow!=0 || rightnow!=0)lastmove=millis(); if(millis()-lastmove>2000)return 1; return 0; } void drive(float current,int vesc){ if(digitalRead(15) || current>20 || current<-20){ VescUartSetCurrentBrake(10,0); VescUartSetCurrentBrake(10,1); } else VescUartSetCurrent(current,vesc); } void serial_task(void *pvParameter){ Serial1.begin(115200, SERIAL_8N1, 13,12);// RX, TX Serial2.begin(115200, SERIAL_8N1, 14,27);// RX, TX SetSerialPort(&Serial1,&Serial2,&Serial2,&Serial2);//,nullptr,nullptr); SetDebugSerialPort(NULL);//&Serial); //delay(500); Input = kalAngleY; Setpoint = 17; //turn the PID on myPID.SetMode(AUTOMATIC); myPID.SetOutputLimits(-5,5); while(1){ /*if (VescUartGetValue(measuredVal,0)) { Serial.println("ONE: ");// Serial.println(count++); //SerialPrint(measuredVal); } else { Serial.println("Failed to get data one!"); } if (VescUartGetValue(measuredVal,1)) { Serial.println("TWO: ");// Serial.println(count++); //SerialPrint(measuredVal); } else { Serial.println("Failed to get data two!"); }*/ /*if(ago(lastdir)<300){ switch(dir){ case 1: drive(-5,1); drive(5,0); break; case 2: drive(5,1); drive(5,0); break; case 3: drive(-5,1); drive(-5,0); break; case 4: drive(5,1); drive(-5,0); break; } }*/ if(kalAngleY>10 && kalAngleY<30 && false){ Input = kalAngleY; myPID.Compute(); drive(Output,0); drive(-Output,1); } else{ if(leftnow==0){ drive(0,1); } else drive(-leftnow/5,1); if(rightnow==0){ drive(0,0); } else drive(rightnow/5,0); } //Serial.print(compAngleY); //Serial.print("\t"); Serial.println(kalAngleY); delay(10); /*if(leftnow==0)VescUartSetCurrent(0,1); else VescUartSetRPM(mapf(leftnow,0.0,100.0,0.0,13000.0),1); if(rightnow==0)VescUartSetCurrent(0,0); else VescUartSetRPM(mapf(rightnow,0.0,100.0,0.0,13000.0),0);*/ //VescUartSetRPM(mapf(leftnow,0.0,100.0,0.0,13000.0),1); //VescUartSetRPM(mapf(rightnow,0.0,100.0,0.0,13000.0),0); /*if(Serial1.available()){ Serial.write(Serial1.read()); } if(Serial.available()){ Serial1.write(Serial.read()); }*/ //delayMicroseconds(1); } vTaskDelete( NULL ); //will never happen }
#include <iostream> #include <sstream> #include <fstream> #include "gl_helpers.h" namespace { std::string load_source_from_file(const std::string& file_path) { std::ifstream source_file{file_path}; if (!source_file.is_open()) { std::cout << "Could not find file:\n" << file_path << "\nExiting" << std::endl; exit(EXIT_FAILURE); } std::stringstream buffer; buffer << source_file.rdbuf(); source_file.close(); return buffer.str(); } } GLuint load_shader_from_file(const std::string& file_path, const GLuint shader_type) { std::string source = load_source_from_file(file_path); const GLchar* shader_source = static_cast<const GLchar*>(source.c_str()); // For some reason, this doesn't always work...: // const GLchar* shader_source = static_cast<const GLchar*>(load_source_from_file(file_path).c_str()); GLuint shader = glCreateShader(shader_type); glShaderSource(shader, 1, &shader_source, NULL); glCompileShader(shader); GLint shader_status; glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_status); if (shader_status != GL_TRUE) { std::cout << "The shader for:\n" << file_path << "\nfailed to compile. Exiting" << std::endl; exit(EXIT_FAILURE); } return shader; }
#ifndef GAME_H #define GAME_H #include <cstdio> #include <string> #include <sstream> #include <vector> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "constants.hpp" #include "Base.hpp" #include "Views/BaseMap.hpp" #include "Building.hpp" #include "Button.hpp" #include "ElectrolysisPlant.hpp" #include "FusionReactor.hpp" #include "Habitat.hpp" #include "HydroponicGreenhouse.hpp" #include "MetalExtractor.hpp" #include "NuclearReactor.hpp" #include "OxygenExtractor.hpp" #include "Refinery.hpp" #include "ScreenManager.hpp" #include "SolarFarm.hpp" #include "Texture.hpp" #include "Tile.hpp" #include "Timer.hpp" #include "WaterRecycler.hpp" using namespace std; class Game { public: Game(); bool loadAssets(); bool init(); void initMap(); int run(); void quit(); private: SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; Texture spritesTexture; TTF_Font *gFont = nullptr; SDL_Rect gTileClips[32]; SDL_Rect gIconClips[1]; Texture gFPSTextTexture; }; #endif
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.2.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QFrame> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTextEdit> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout_2; QGridLayout *gridLayout; QSpacerItem *horizontalSpacer; QLabel *lblListeningBanner; QLabel *label_2; QLineEdit *leHmmDir; QLabel *label_4; QLineEdit *leLanguageModel; QLabel *label_5; QLineEdit *leDictionary; QPushButton *btnSetModels; QFrame *line; QPushButton *btnStart; QLabel *label; QLabel *label_3; QTextEdit *teHistory; QLabel *lblRecognizedWord; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(906, 484); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout_2 = new QGridLayout(centralWidget); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); gridLayout = new QGridLayout(); gridLayout->setSpacing(6); gridLayout->setObjectName(QStringLiteral("gridLayout")); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout->addItem(horizontalSpacer, 6, 5, 1, 1); lblListeningBanner = new QLabel(centralWidget); lblListeningBanner->setObjectName(QStringLiteral("lblListeningBanner")); lblListeningBanner->setStyleSheet(QLatin1String("background:rgb(255, 0, 4);\n" "color:rgb(255, 255, 255);")); gridLayout->addWidget(lblListeningBanner, 6, 2, 1, 1); label_2 = new QLabel(centralWidget); label_2->setObjectName(QStringLiteral("label_2")); gridLayout->addWidget(label_2, 0, 0, 1, 1); leHmmDir = new QLineEdit(centralWidget); leHmmDir->setObjectName(QStringLiteral("leHmmDir")); gridLayout->addWidget(leHmmDir, 0, 1, 1, 5); label_4 = new QLabel(centralWidget); label_4->setObjectName(QStringLiteral("label_4")); gridLayout->addWidget(label_4, 1, 0, 1, 1); leLanguageModel = new QLineEdit(centralWidget); leLanguageModel->setObjectName(QStringLiteral("leLanguageModel")); gridLayout->addWidget(leLanguageModel, 1, 1, 1, 5); label_5 = new QLabel(centralWidget); label_5->setObjectName(QStringLiteral("label_5")); gridLayout->addWidget(label_5, 2, 0, 1, 1); leDictionary = new QLineEdit(centralWidget); leDictionary->setObjectName(QStringLiteral("leDictionary")); gridLayout->addWidget(leDictionary, 2, 1, 1, 5); btnSetModels = new QPushButton(centralWidget); btnSetModels->setObjectName(QStringLiteral("btnSetModels")); gridLayout->addWidget(btnSetModels, 2, 6, 1, 1); line = new QFrame(centralWidget); line->setObjectName(QStringLiteral("line")); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); gridLayout->addWidget(line, 3, 0, 1, 7); btnStart = new QPushButton(centralWidget); btnStart->setObjectName(QStringLiteral("btnStart")); gridLayout->addWidget(btnStart, 5, 0, 2, 2); label = new QLabel(centralWidget); label->setObjectName(QStringLiteral("label")); QFont font; font.setPointSize(12); label->setFont(font); gridLayout->addWidget(label, 7, 0, 1, 3); label_3 = new QLabel(centralWidget); label_3->setObjectName(QStringLiteral("label_3")); gridLayout->addWidget(label_3, 8, 0, 1, 1); teHistory = new QTextEdit(centralWidget); teHistory->setObjectName(QStringLiteral("teHistory")); teHistory->setFont(font); gridLayout->addWidget(teHistory, 9, 0, 1, 7); lblRecognizedWord = new QLabel(centralWidget); lblRecognizedWord->setObjectName(QStringLiteral("lblRecognizedWord")); lblRecognizedWord->setFont(font); lblRecognizedWord->setStyleSheet(QLatin1String("color:rgb(255, 255, 255);\n" "background:rgb(21, 154, 255);")); gridLayout->addWidget(lblRecognizedWord, 7, 3, 1, 4); gridLayout_2->addLayout(gridLayout, 0, 0, 1, 1); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 906, 26)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0)); lblListeningBanner->setText(QApplication::translate("MainWindow", "Listening.......", 0)); label_2->setText(QApplication::translate("MainWindow", "HMM dir", 0)); label_4->setText(QApplication::translate("MainWindow", "Language Model", 0)); label_5->setText(QApplication::translate("MainWindow", "Dictionary", 0)); btnSetModels->setText(QApplication::translate("MainWindow", "SET/STOP", 0)); btnStart->setText(QApplication::translate("MainWindow", "Start", 0)); label->setText(QApplication::translate("MainWindow", "Last Detected!!!", 0)); label_3->setText(QApplication::translate("MainWindow", "History", 0)); teHistory->setHtml(QApplication::translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:12pt; font-weight:400; font-style:normal;\">\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;\"><br /></p></body></html>", 0)); lblRecognizedWord->setText(QString()); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
#ifndef CORE_ENGINE_HPP # define CORE_ENGINE_HPP # include <iostream> # include <sys/time.h> # include <unistd.h> # include "OpenGlLib.hpp" # include "../core/GameObject.hpp" # include "../game/Gomoku.hpp" # define SECOND (1000000.0) class CoreEngine { public: CoreEngine( float fps ); CoreEngine( CoreEngine const & src ); ~CoreEngine( void ); CoreEngine & operator=( CoreEngine const & rhs ); bool start( void ); bool stop( void ); void setFPS( int fps ); // int update( double delta ); // int render( void ) const; int setRunnig( int state ); int setGame( Gomoku *game ); private: CoreEngine( void ); double getTime( void ); void * _handle; float _fps; bool _isRunning; Gomoku* _game; OpenGlLib* _renderLib; }; #endif
#pragma once #include "ofMain.h" #include "ofxGui.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); int scale; ofVideoPlayer vid; ofSpherePrimitive sphere; ofMaterial material; ofPlanePrimitive plane; ofxPanel gui; ofCamera camera; ofxFloatSlider radius; ofxFloatSlider sphereResolution; ofxFloatSlider sphereZ; ofxFloatSlider fov; ofxToggle filled; void bind(); void unbind(); void drawMouseUI(); ofVec2f mouseDownPosition; bool isMouseDown; float keyAcc = 2.0f; float maxVel = 100.0f; float friction = 0.9f; ofPoint acc; ofPoint vel; };
#pragma once #include <algorithm> #include <cmath> namespace utils { inline unsigned int factorial(unsigned int const factor) { return static_cast<unsigned int>(std::tgamma(factor + 1.0)); } inline unsigned int num_combinations(unsigned int const num_items, unsigned int const chosen_items_at_time) { return factorial(num_items) / (factorial(chosen_items_at_time) * factorial(num_items - chosen_items_at_time)); } template<typename Iterator> bool next_combination(const Iterator first, Iterator k, const Iterator last) { /* Credits: Mark Nelson http://marknelson.us */ if ((first == last) || (first == k) || (last == k)) return false; Iterator i1 = first; Iterator i2 = last; ++i1; if (last == i1) return false; i1 = last; --i1; i1 = k; --i2; while (first != i1) { if (*--i1 < *i2) { Iterator j = k; while (!(*i1 < *j)) ++j; std::iter_swap(i1, j); ++i1; ++j; i2 = k; std::rotate(i1, j, last); while (last != j) { ++j; ++i2; } std::rotate(k, i2, last); return true; } } std::rotate(first, k, last); return false; } }// namespace utils
#include "../Include/PainterForEllipse.h" #include "../Include/Window.h" #include "../Include/Graph.h" #include "../Include/World.h" PainterForEllipse::PainterForEllipse(Application * targetApp, Window * targetWindow, World * targetWorld) : Painter(targetApp, targetWindow, targetWorld) { requiredClicks = 1; } PainterForEllipse::PainterForEllipse() { } void PainterForEllipse::mouseButton(int button, int state, int x, int y) { switch (button) { case GLUT_LEFT_BUTTON: switch (state) { case GLUT_DOWN: break; case GLUT_UP: if (mPainter->getTargetWindow()->isInPaper()) { if (mPainter->getTargetGraph() != NULL) { if (mPainter->getRequiredClicks() <= 0) { mPainter->quit(); } } } break; } break; case GLUT_RIGHT_BUTTON: switch (state) { case GLUT_DOWN: //点击右键结束绘图 mPainter->quit(); break; default: break; } break; case GLUT_MIDDLE_BUTTON: break; } mPainter->update(); } void PainterForEllipse::mouseMotion(int x, int y) { //换算后的坐标 mPainter->setEndPos(x + 50, 770 - y); float deltaX = -mPainter->getCurPosX() + mPainter->getEndPosX(); float deltaY = -mPainter->getCurPosY() + mPainter->getEndPosY(); float R1 = deltaX > 0 ? deltaX : -deltaX; float R2 = deltaY > 0 ? deltaY : -deltaY; if (mPainter->getTargetWindow()->isInPaper()) { if (mPainter->getTargetGraph() != NULL) mPainter->getTargetGraph()->setRadiusA(R1); mPainter->getTargetGraph()->setRadiusB(R2); } //更新当前操作状态 mPainter->update(); } void PainterForEllipse::paint(int x, int y) { if (!mPainter->isStarted()) { start(x, y); } glutMouseFunc(mouseButton); glutMotionFunc(mouseMotion); } void PainterForEllipse::start(int x, int y) { //记录起始点,用于motion求半径 mPainter->setCurPos(x, y); mPainter->setStarted(); mPainter->getTargetGraph()->setRadiusA(0); mPainter->getTargetGraph()->setRadiusB(0); mPainter->getTargetGraph()->moveTo(x, y); mPainter->getTargetGraph()->setColor(mColor.r, mColor.g, mColor.b); mPainter->getTargetGraph()->setLineWidth(mPainter->getTargetWindow()->getActiveLineWidth()); mPainter->getTargetWorld()->addGraph(mPainter->getTargetGraph()); mPainter->setClicked(); } void PainterForEllipse::setRadiusA(float r) { } void PainterForEllipse::setRadiusB(float r) { }
class Solution { public: vector<vector<string>> result; vector<vector<string>> solveNQueens(int n) { vector<vector<int>> xie(n, vector<int>(n,0)); vector<string> temp; backtrack(n,0,temp,xie); return result; } void backtrack(int n, int row, vector<string> temp, vector<vector<int>>& xie) { if(row == n) { result.push_back(temp); return; } string s = string(n,'.'); for(int i = 0; i < n; i++) { if(xie[row][i] == 0) { int count = 0; for(int j = row; j < n; j++) { xie[j][i]++; if(i+count < n) xie[j][i+count]++; if(i-count >= 0) xie[j][i-count]++; count++; } s[i] = 'Q'; temp.push_back(s); backtrack(n,row+1,temp,xie); count = 0; for(int j = row; j < n; j++) { xie[j][i]--; if(i+count < n) xie[j][i+count]--; if(i-count >= 0) xie[j][i-count]--; count++; } s[i] = '.'; temp.pop_back(); } } } };
/**************************************************************************** Author: Luma (stubma@gmail.com) https://github.com/stubma/cocos2dx-better @2015 QuanNguyen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "Packet.h" #include "ByteBuffer.h" #include "JSONUtils.h" USING_NS_CC; namespace funny { namespace network { Packet::Packet() : m_buffer(NULL), m_packetLength(0), m_raw(false) { memset(&m_header, 0, sizeof(Header)); } Packet::~Packet() { CC_SAFE_FREE(m_buffer); } bool Packet::initWithJson(const std::string& magic, int command, const cocos2d::Value& json, int protocolVersion, int serverVersion, int algorithm) { // check magic if(magic.length() < 4) return false; // magic m_header.magic[0] = magic.at(0); m_header.magic[1] = magic.at(1); m_header.magic[2] = magic.at(2); m_header.magic[3] = magic.at(3); // protocol version m_header.protocolVersion = protocolVersion; // server version m_header.serverVersion = serverVersion; // command id m_header.command = command; // no encrypt m_header.encryptAlgorithm = algorithm; // body std::string bodyStr = JSONUtils::getInstance()->JSONStringFromValue(json); char* plain = (char*)bodyStr.c_str(); m_header.length = (int)bodyStr.length(); allocate(bodyStr.length() + kPacketHeaderLength + 1); memcpy(m_buffer + kPacketHeaderLength, plain, bodyStr.length()); m_packetLength = bodyStr.length() + kPacketHeaderLength; // write header writeHeader(); // init m_raw = false; return true; } bool Packet::initWithStandardBuf(const char* buf, size_t len) { // quick check if(len < kPacketHeaderLength) { return false; } // header ByteBuffer bb(buf, len, len); m_header.magic[0] = bb.read<char>(); m_header.magic[1] = bb.read<char>(); m_header.magic[2] = bb.read<char>(); m_header.magic[3] = bb.read<char>(); m_header.protocolVersion = (int32_t)(bb.read<int>()); m_header.serverVersion = (int32_t)(bb.read<int>()); m_header.command = (int32_t)(bb.read<int>()); m_header.encryptAlgorithm = (int32_t)(bb.read<int>()); m_header.length = (int32_t)(bb.read<int>()); // body if(bb.available() >= m_header.length) { allocate(m_header.length + kPacketHeaderLength + 1); bb.read((uint8_t*)m_buffer + kPacketHeaderLength, m_header.length); } else { return false; } // init other m_raw = false; m_packetLength = m_header.length + kPacketHeaderLength; // write header writeHeader(); return true; } bool Packet::initWithRawBuf(const char* buf, size_t len, int algorithm) { m_header.length = (int)len; allocate(len + 1); memcpy(m_buffer, buf, len); // other m_raw = true; m_packetLength = m_header.length; return true; } void Packet::writeHeader() { ByteBuffer bb(m_buffer, m_packetLength, 0); // magic bb.write<char>(m_header.magic[0]); bb.write<char>(m_header.magic[1]); bb.write<char>(m_header.magic[2]); bb.write<char>(m_header.magic[3]); // protocol version bb.write<int>(int32_t(m_header.protocolVersion)); // server version bb.write<int>(int32_t(m_header.serverVersion)); // command id bb.write<int>(int32_t(m_header.command)); // no encrypt bb.write<int>(int32_t(m_header.encryptAlgorithm)); // body length bb.write<int>(int32_t(m_header.length)); } const char* Packet::getBody() { if(m_raw) return m_buffer; else return m_buffer + kPacketHeaderLength; } void Packet::allocate(size_t len) { if(!m_buffer) m_buffer = (char*)calloc(len, sizeof(char)); } } }
#include "guiutils.h" GuiUtils::GuiUtils() { } GuiUtils::~GuiUtils() { } std::string GuiUtils::getFilePath(QWidget *parent) { QFileDialog *dialog = new QFileDialog(parent); QString fileName = dialog->getOpenFileName(parent, QString("Open File"), QString(), QString()); dialog->close(); dialog->~QFileDialog(); return fileName.toStdString(); } void GuiUtils::showInFinder(QWidget *parent, const QString &filePath) { Q_UNUSED(parent); QStringList args; args << "-e"; args << "tell application \"Finder\""; args << "-e"; args << "activate"; args << "-e"; args << "select POSIX file \"" + filePath + "\""; args << "-e"; args << "end tell"; QProcess::startDetached("osascript", args); } QImage GuiUtils::Mat2QImg(cv::Mat src) { cv::Mat tmp; cv::cvtColor(src, tmp, cv::COLOR_BGR2RGB); QImage dst((const unsigned char*)tmp.data, tmp.cols, tmp.rows, tmp.step, QImage::Format_RGB888); dst.bits(); return dst; }
#include <bits/stdc++.h> #define ull unsigned long long #define ll long long #define il inline #define db double #define ls rt << 1 #define rs rt << 1 | 1 #define pb push_back #define mp make_pair #define pii pair<int, int> #define X first #define Y second #define pcc pair<char, char> #define vi vector<int> #define vl vector<ll> #define rep(i, x, y) for(int i = x; i <= y; i ++) #define rrep(i, x, y) for(int i = x; i >= y; i --) #define rep0(i, n) for(int i = 0; i < (n); i ++) #define per0(i, n) for(int i = (n) - 1; i >= 0; i --) #define ept 1e-9 #define INF 0x3f3f3f3f #define sz(x) (x).size() #define ALL(x) (x).begin(), (x).end() using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } inline ll read1() { ll x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } const ll inf = 1000000007; const ll mod = 998244353; const int N = 1e6 + 10; ll a[N], b[N], c[N]; ll amxz[N], amnz[N], amxf[N], amnf[N], bmxz[N], bmnz[N], bmxf[N], bmnf[N]; bool hasaz[N], hasaf[N], hasbz[N], hasbf[N], has0[N]; int main() { int T = read(); while (T --) { int n = read(); int k = 1, _ = 0; while (k < n) k <<= 1, ++ _; k --; rep0(i, k + 1) { amxz[i] = 0; amnz[i] = inf; amxf[i] = -inf; amnf[i] = 0; bmxz[i] = 0; bmnz[i] = inf; bmxf[i] = -inf; bmnf[i] = 0; hasaz[i] = 0; hasaf[i] = 0; hasbz[i] = 0; hasbf[i] = 0; has0[i] = 0; c[i] = -inf * inf; } rep0(i, n) { a[i] = read(); if (a[i] > 0) { amxz[i] = max(amxz[i], a[i]); amnz[i] = min(amnz[i], a[i]); hasaz[i] = 1; } else if (a[i] < 0) { amxf[i] = max(amxf[i], a[i]); amnf[i] = min(amnf[i], a[i]); hasaf[i] = 1; } else if (a[i] == 0) has0[i] = 1; } rep0(i, n) { b[i] = read1(); if (b[i] > 0) { bmxz[i] = max(bmxz[i], b[i]); bmnz[i] = min(bmnz[i], b[i]); hasbz[i] = 1; } else if (b[i] < 0) { bmxf[i] = max(bmxf[i], b[i]); bmnf[i] = min(bmnf[i], b[i]); hasbf[i] = 1; } else if (b[i] == 0) has0[i] = 1; } ll ans = 0; rrep(S, k, 0) { rep0(i, _) if ((S & (1 << i)) == 0) { int sta = S | (1 << i); hasaz[S] |= hasaz[sta]; hasaf[S] |= hasaf[sta]; hasbz[S] |= hasbz[sta]; hasbf[S] |= hasbf[sta]; has0[S] |= has0[sta]; if (hasaz[S]) { amxz[S] = max(amxz[S], amxz[sta]); amnz[S] = min(amnz[S], amnz[sta]); } if (hasaf[S]) { amxf[S] = max(amxf[S], amxf[sta]); amnf[S] = min(amnf[S], amnf[sta]); } if (hasbz[S]) { bmxz[S] = max(bmxz[S], bmxz[sta]); bmnz[S] = min(bmnz[S], bmnz[sta]); } if (hasbf[S]) { bmxf[S] = max(bmxf[S], bmxf[sta]); bmnf[S] = min(bmnf[S], bmnf[sta]); } } //cerr<<S<<" "<<hasaz[S]<<" "<<hasaf[S]<<" "<<hasbz[S]<<" "<<hasbf[S]<<" "<<has0[S]<<endl; if (hasaz[S] && hasbz[S])c[S] = max(c[S], amxz[S] * bmxz[S]); if (hasaf[S] && hasbf[S])c[S] = max(c[S], amnf[S] * bmnf[S]); if (hasaz[S] && hasbf[S])c[S] = max(c[S], amnz[S] * bmxf[S]); if (hasaf[S] && hasbz[S])c[S] = max(c[S], amxf[S] * bmnz[S]); if (has0[S])c[S] = max(c[S], 0ll); //cerr<<c[S]<<endl; if (S < k)c[S] = max(c[S], c[S + 1]); if (S < n) { ans = (ans + c[S]) % mod; assert(abs(c[S]) < inf * 1ll * inf); } } ans = (ans % mod + mod) % mod; printf("%lld\n", ans); } }
// // AudioManager.cpp // Boids // // Created by Yanjie Chen on 3/9/15. // // #include "AudioManager.h" #include "audio/include/SimpleAudioEngine.h" #include "audio/include/AudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; using namespace experimental; AudioManager* AudioManager::_instance = nullptr; AudioManager::AudioManager() { } AudioManager::~AudioManager() { } AudioManager* AudioManager::getInstance() { if( _instance == nullptr ) { _instance = new AudioManager(); } return _instance; } void AudioManager::destroy() { if( _instance ) { delete _instance; _instance = nullptr; } } void AudioManager::reset() { this->stopAll(); } bool AudioManager::playMusic( const std::string& resource, bool loop ) { if( FileUtils::getInstance()->isFileExist( resource ) ) { SimpleAudioEngine::getInstance()->playBackgroundMusic( resource.c_str(), loop ); return true; } return false; } bool AudioManager::playEffect( const std::string& resource, bool loop ) { if( FileUtils::getInstance()->isFileExist( resource ) ) { int aid = SimpleAudioEngine::getInstance()->playEffect( resource.c_str() ); _audio_ids[resource] = Value( aid ); return true; } return false; } void AudioManager::pauseMusic( const std::string& resource ) { SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } void AudioManager::resumeMusic( const std::string& resource ) { SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } void AudioManager::stopMusic( const std::string& resource ) { SimpleAudioEngine::getInstance()->stopBackgroundMusic(); } void AudioManager::stopEffect( const std::string& resource ) { auto itr = _audio_ids.find( resource ); if( itr != _audio_ids.end() ) { SimpleAudioEngine::getInstance()->stopEffect( itr->second.asInt() ); _audio_ids.erase( itr ); } } bool AudioManager::vibrate() { AudioEngine::vibrate(); return true; } void AudioManager::stopAll() { SimpleAudioEngine::getInstance()->stopAllEffects(); SimpleAudioEngine::getInstance()->stopBackgroundMusic(); AudioEngine::stopAll(); _audio_ids.clear(); }
// Copyright Epic Games, Inc. All Rights Reserved. #include "TempCapstoneProjectGameMode.h" #include "TempCapstoneProjectCharacter.h" #include "DummyPawn.h" #include "UObject/ConstructorHelpers.h" #include "SplitScreenGameViewportClient.h" #include "TempCapstoneProjectGameState.h" #include "Engine/LevelStreaming.h" #include "Kismet/GameplayStatics.h" #include "GameFramework/PlayerStart.h" ATempCapstoneProjectGameMode::ATempCapstoneProjectGameMode() { // Get all our required bps and controllers static ConstructorHelpers::FClassFinder<ACharacter> PaladinBP_Getter(TEXT("/Game/Blueprints/Characters/BP_PaladinCharacter")); static ConstructorHelpers::FClassFinder<ACharacter> RogueBP_Getter(TEXT("/Game/Blueprints/Characters/BP_RogueCharacter")); static ConstructorHelpers::FClassFinder<APawn> DummyLocalBP_Getter(TEXT("/Game/Blueprints/Characters/BP_DummyPawn")); if (DummyLocalBP_Getter.Class != NULL) { pDummyBP = DummyLocalBP_Getter.Class; } if (PaladinBP_Getter.Class != NULL) { pPaladinBP = PaladinBP_Getter.Class; } if (RogueBP_Getter.Class != NULL) { pRogueBP = RogueBP_Getter.Class; } bStartPlayersAsSpectators = true; } // Called when the game starts or when spawned void ATempCapstoneProjectGameMode::BeginPlay() { Super::BeginPlay(); // Acquire pointer to Viewport client GameViewportClient = Cast<USplitScreenGameViewportClient>(GetWorld()->GetGameViewport()); } /// <summary> /// Intercept players PostLogin, wait until level has loaded before spawning their proper character based on their controller. /// </summary> void ATempCapstoneProjectGameMode::PostLogin(APlayerController* NewPlayer) { // In case we want to specify custom controller classes: // if (NewPlayer->GetLocalRole() == ROLE_Authority) // { // PlayerControllerClass = PlayerOneIsPaladin?pPaladinBPcontroller:pRogueBPcontroller; // } // if (NewPlayer->GetRemoteRole() < ROLE_Authority) // { // PlayerControllerClass = PlayerOneIsPaladin?pRogueBPcontroller:pPaladinBPcontroller; // } PlayerControllerList.Add(NewPlayer); NewPlayer->bBlockInput = true; Super::PostLogin(NewPlayer); if (!bLevelHasLoaded) { DelaySpawnUntilLevelLoaded(); } else { SpawnPawnAndPosess(NewPlayer); } } /// <summary> /// Check if the level has loaded every half a second. If it has, spawn every player contoller submitted. /// </summary> void ATempCapstoneProjectGameMode::DelaySpawnUntilLevelLoaded() { //GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, TEXT("Checking level loaded to spawn.")); TArray<ULevelStreaming*> levels = GetWorld()->GetStreamingLevels(); int LoadedCount = 0; if (levels.Num() != 0) { for (size_t i = 0; i < GetWorld()->GetStreamingLevels().Num(); i++) { if (levels[i]->GetCurrentState() == ULevelStreaming::ECurrentState::LoadedVisible) LoadedCount += 1; } } bLevelHasLoaded = LoadedCount == GetWorld()->GetStreamingLevels().Num(); if (bLevelHasLoaded) { for (size_t i = 0; i < PlayerControllerList.Num(); i++) { SpawnPawnAndPosess(PlayerControllerList[i]); } GetWorldTimerManager().ClearTimer(SpawnDelayHandle); return; } GetWorldTimerManager().SetTimer(SpawnDelayHandle, this, &ATempCapstoneProjectGameMode::DelaySpawnUntilLevelLoaded, 0.5f, false); } /// <summary> /// Helper function to spawn and posess the correct pawn based on the player's assigned controller. Also spawns a dummy pawn for Splitscreen purposes /// </summary> void ATempCapstoneProjectGameMode::SpawnPawnAndPosess(APlayerController* NewPlayer) { PlayerCount++; APawn* oldPawn = NewPlayer->GetPawnOrSpectator(); NewPlayer->UnPossess(); TArray<AActor*> FoundStartPoints; UGameplayStatics::GetAllActorsOfClass(GetWorld(), APlayerStart::StaticClass(), FoundStartPoints ); if (FoundStartPoints.Num() > 1) { AActor* PaladinStartPoint; AActor* RogueStartPoint; if (Cast<APlayerStart>(FoundStartPoints[0])->PlayerStartTag == "Paladin") { PaladinStartPoint = FoundStartPoints[0]; RogueStartPoint = FoundStartPoints[1]; } else { PaladinStartPoint = FoundStartPoints[1]; RogueStartPoint = FoundStartPoints[0]; } // Oh god oh fuck switch (PlayerCount) { case 1: DefaultPawnClass = PlayerOneIsPaladin ? pPaladinBP : pRogueBP; RestartPlayerAtPlayerStart(NewPlayer, PlayerOneIsPaladin ? PaladinStartPoint : RogueStartPoint); break; case 2: DefaultPawnClass = pDummyBP; RestartPlayerAtPlayerStart(NewPlayer, PlayerOneIsPaladin ? PaladinStartPoint : RogueStartPoint); break; case 3: DefaultPawnClass = !PlayerOneIsPaladin ? pPaladinBP : pRogueBP; RestartPlayerAtPlayerStart(NewPlayer, !PlayerOneIsPaladin ? PaladinStartPoint : RogueStartPoint); break; case 4: DefaultPawnClass = pDummyBP; RestartPlayerAtPlayerStart(NewPlayer, !PlayerOneIsPaladin ? PaladinStartPoint : RogueStartPoint); // everyone's in the game, setup dummy pawns Cast<ADummyPawn>(PlayerControllerList[1]->GetPawn())->SetupDummyPawn( Cast<ATempCapstoneProjectCharacter>(PlayerControllerList[2]->GetCharacter()) ); Cast<ADummyPawn>(PlayerControllerList[3]->GetPawn())->SetupDummyPawn( Cast<ATempCapstoneProjectCharacter>(PlayerControllerList[0]->GetCharacter()) ); SetSplitscreenBias(1, 0, true); break; } } // if (oldPawn) // oldPawn->Destroy(); // /// Spawn Player // { // APawn* oldPawn = NewPlayer->GetPawnOrSpectator(); // NewPlayer->UnPossess(); // // // hacking in player pawn selection // DefaultPawnClass = // PlayerCount == 1 ? // PlayerOneIsPaladin ? pPaladinBP : pRogueBP: // PlayerOneIsPaladin ? pRogueBP : pPaladinBP; // // RestartPlayer(NewPlayer); // // // FString s; // // ULocalPlayer* x = GetGameInstance()->CreateLocalPlayer(PlayerCount + 2, s, false); // // RestartPlayer(x->GetPlayerController(GetWorld())); // // if (oldPawn) // oldPawn->Destroy(); // } // workaround for prototype: grab spawned character and possess } void ATempCapstoneProjectGameMode::SetSplitscreenBias(float TargetBias, float TransitionDuration, bool Symmetrical, EScreenDividerMovementStyle TransitionStyle) { GetGameState<ATempCapstoneProjectGameState>()->SetSplitscreenBias(TargetBias, TransitionDuration, Symmetrical, TransitionStyle); } // CODE DUMP ///shadowstalk code dump // if (ASTK_EntityCharacterMonsterController* monsterController = dynamic_cast<ASTK_EntityCharacterMonsterController*>(NewPlayer)) // { // APawn* oldPawn = monsterController->GetPawnOrSpectator(); // // monsterController->UnPossess(); // // DefaultPawnClass = pMonsterBP; // RestartPlayer(monsterController); // // if (oldPawn) // oldPawn->Destroy(); // // monsterController->bBlockInput = false; // } // else if (ASTK_EntityCharacterShadeController* shadeController = dynamic_cast<ASTK_EntityCharacterShadeController*>(NewPlayer)) // { // APawn* oldPawn = shadeController->GetPawnOrSpectator(); // // shadeController->UnPossess(); // // DefaultPawnClass = pShadeBP; // RestartPlayer(shadeController); // // if (oldPawn) // oldPawn->Destroy(); // // shadeController->bBlockInput = false; // } // /// Spawn Dummy Pawn // { // ATempCapstoneProjectCharacter* NewCharacter = Cast<ATempCapstoneProjectCharacter>(NewPlayer->GetCharacter()); // FActorSpawnParameters params; // params.bNoFail = true; // params.Owner = NewCharacter; // // UClass* PawnClass = pDummyBP->GetClass(); // ADummyPawn* DummyPawn = GetWorld()->SpawnActor<ADummyPawn>(NewCharacter->GetActorLocation(), NewCharacter->GetActorRotation(), params); // ADummyPawn* DummyPawn = GetWorld()->SpawnActor<ADummyPawn>(PawnClass, &NewCharacter->GetTransform(), params); // ADummyPawn* DummyPawn = Cast<ADummyPawn>(GetWorld()->SpawnActor(pDummyBP->GetClass(), &NewCharacter->GetTransform(), params)); // DefaultPawnClass = pDummyBP; // FString ErrorMsg; // ULocalPlayer* Dummy = GetWorld()->GetGameInstance()->CreateLocalPlayer(PlayerCount + 2, ErrorMsg, true); // Dummy->GetPlayerController(GetWorld())->Possess(DummyPawn); // DummyPawn->SetupDummyPawn(NewCharacter); // This calls SetupDummyPawn on a DummyPawn actor that gets spawned, passing in the new character. // Cast<ADummyPawn>(UGameplayStatics::CreatePlayer(GetWorld(), -1, true)->GetPawn())->SetupDummyPawn(Cast<ATempCapstoneProjectCharacter>(NewPlayer->GetCharacter())); // } /* if (DefaultPawnClass == pDummyBP) { APawn* oldPawn = NewPlayer->GetPawnOrSpectator(); NewPlayer->UnPossess(); RestartPlayer(NewPlayer); if (oldPawn) oldPawn->Destroy(); DefaultPawnClass = pPaladinBP; } else { PlayerCount++; // hacking in player pawn selection DefaultPawnClass = PlayerCount == 1 ? PlayerOneIsPaladin ? pPaladinBP : pRogueBP : PlayerOneIsPaladin ? pRogueBP : pPaladinBP; /// Spawn Player APawn* oldPawn = NewPlayer->GetPawnOrSpectator(); NewPlayer->UnPossess(); RestartPlayer(NewPlayer); if (oldPawn) oldPawn->Destroy(); DefaultPawnClass = pDummyBP; UGameplayStatics::CreatePlayer(GetWorld(), PlayerCount + 2); }*/
#include<stdio.h> int print1(); int print2(); int main(){ char a[10]="hhh"; char b[10]="hhh"; if(a==b) printf("nkfndknfk"); print1(); print1(); print2(); print2(); return 0; } int print1(){ static int x=10; x +=5; printf("%d ",x); } int print2(){ static int x; x=10; x+=5; printf("%d ",x); }
/******************************************************************************** ** Form generated from reading UI file 'PointCloudTools.ui' ** ** Created by: Qt User Interface Compiler version 5.7.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_POINTCLOUDTOOLS_H #define UI_POINTCLOUDTOOLS_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QDockWidget> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLCDNumber> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QRadioButton> #include <QtWidgets/QSlider> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTableWidget> #include <QtWidgets/QToolBar> #include <QtWidgets/QTreeWidget> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> #include "QVTKWidget.h" QT_BEGIN_NAMESPACE class Ui_PointCloudToolsClass { public: QAction *openAction; QAction *saveAction; QAction *saveasAction; QAction *cubeAction; QAction *helpAction; QAction *aboutAction; QAction *exitAction; QAction *pointcolorAction; QAction *bgcolorAction; QAction *mainviewAction; QAction *leftviewAction; QAction *topviewAction; QAction *dataAction; QAction *propertyAction; QAction *consoleAction; QAction *RGBAction; QAction *clearAction; QAction *sphereAction; QAction *cylinderAction; QAction *meshsurfaceAction; QAction *wireframeAction; QAction *windowsThemeAction; QAction *darculaThemeAction; QAction *englishAction; QAction *chineseAction; QAction *saveBinaryAction; QAction *filterAction; QAction *voxelAction; QWidget *centralWidget; QHBoxLayout *horizontalLayout_2; QVTKWidget *screen; QMenuBar *menuBar; QMenu *menuFile; QMenu *menuGenerate; QMenu *menuAbout; QMenu *menuOption; QMenu *themeAction; QMenu *langAction; QMenu *menuView; QMenu *menuAngle_view; QMenu *menuView_2; QMenu *menuProcess; QToolBar *mainToolBar; QStatusBar *statusBar; QDockWidget *imageDock; QWidget *dockWidgetContents_4; QVBoxLayout *verticalLayout_2; QLabel *imageDepth; QPushButton *colormapBtn; QLabel *imageColor; QPushButton *convertBtn; QDockWidget *dataDock; QWidget *dockWidgetContents_5; QVBoxLayout *verticalLayout_3; QTreeWidget *dataTree; QDockWidget *propertyDock; QWidget *dockWidgetContents_6; QWidget *gridLayoutWidget; QGridLayout *gridLayout; QLabel *label_2; QLineEdit *fyLineedit; QLineEdit *k2Lineedit; QLabel *label_4; QLabel *label_6; QLineEdit *cxLineedit; QLineEdit *p1Lineedit; QLabel *label_8; QLabel *label_7; QLabel *label_9; QLineEdit *cyLineedit; QLineEdit *p2Lineedit; QLabel *label_3; QLineEdit *fxLineedit; QLineEdit *k1Lineedit; QLabel *label; QLabel *label_10; QLineEdit *aLineedit; QLabel *label_11; QLineEdit *k3Lineedit; QDockWidget *consoleDock; QWidget *dockWidgetContents_7; QVBoxLayout *verticalLayout_5; QTableWidget *consoleTable; QDockWidget *RGBDock; QWidget *dockWidgetContents; QVBoxLayout *verticalLayout_4; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label_14; QLCDNumber *sizeLCD; QSlider *pSlider; QHBoxLayout *horizontalLayout_6; QLabel *label_5; QRadioButton *colormap_x; QRadioButton *colormap_y; QRadioButton *colormap_z; QHBoxLayout *horizontalLayout_7; QLineEdit *colorMapLeft; QLineEdit *colorMapRight; QPushButton *colorBtn; QCheckBox *cooCbx; void setupUi(QMainWindow *PointCloudToolsClass) { if (PointCloudToolsClass->objectName().isEmpty()) PointCloudToolsClass->setObjectName(QStringLiteral("PointCloudToolsClass")); PointCloudToolsClass->resize(1295, 802); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy.setHorizontalStretch(85); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(PointCloudToolsClass->sizePolicy().hasHeightForWidth()); PointCloudToolsClass->setSizePolicy(sizePolicy); PointCloudToolsClass->setMinimumSize(QSize(900, 650)); PointCloudToolsClass->setMaximumSize(QSize(16777215, 16777215)); PointCloudToolsClass->setStyleSheet(QStringLiteral("")); PointCloudToolsClass->setAnimated(true); PointCloudToolsClass->setTabShape(QTabWidget::Rounded); PointCloudToolsClass->setDockNestingEnabled(false); openAction = new QAction(PointCloudToolsClass); openAction->setObjectName(QStringLiteral("openAction")); QIcon icon; icon.addFile(QStringLiteral(":/Resources/images/open.png"), QSize(), QIcon::Normal, QIcon::Off); openAction->setIcon(icon); saveAction = new QAction(PointCloudToolsClass); saveAction->setObjectName(QStringLiteral("saveAction")); QIcon icon1; icon1.addFile(QStringLiteral(":/Resources/images/save.png"), QSize(), QIcon::Normal, QIcon::Off); saveAction->setIcon(icon1); saveasAction = new QAction(PointCloudToolsClass); saveasAction->setObjectName(QStringLiteral("saveasAction")); cubeAction = new QAction(PointCloudToolsClass); cubeAction->setObjectName(QStringLiteral("cubeAction")); QIcon icon2; icon2.addFile(QStringLiteral(":/Resources/images/cube.png"), QSize(), QIcon::Normal, QIcon::Off); cubeAction->setIcon(icon2); helpAction = new QAction(PointCloudToolsClass); helpAction->setObjectName(QStringLiteral("helpAction")); QIcon icon3; icon3.addFile(QStringLiteral(":/Resources/images/help.png"), QSize(), QIcon::Normal, QIcon::Off); helpAction->setIcon(icon3); aboutAction = new QAction(PointCloudToolsClass); aboutAction->setObjectName(QStringLiteral("aboutAction")); QIcon icon4; icon4.addFile(QStringLiteral(":/Resources/images/about.png"), QSize(), QIcon::Normal, QIcon::Off); aboutAction->setIcon(icon4); exitAction = new QAction(PointCloudToolsClass); exitAction->setObjectName(QStringLiteral("exitAction")); QIcon icon5; icon5.addFile(QStringLiteral(":/Resources/images/exit.png"), QSize(), QIcon::Normal, QIcon::Off); exitAction->setIcon(icon5); pointcolorAction = new QAction(PointCloudToolsClass); pointcolorAction->setObjectName(QStringLiteral("pointcolorAction")); QIcon icon6; icon6.addFile(QStringLiteral(":/Resources/images/pointcolor.png"), QSize(), QIcon::Normal, QIcon::Off); pointcolorAction->setIcon(icon6); bgcolorAction = new QAction(PointCloudToolsClass); bgcolorAction->setObjectName(QStringLiteral("bgcolorAction")); QIcon icon7; icon7.addFile(QStringLiteral(":/Resources/images/bgcolor.png"), QSize(), QIcon::Normal, QIcon::Off); bgcolorAction->setIcon(icon7); mainviewAction = new QAction(PointCloudToolsClass); mainviewAction->setObjectName(QStringLiteral("mainviewAction")); QIcon icon8; icon8.addFile(QStringLiteral(":/Resources/images/mainview.png"), QSize(), QIcon::Normal, QIcon::Off); mainviewAction->setIcon(icon8); leftviewAction = new QAction(PointCloudToolsClass); leftviewAction->setObjectName(QStringLiteral("leftviewAction")); QIcon icon9; icon9.addFile(QStringLiteral(":/Resources/images/leftview.png"), QSize(), QIcon::Normal, QIcon::Off); leftviewAction->setIcon(icon9); topviewAction = new QAction(PointCloudToolsClass); topviewAction->setObjectName(QStringLiteral("topviewAction")); QIcon icon10; icon10.addFile(QStringLiteral(":/Resources/images/topview.png"), QSize(), QIcon::Normal, QIcon::Off); topviewAction->setIcon(icon10); dataAction = new QAction(PointCloudToolsClass); dataAction->setObjectName(QStringLiteral("dataAction")); dataAction->setCheckable(true); dataAction->setChecked(true); propertyAction = new QAction(PointCloudToolsClass); propertyAction->setObjectName(QStringLiteral("propertyAction")); propertyAction->setCheckable(true); propertyAction->setChecked(true); consoleAction = new QAction(PointCloudToolsClass); consoleAction->setObjectName(QStringLiteral("consoleAction")); consoleAction->setCheckable(true); consoleAction->setChecked(true); RGBAction = new QAction(PointCloudToolsClass); RGBAction->setObjectName(QStringLiteral("RGBAction")); RGBAction->setCheckable(true); RGBAction->setChecked(true); clearAction = new QAction(PointCloudToolsClass); clearAction->setObjectName(QStringLiteral("clearAction")); QIcon icon11; icon11.addFile(QStringLiteral(":/Resources/images/clean.png"), QSize(), QIcon::Normal, QIcon::Off); clearAction->setIcon(icon11); sphereAction = new QAction(PointCloudToolsClass); sphereAction->setObjectName(QStringLiteral("sphereAction")); QIcon icon12; icon12.addFile(QStringLiteral(":/Resources/images/sphere.png"), QSize(), QIcon::Normal, QIcon::Off); sphereAction->setIcon(icon12); cylinderAction = new QAction(PointCloudToolsClass); cylinderAction->setObjectName(QStringLiteral("cylinderAction")); QIcon icon13; icon13.addFile(QStringLiteral(":/Resources/images/sylinder.png"), QSize(), QIcon::Normal, QIcon::Off); cylinderAction->setIcon(icon13); meshsurfaceAction = new QAction(PointCloudToolsClass); meshsurfaceAction->setObjectName(QStringLiteral("meshsurfaceAction")); QIcon icon14; icon14.addFile(QStringLiteral(":/Resources/images/meshsurface.png"), QSize(), QIcon::Normal, QIcon::Off); meshsurfaceAction->setIcon(icon14); wireframeAction = new QAction(PointCloudToolsClass); wireframeAction->setObjectName(QStringLiteral("wireframeAction")); QIcon icon15; icon15.addFile(QStringLiteral(":/Resources/images/wireframe.png"), QSize(), QIcon::Normal, QIcon::Off); wireframeAction->setIcon(icon15); windowsThemeAction = new QAction(PointCloudToolsClass); windowsThemeAction->setObjectName(QStringLiteral("windowsThemeAction")); darculaThemeAction = new QAction(PointCloudToolsClass); darculaThemeAction->setObjectName(QStringLiteral("darculaThemeAction")); englishAction = new QAction(PointCloudToolsClass); englishAction->setObjectName(QStringLiteral("englishAction")); chineseAction = new QAction(PointCloudToolsClass); chineseAction->setObjectName(QStringLiteral("chineseAction")); saveBinaryAction = new QAction(PointCloudToolsClass); saveBinaryAction->setObjectName(QStringLiteral("saveBinaryAction")); QIcon icon16; icon16.addFile(QStringLiteral(":/Resources/images/saveBinary.png"), QSize(), QIcon::Normal, QIcon::Off); saveBinaryAction->setIcon(icon16); filterAction = new QAction(PointCloudToolsClass); filterAction->setObjectName(QStringLiteral("filterAction")); QIcon icon17; icon17.addFile(QStringLiteral(":/Resources/images/filter.png"), QSize(), QIcon::Normal, QIcon::Off); filterAction->setIcon(icon17); voxelAction = new QAction(PointCloudToolsClass); voxelAction->setObjectName(QStringLiteral("voxelAction")); QIcon icon18; icon18.addFile(QStringLiteral(":/Resources/images/voxel.png"), QSize(), QIcon::Normal, QIcon::Off); voxelAction->setIcon(icon18); centralWidget = new QWidget(PointCloudToolsClass); centralWidget->setObjectName(QStringLiteral("centralWidget")); QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(centralWidget->sizePolicy().hasHeightForWidth()); centralWidget->setSizePolicy(sizePolicy1); horizontalLayout_2 = new QHBoxLayout(centralWidget); horizontalLayout_2->setSpacing(6); horizontalLayout_2->setContentsMargins(11, 11, 11, 11); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); screen = new QVTKWidget(centralWidget); screen->setObjectName(QStringLiteral("screen")); screen->setMinimumSize(QSize(600, 400)); horizontalLayout_2->addWidget(screen); PointCloudToolsClass->setCentralWidget(centralWidget); menuBar = new QMenuBar(PointCloudToolsClass); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1295, 23)); QFont font; font.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221")); menuBar->setFont(font); menuFile = new QMenu(menuBar); menuFile->setObjectName(QStringLiteral("menuFile")); menuGenerate = new QMenu(menuBar); menuGenerate->setObjectName(QStringLiteral("menuGenerate")); menuAbout = new QMenu(menuBar); menuAbout->setObjectName(QStringLiteral("menuAbout")); menuOption = new QMenu(menuBar); menuOption->setObjectName(QStringLiteral("menuOption")); themeAction = new QMenu(menuOption); themeAction->setObjectName(QStringLiteral("themeAction")); QIcon icon19; icon19.addFile(QStringLiteral(":/Resources/images/theme.png"), QSize(), QIcon::Normal, QIcon::Off); themeAction->setIcon(icon19); langAction = new QMenu(menuOption); langAction->setObjectName(QStringLiteral("langAction")); QIcon icon20; icon20.addFile(QStringLiteral(":/Resources/images/language.png"), QSize(), QIcon::Normal, QIcon::Off); langAction->setIcon(icon20); menuView = new QMenu(menuBar); menuView->setObjectName(QStringLiteral("menuView")); menuAngle_view = new QMenu(menuView); menuAngle_view->setObjectName(QStringLiteral("menuAngle_view")); menuView_2 = new QMenu(menuBar); menuView_2->setObjectName(QStringLiteral("menuView_2")); menuProcess = new QMenu(menuBar); menuProcess->setObjectName(QStringLiteral("menuProcess")); PointCloudToolsClass->setMenuBar(menuBar); mainToolBar = new QToolBar(PointCloudToolsClass); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); PointCloudToolsClass->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(PointCloudToolsClass); statusBar->setObjectName(QStringLiteral("statusBar")); PointCloudToolsClass->setStatusBar(statusBar); imageDock = new QDockWidget(PointCloudToolsClass); imageDock->setObjectName(QStringLiteral("imageDock")); imageDock->setMinimumSize(QSize(338, 584)); imageDock->setMaximumSize(QSize(338, 524287)); dockWidgetContents_4 = new QWidget(); dockWidgetContents_4->setObjectName(QStringLiteral("dockWidgetContents_4")); verticalLayout_2 = new QVBoxLayout(dockWidgetContents_4); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); imageDepth = new QLabel(dockWidgetContents_4); imageDepth->setObjectName(QStringLiteral("imageDepth")); imageDepth->setMinimumSize(QSize(320, 240)); imageDepth->setMaximumSize(QSize(320, 240)); imageDepth->setAlignment(Qt::AlignCenter); verticalLayout_2->addWidget(imageDepth); colormapBtn = new QPushButton(dockWidgetContents_4); colormapBtn->setObjectName(QStringLiteral("colormapBtn")); verticalLayout_2->addWidget(colormapBtn); imageColor = new QLabel(dockWidgetContents_4); imageColor->setObjectName(QStringLiteral("imageColor")); imageColor->setMinimumSize(QSize(320, 240)); imageColor->setMaximumSize(QSize(320, 240)); imageColor->setAlignment(Qt::AlignCenter); verticalLayout_2->addWidget(imageColor); convertBtn = new QPushButton(dockWidgetContents_4); convertBtn->setObjectName(QStringLiteral("convertBtn")); verticalLayout_2->addWidget(convertBtn); imageDock->setWidget(dockWidgetContents_4); PointCloudToolsClass->addDockWidget(static_cast<Qt::DockWidgetArea>(2), imageDock); dataDock = new QDockWidget(PointCloudToolsClass); dataDock->setObjectName(QStringLiteral("dataDock")); dataDock->setMinimumSize(QSize(250, 150)); dataDock->setMaximumSize(QSize(300, 524287)); QFont font1; font1.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221")); font1.setPointSize(10); dataDock->setFont(font1); dockWidgetContents_5 = new QWidget(); dockWidgetContents_5->setObjectName(QStringLiteral("dockWidgetContents_5")); verticalLayout_3 = new QVBoxLayout(dockWidgetContents_5); verticalLayout_3->setSpacing(6); verticalLayout_3->setContentsMargins(11, 11, 11, 11); verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3")); dataTree = new QTreeWidget(dockWidgetContents_5); dataTree->setObjectName(QStringLiteral("dataTree")); dataTree->setMinimumSize(QSize(0, 100)); QFont font2; font2.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221")); font2.setPointSize(9); dataTree->setFont(font2); dataTree->setContextMenuPolicy(Qt::CustomContextMenu); verticalLayout_3->addWidget(dataTree); dataDock->setWidget(dockWidgetContents_5); PointCloudToolsClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), dataDock); propertyDock = new QDockWidget(PointCloudToolsClass); propertyDock->setObjectName(QStringLiteral("propertyDock")); sizePolicy1.setHeightForWidth(propertyDock->sizePolicy().hasHeightForWidth()); propertyDock->setSizePolicy(sizePolicy1); propertyDock->setMinimumSize(QSize(250, 186)); propertyDock->setMaximumSize(QSize(250, 186)); propertyDock->setFont(font1); dockWidgetContents_6 = new QWidget(); dockWidgetContents_6->setObjectName(QStringLiteral("dockWidgetContents_6")); gridLayoutWidget = new QWidget(dockWidgetContents_6); gridLayoutWidget->setObjectName(QStringLiteral("gridLayoutWidget")); gridLayoutWidget->setGeometry(QRect(10, 0, 231, 151)); gridLayout = new QGridLayout(gridLayoutWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); label_2 = new QLabel(gridLayoutWidget); label_2->setObjectName(QStringLiteral("label_2")); gridLayout->addWidget(label_2, 0, 2, 1, 1); fyLineedit = new QLineEdit(gridLayoutWidget); fyLineedit->setObjectName(QStringLiteral("fyLineedit")); gridLayout->addWidget(fyLineedit, 1, 1, 1, 1); k2Lineedit = new QLineEdit(gridLayoutWidget); k2Lineedit->setObjectName(QStringLiteral("k2Lineedit")); gridLayout->addWidget(k2Lineedit, 1, 3, 1, 1); label_4 = new QLabel(gridLayoutWidget); label_4->setObjectName(QStringLiteral("label_4")); gridLayout->addWidget(label_4, 1, 2, 1, 1); label_6 = new QLabel(gridLayoutWidget); label_6->setObjectName(QStringLiteral("label_6")); gridLayout->addWidget(label_6, 2, 0, 1, 1); cxLineedit = new QLineEdit(gridLayoutWidget); cxLineedit->setObjectName(QStringLiteral("cxLineedit")); gridLayout->addWidget(cxLineedit, 2, 1, 1, 1); p1Lineedit = new QLineEdit(gridLayoutWidget); p1Lineedit->setObjectName(QStringLiteral("p1Lineedit")); gridLayout->addWidget(p1Lineedit, 2, 3, 1, 1); label_8 = new QLabel(gridLayoutWidget); label_8->setObjectName(QStringLiteral("label_8")); gridLayout->addWidget(label_8, 3, 0, 1, 1); label_7 = new QLabel(gridLayoutWidget); label_7->setObjectName(QStringLiteral("label_7")); gridLayout->addWidget(label_7, 2, 2, 1, 1); label_9 = new QLabel(gridLayoutWidget); label_9->setObjectName(QStringLiteral("label_9")); gridLayout->addWidget(label_9, 3, 2, 1, 1); cyLineedit = new QLineEdit(gridLayoutWidget); cyLineedit->setObjectName(QStringLiteral("cyLineedit")); gridLayout->addWidget(cyLineedit, 3, 1, 1, 1); p2Lineedit = new QLineEdit(gridLayoutWidget); p2Lineedit->setObjectName(QStringLiteral("p2Lineedit")); gridLayout->addWidget(p2Lineedit, 3, 3, 1, 1); label_3 = new QLabel(gridLayoutWidget); label_3->setObjectName(QStringLiteral("label_3")); gridLayout->addWidget(label_3, 1, 0, 1, 1); fxLineedit = new QLineEdit(gridLayoutWidget); fxLineedit->setObjectName(QStringLiteral("fxLineedit")); gridLayout->addWidget(fxLineedit, 0, 1, 1, 1); k1Lineedit = new QLineEdit(gridLayoutWidget); k1Lineedit->setObjectName(QStringLiteral("k1Lineedit")); gridLayout->addWidget(k1Lineedit, 0, 3, 1, 1); label = new QLabel(gridLayoutWidget); label->setObjectName(QStringLiteral("label")); gridLayout->addWidget(label, 0, 0, 1, 1); label_10 = new QLabel(gridLayoutWidget); label_10->setObjectName(QStringLiteral("label_10")); gridLayout->addWidget(label_10, 4, 0, 1, 1); aLineedit = new QLineEdit(gridLayoutWidget); aLineedit->setObjectName(QStringLiteral("aLineedit")); gridLayout->addWidget(aLineedit, 4, 1, 1, 1); label_11 = new QLabel(gridLayoutWidget); label_11->setObjectName(QStringLiteral("label_11")); gridLayout->addWidget(label_11, 4, 2, 1, 1); k3Lineedit = new QLineEdit(gridLayoutWidget); k3Lineedit->setObjectName(QStringLiteral("k3Lineedit")); gridLayout->addWidget(k3Lineedit, 4, 3, 1, 1); propertyDock->setWidget(dockWidgetContents_6); PointCloudToolsClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), propertyDock); consoleDock = new QDockWidget(PointCloudToolsClass); consoleDock->setObjectName(QStringLiteral("consoleDock")); consoleDock->setMinimumSize(QSize(200, 111)); consoleDock->setMaximumSize(QSize(524287, 220)); dockWidgetContents_7 = new QWidget(); dockWidgetContents_7->setObjectName(QStringLiteral("dockWidgetContents_7")); verticalLayout_5 = new QVBoxLayout(dockWidgetContents_7); verticalLayout_5->setSpacing(6); verticalLayout_5->setContentsMargins(11, 11, 11, 11); verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5")); consoleTable = new QTableWidget(dockWidgetContents_7); if (consoleTable->columnCount() < 5) consoleTable->setColumnCount(5); QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem(); __qtablewidgetitem->setTextAlignment(Qt::AlignLeading|Qt::AlignVCenter); consoleTable->setHorizontalHeaderItem(0, __qtablewidgetitem); QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem(); __qtablewidgetitem1->setTextAlignment(Qt::AlignLeading|Qt::AlignVCenter); consoleTable->setHorizontalHeaderItem(1, __qtablewidgetitem1); QTableWidgetItem *__qtablewidgetitem2 = new QTableWidgetItem(); __qtablewidgetitem2->setTextAlignment(Qt::AlignLeading|Qt::AlignVCenter); consoleTable->setHorizontalHeaderItem(2, __qtablewidgetitem2); QTableWidgetItem *__qtablewidgetitem3 = new QTableWidgetItem(); __qtablewidgetitem3->setTextAlignment(Qt::AlignLeading|Qt::AlignVCenter); consoleTable->setHorizontalHeaderItem(3, __qtablewidgetitem3); QTableWidgetItem *__qtablewidgetitem4 = new QTableWidgetItem(); __qtablewidgetitem4->setTextAlignment(Qt::AlignLeading|Qt::AlignVCenter); consoleTable->setHorizontalHeaderItem(4, __qtablewidgetitem4); consoleTable->setObjectName(QStringLiteral("consoleTable")); consoleTable->setShowGrid(false); consoleTable->setGridStyle(Qt::SolidLine); consoleTable->setRowCount(0); consoleTable->setColumnCount(5); consoleTable->horizontalHeader()->setVisible(true); consoleTable->horizontalHeader()->setDefaultSectionSize(200); consoleTable->horizontalHeader()->setStretchLastSection(true); consoleTable->verticalHeader()->setVisible(false); verticalLayout_5->addWidget(consoleTable); consoleDock->setWidget(dockWidgetContents_7); PointCloudToolsClass->addDockWidget(static_cast<Qt::DockWidgetArea>(8), consoleDock); RGBDock = new QDockWidget(PointCloudToolsClass); RGBDock->setObjectName(QStringLiteral("RGBDock")); RGBDock->setMinimumSize(QSize(250, 220)); RGBDock->setMaximumSize(QSize(250, 220)); RGBDock->setFont(font1); dockWidgetContents = new QWidget(); dockWidgetContents->setObjectName(QStringLiteral("dockWidgetContents")); verticalLayout_4 = new QVBoxLayout(dockWidgetContents); verticalLayout_4->setSpacing(6); verticalLayout_4->setContentsMargins(11, 11, 11, 11); verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4")); verticalLayout = new QVBoxLayout(); verticalLayout->setSpacing(6); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, -1, -1); label_14 = new QLabel(dockWidgetContents); label_14->setObjectName(QStringLiteral("label_14")); horizontalLayout->addWidget(label_14); sizeLCD = new QLCDNumber(dockWidgetContents); sizeLCD->setObjectName(QStringLiteral("sizeLCD")); sizeLCD->setAutoFillBackground(false); sizeLCD->setStyleSheet(QStringLiteral("gridline-color: rgb(255, 0, 255);")); sizeLCD->setSegmentStyle(QLCDNumber::Flat); sizeLCD->setProperty("intValue", QVariant(1)); horizontalLayout->addWidget(sizeLCD); verticalLayout->addLayout(horizontalLayout); pSlider = new QSlider(dockWidgetContents); pSlider->setObjectName(QStringLiteral("pSlider")); pSlider->setMinimum(1); pSlider->setMaximum(10); pSlider->setValue(1); pSlider->setOrientation(Qt::Horizontal); verticalLayout->addWidget(pSlider); horizontalLayout_6 = new QHBoxLayout(); horizontalLayout_6->setSpacing(6); horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6")); horizontalLayout_6->setSizeConstraint(QLayout::SetFixedSize); label_5 = new QLabel(dockWidgetContents); label_5->setObjectName(QStringLiteral("label_5")); label_5->setMaximumSize(QSize(16777215, 50)); label_5->setFont(font1); label_5->setCursor(QCursor(Qt::ArrowCursor)); horizontalLayout_6->addWidget(label_5); colormap_x = new QRadioButton(dockWidgetContents); colormap_x->setObjectName(QStringLiteral("colormap_x")); horizontalLayout_6->addWidget(colormap_x); colormap_y = new QRadioButton(dockWidgetContents); colormap_y->setObjectName(QStringLiteral("colormap_y")); horizontalLayout_6->addWidget(colormap_y); colormap_z = new QRadioButton(dockWidgetContents); colormap_z->setObjectName(QStringLiteral("colormap_z")); colormap_z->setChecked(true); horizontalLayout_6->addWidget(colormap_z); verticalLayout->addLayout(horizontalLayout_6); horizontalLayout_7 = new QHBoxLayout(); horizontalLayout_7->setSpacing(6); horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7")); colorMapLeft = new QLineEdit(dockWidgetContents); colorMapLeft->setObjectName(QStringLiteral("colorMapLeft")); horizontalLayout_7->addWidget(colorMapLeft); colorMapRight = new QLineEdit(dockWidgetContents); colorMapRight->setObjectName(QStringLiteral("colorMapRight")); horizontalLayout_7->addWidget(colorMapRight); verticalLayout->addLayout(horizontalLayout_7); colorBtn = new QPushButton(dockWidgetContents); colorBtn->setObjectName(QStringLiteral("colorBtn")); QFont font3; font3.setFamily(QStringLiteral("Times New Roman")); font3.setPointSize(11); colorBtn->setFont(font3); colorBtn->setStyleSheet(QStringLiteral("")); verticalLayout->addWidget(colorBtn); verticalLayout_4->addLayout(verticalLayout); cooCbx = new QCheckBox(dockWidgetContents); cooCbx->setObjectName(QStringLiteral("cooCbx")); cooCbx->setFont(font1); verticalLayout_4->addWidget(cooCbx); RGBDock->setWidget(dockWidgetContents); PointCloudToolsClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), RGBDock); #ifndef QT_NO_SHORTCUT label_2->setBuddy(k1Lineedit); label_4->setBuddy(k2Lineedit); label_6->setBuddy(cxLineedit); label_8->setBuddy(cyLineedit); label_7->setBuddy(p1Lineedit); label_9->setBuddy(p2Lineedit); label_3->setBuddy(fyLineedit); label->setBuddy(fxLineedit); label_10->setBuddy(aLineedit); label_11->setBuddy(k3Lineedit); label_5->setBuddy(colormap_x); #endif // QT_NO_SHORTCUT QWidget::setTabOrder(fxLineedit, fyLineedit); QWidget::setTabOrder(fyLineedit, cxLineedit); QWidget::setTabOrder(cxLineedit, cyLineedit); QWidget::setTabOrder(cyLineedit, aLineedit); QWidget::setTabOrder(aLineedit, k1Lineedit); QWidget::setTabOrder(k1Lineedit, k2Lineedit); QWidget::setTabOrder(k2Lineedit, p1Lineedit); QWidget::setTabOrder(p1Lineedit, p2Lineedit); QWidget::setTabOrder(p2Lineedit, k3Lineedit); QWidget::setTabOrder(k3Lineedit, colormap_x); QWidget::setTabOrder(colormap_x, colormap_y); QWidget::setTabOrder(colormap_y, colormap_z); QWidget::setTabOrder(colormap_z, colorMapLeft); QWidget::setTabOrder(colorMapLeft, colorMapRight); QWidget::setTabOrder(colorMapRight, colorBtn); QWidget::setTabOrder(colorBtn, cooCbx); QWidget::setTabOrder(cooCbx, consoleTable); QWidget::setTabOrder(consoleTable, dataTree); QWidget::setTabOrder(dataTree, convertBtn); menuBar->addAction(menuFile->menuAction()); menuBar->addAction(menuView->menuAction()); menuBar->addAction(menuView_2->menuAction()); menuBar->addAction(menuGenerate->menuAction()); menuBar->addAction(menuProcess->menuAction()); menuBar->addAction(menuOption->menuAction()); menuBar->addAction(menuAbout->menuAction()); menuFile->addAction(openAction); menuFile->addAction(clearAction); menuFile->addAction(saveAction); menuFile->addAction(saveBinaryAction); menuFile->addAction(exitAction); menuGenerate->addAction(cubeAction); menuGenerate->addAction(sphereAction); menuGenerate->addAction(cylinderAction); menuAbout->addAction(helpAction); menuAbout->addAction(aboutAction); menuOption->addAction(themeAction->menuAction()); menuOption->addAction(langAction->menuAction()); themeAction->addAction(windowsThemeAction); themeAction->addAction(darculaThemeAction); langAction->addAction(englishAction); langAction->addAction(chineseAction); menuView->addAction(pointcolorAction); menuView->addAction(bgcolorAction); menuView->addAction(menuAngle_view->menuAction()); menuAngle_view->addAction(mainviewAction); menuAngle_view->addAction(leftviewAction); menuAngle_view->addAction(topviewAction); menuView_2->addAction(dataAction); menuView_2->addAction(propertyAction); menuView_2->addAction(consoleAction); menuView_2->addAction(RGBAction); menuProcess->addAction(meshsurfaceAction); menuProcess->addAction(wireframeAction); menuProcess->addAction(filterAction); menuProcess->addAction(voxelAction); mainToolBar->addAction(openAction); mainToolBar->addAction(clearAction); mainToolBar->addAction(saveAction); mainToolBar->addAction(saveBinaryAction); mainToolBar->addSeparator(); mainToolBar->addAction(pointcolorAction); mainToolBar->addAction(bgcolorAction); mainToolBar->addSeparator(); mainToolBar->addAction(mainviewAction); mainToolBar->addAction(leftviewAction); mainToolBar->addAction(topviewAction); mainToolBar->addSeparator(); mainToolBar->addAction(cubeAction); mainToolBar->addAction(sphereAction); mainToolBar->addAction(cylinderAction); mainToolBar->addSeparator(); mainToolBar->addAction(meshsurfaceAction); mainToolBar->addAction(wireframeAction); mainToolBar->addAction(filterAction); mainToolBar->addAction(voxelAction); mainToolBar->addSeparator(); mainToolBar->addAction(helpAction); mainToolBar->addAction(aboutAction); retranslateUi(PointCloudToolsClass); QMetaObject::connectSlotsByName(PointCloudToolsClass); } // setupUi void retranslateUi(QMainWindow *PointCloudToolsClass) { PointCloudToolsClass->setWindowTitle(QApplication::translate("PointCloudToolsClass", "PointCloudTools", 0)); openAction->setText(QApplication::translate("PointCloudToolsClass", "Open", 0)); #ifndef QT_NO_STATUSTIP openAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "open a exsting file", 0)); #endif // QT_NO_STATUSTIP openAction->setShortcut(QApplication::translate("PointCloudToolsClass", "Ctrl+O", 0)); saveAction->setText(QApplication::translate("PointCloudToolsClass", "Save", 0)); #ifndef QT_NO_STATUSTIP saveAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "save point cloud file", 0)); #endif // QT_NO_STATUSTIP saveAction->setShortcut(QApplication::translate("PointCloudToolsClass", "Ctrl+S", 0)); saveasAction->setText(QApplication::translate("PointCloudToolsClass", "Save as...", 0)); cubeAction->setText(QApplication::translate("PointCloudToolsClass", "Generate cube", 0)); #ifndef QT_NO_STATUSTIP cubeAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "generate a cube point cloud", 0)); #endif // QT_NO_STATUSTIP helpAction->setText(QApplication::translate("PointCloudToolsClass", "Help", 0)); #ifndef QT_NO_STATUSTIP helpAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "show help information", 0)); #endif // QT_NO_STATUSTIP aboutAction->setText(QApplication::translate("PointCloudToolsClass", "About", 0)); #ifndef QT_NO_STATUSTIP aboutAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "show some information of the software", 0)); #endif // QT_NO_STATUSTIP exitAction->setText(QApplication::translate("PointCloudToolsClass", "Exit", 0)); exitAction->setShortcut(QApplication::translate("PointCloudToolsClass", "Ctrl+Q", 0)); pointcolorAction->setText(QApplication::translate("PointCloudToolsClass", "Point cloud color", 0)); #ifndef QT_NO_STATUSTIP pointcolorAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Change point cloud color", 0)); #endif // QT_NO_STATUSTIP bgcolorAction->setText(QApplication::translate("PointCloudToolsClass", "Background color", 0)); #ifndef QT_NO_STATUSTIP bgcolorAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Change background color", 0)); #endif // QT_NO_STATUSTIP mainviewAction->setText(QApplication::translate("PointCloudToolsClass", "Main view", 0)); leftviewAction->setText(QApplication::translate("PointCloudToolsClass", "Left view", 0)); topviewAction->setText(QApplication::translate("PointCloudToolsClass", "Top view", 0)); dataAction->setText(QApplication::translate("PointCloudToolsClass", "Data Manager", 0)); propertyAction->setText(QApplication::translate("PointCloudToolsClass", "Property Manager", 0)); consoleAction->setText(QApplication::translate("PointCloudToolsClass", "Console", 0)); RGBAction->setText(QApplication::translate("PointCloudToolsClass", "RGB Manager", 0)); clearAction->setText(QApplication::translate("PointCloudToolsClass", "Clear", 0)); #ifndef QT_NO_STATUSTIP clearAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Clear all opened files", 0)); #endif // QT_NO_STATUSTIP sphereAction->setText(QApplication::translate("PointCloudToolsClass", "Generate Sphere", 0)); #ifndef QT_NO_STATUSTIP sphereAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "generate a sphere point cloud", 0)); #endif // QT_NO_STATUSTIP cylinderAction->setText(QApplication::translate("PointCloudToolsClass", "Generate Cylinder", 0)); #ifndef QT_NO_STATUSTIP cylinderAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "generate a cylinder point cloud", 0)); #endif // QT_NO_STATUSTIP meshsurfaceAction->setText(QApplication::translate("PointCloudToolsClass", "Surface", 0)); wireframeAction->setText(QApplication::translate("PointCloudToolsClass", "Wireframe", 0)); windowsThemeAction->setText(QApplication::translate("PointCloudToolsClass", "Windows", 0)); darculaThemeAction->setText(QApplication::translate("PointCloudToolsClass", "Darcula", 0)); englishAction->setText(QApplication::translate("PointCloudToolsClass", "English", 0)); chineseAction->setText(QApplication::translate("PointCloudToolsClass", "Chinese", 0)); saveBinaryAction->setText(QApplication::translate("PointCloudToolsClass", "Save as binary", 0)); #ifndef QT_NO_STATUSTIP saveBinaryAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Save point cloud as binary file", 0)); #endif // QT_NO_STATUSTIP filterAction->setText(QApplication::translate("PointCloudToolsClass", "Filter", 0)); #ifndef QT_NO_TOOLTIP filterAction->setToolTip(QApplication::translate("PointCloudToolsClass", "Filter", 0)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_STATUSTIP filterAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Statistical outlier removal", 0)); #endif // QT_NO_STATUSTIP voxelAction->setText(QApplication::translate("PointCloudToolsClass", "Voxel", 0)); #ifndef QT_NO_TOOLTIP voxelAction->setToolTip(QApplication::translate("PointCloudToolsClass", "VoxelGrid", 0)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_STATUSTIP voxelAction->setStatusTip(QApplication::translate("PointCloudToolsClass", "Voxel grid filter", 0)); #endif // QT_NO_STATUSTIP menuFile->setTitle(QApplication::translate("PointCloudToolsClass", "File", 0)); menuGenerate->setTitle(QApplication::translate("PointCloudToolsClass", "Generate", 0)); menuAbout->setTitle(QApplication::translate("PointCloudToolsClass", "About", 0)); menuOption->setTitle(QApplication::translate("PointCloudToolsClass", "Option", 0)); themeAction->setTitle(QApplication::translate("PointCloudToolsClass", "Theme", 0)); langAction->setTitle(QApplication::translate("PointCloudToolsClass", "Language", 0)); menuView->setTitle(QApplication::translate("PointCloudToolsClass", "Display", 0)); menuAngle_view->setTitle(QApplication::translate("PointCloudToolsClass", "Angle view", 0)); menuView_2->setTitle(QApplication::translate("PointCloudToolsClass", "View", 0)); menuProcess->setTitle(QApplication::translate("PointCloudToolsClass", "Process", 0)); imageDock->setWindowTitle(QApplication::translate("PointCloudToolsClass", "Image", 0)); imageDepth->setText(QApplication::translate("PointCloudToolsClass", "Depth Image", 0)); colormapBtn->setText(QApplication::translate("PointCloudToolsClass", "Colormap", 0)); imageColor->setText(QApplication::translate("PointCloudToolsClass", "Colormap Image", 0)); convertBtn->setText(QApplication::translate("PointCloudToolsClass", "Convert", 0)); dataDock->setWindowTitle(QApplication::translate("PointCloudToolsClass", "Files", 0)); QTreeWidgetItem *___qtreewidgetitem = dataTree->headerItem(); ___qtreewidgetitem->setText(0, QApplication::translate("PointCloudToolsClass", "Files", 0)); propertyDock->setWindowTitle(QApplication::translate("PointCloudToolsClass", "Properties", 0)); label_2->setText(QApplication::translate("PointCloudToolsClass", "k1", 0)); fyLineedit->setText(QApplication::translate("PointCloudToolsClass", "1", 0)); k2Lineedit->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); label_4->setText(QApplication::translate("PointCloudToolsClass", "k2", 0)); label_6->setText(QApplication::translate("PointCloudToolsClass", "cx", 0)); cxLineedit->setText(QApplication::translate("PointCloudToolsClass", "160", 0)); p1Lineedit->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); label_8->setText(QApplication::translate("PointCloudToolsClass", "cy", 0)); label_7->setText(QApplication::translate("PointCloudToolsClass", "p1", 0)); label_9->setText(QApplication::translate("PointCloudToolsClass", "p2", 0)); cyLineedit->setText(QApplication::translate("PointCloudToolsClass", "120", 0)); p2Lineedit->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); label_3->setText(QApplication::translate("PointCloudToolsClass", "fy", 0)); fxLineedit->setText(QApplication::translate("PointCloudToolsClass", "1", 0)); k1Lineedit->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); label->setText(QApplication::translate("PointCloudToolsClass", "fx", 0)); label_10->setText(QApplication::translate("PointCloudToolsClass", "\316\261", 0)); aLineedit->setText(QApplication::translate("PointCloudToolsClass", "1", 0)); label_11->setText(QApplication::translate("PointCloudToolsClass", "k3", 0)); k3Lineedit->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); consoleDock->setWindowTitle(QApplication::translate("PointCloudToolsClass", "Console", 0)); QTableWidgetItem *___qtablewidgetitem = consoleTable->horizontalHeaderItem(0); ___qtablewidgetitem->setText(QApplication::translate("PointCloudToolsClass", "Time", 0)); QTableWidgetItem *___qtablewidgetitem1 = consoleTable->horizontalHeaderItem(1); ___qtablewidgetitem1->setText(QApplication::translate("PointCloudToolsClass", "Operation", 0)); QTableWidgetItem *___qtablewidgetitem2 = consoleTable->horizontalHeaderItem(2); ___qtablewidgetitem2->setText(QApplication::translate("PointCloudToolsClass", "Operation obeject", 0)); QTableWidgetItem *___qtablewidgetitem3 = consoleTable->horizontalHeaderItem(3); ___qtablewidgetitem3->setText(QApplication::translate("PointCloudToolsClass", "Details", 0)); QTableWidgetItem *___qtablewidgetitem4 = consoleTable->horizontalHeaderItem(4); ___qtablewidgetitem4->setText(QApplication::translate("PointCloudToolsClass", "Note", 0)); RGBDock->setWindowTitle(QApplication::translate("PointCloudToolsClass", "RGB", 0)); label_14->setText(QApplication::translate("PointCloudToolsClass", "Point Size", 0)); label_5->setText(QApplication::translate("PointCloudToolsClass", "Color Map", 0)); colormap_x->setText(QApplication::translate("PointCloudToolsClass", "X", 0)); colormap_y->setText(QApplication::translate("PointCloudToolsClass", "Y", 0)); colormap_z->setText(QApplication::translate("PointCloudToolsClass", "Z", 0)); colorMapLeft->setText(QApplication::translate("PointCloudToolsClass", "0", 0)); colorMapRight->setText(QApplication::translate("PointCloudToolsClass", "30000", 0)); colorBtn->setText(QApplication::translate("PointCloudToolsClass", "Color", 0)); cooCbx->setText(QApplication::translate("PointCloudToolsClass", "Coordinate", 0)); } // retranslateUi }; namespace Ui { class PointCloudToolsClass: public Ui_PointCloudToolsClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_POINTCLOUDTOOLS_H
#include<iostream> using namespace std; class Node{ private: int data; Node *next; public: Node(){ data=0; next=NULL; } int getData(){ return data; } void setData(int data){ this->data = data; } Node* getNext(){ return next; } void setNext(Node* temp){ next = temp; } }; class Linklist{ private: Node *head; Node *tail; int count; int count1; public: Linklist(){ head = NULL; tail = NULL; count = 0; count1 = 0; } ~Linklist(){ Node *temp; temp = head; while(head != NULL){ head = head->getNext(); delete temp; temp = head; } } bool isEmpty(){ return (head == NULL && tail==NULL); } int size(){ return count; } void AddBegin(int data){ Node *temp = new Node; if(isEmpty()){ temp->setNext(NULL); temp->setData(data); head = temp; tail = temp; }else{ temp->setNext(head); temp->setData(data); head = temp; } count++; } void AddEnd(int data){ Node *temp = new Node; if(isEmpty()){ temp->setNext(NULL); temp->setData(data); head = temp; tail = temp; }else{ tail->setNext(temp); temp->setNext(NULL); temp->setData(data); tail = temp; } count++; } void AddConsacative(){ Node *t = new Node; int sum = 0; t = head; while(t != NULL && t->getNext() != NULL){ sum = t->getData(); t = t->getNext(); sum = sum + t->getData(); Node *n = new Node; //t=NULL; n->setData(sum); n->setNext(t->getNext()); t->setNext(n); t = n->getNext(); sum = 0; //Display(); } } void Even(){ int pos = 1; Node *t = new Node; t = head; while(t != NULL){ if(pos%2 == 0){ cout<<"\t"<<t->getData(); } t = t->getNext(); pos++; } cout<<"\n"; } void AddEven(){ Node *temp = new Node; temp = head; int sum = 0; while(temp != NULL && temp->getNext() !-= NULL){ temp = temp->getNext(); if(temp != NULL){ sum = temp->getData(); temp = temp->getNext(); if(temp != NULL){ temp = temp->getNext(); if(temp != NULL){ sum = sum + temp->getData(); AddBegin(sum); } } } if(temp != NULL){ temp = temp->getNext(); } } } void Display(){ Node *temp = new Node; if(isEmpty()){ cout<<"\nList is Empty."; }else{ temp = head; while(temp != NULL){ cout<<"\n"<<temp->getData(); temp = temp->getNext(); } } cout<<endl; } Node* getHead(){ return head; } }; int main(){ Linklist ll; int ch = 0; char loop = 1; int data; int pos; while(loop){ cout<<"Menu:\n1.AddBegin\n2.AddEnd\n3.Add consacative and add result after it\n4.Display Even Node\n5.Display\n6.Add Even Node and add result at begin\n11.Exit\n"; cin>>ch; switch(ch){ case 1: cout<<"Enter Element : \n"; cin>>data; ll.AddBegin(data); break; case 2: cout<<"Enter Element : \n"; cin>>data; ll.AddEnd(data); break; case 3: ll.AddConsacative(); break; case 4: ll.Even(); break; case 6: ll.AddEven(); break; case 5: ll.Display(); break; case 11: loop = 0; break; default: cout<<"Enter correct choice..."; } } return 0; }
// // Copyright (C) 2017 Ruslan Manaev (manavrion@yandex.com) // This file is part of the Modern Expert System // #pragma once #include "AddQuestionPage.g.h" #include "MainPageController.h" #include <string> #include <map> #include <utility> #include <vector> namespace modern_expert_system { struct ThreeTextBox { Windows::UI::Xaml::Controls::TextBox^ Content; Windows::UI::Xaml::Controls::TextBox^ BindProperty; Windows::UI::Xaml::Controls::TextBox^ BindValue; }; public ref class AddQuestionPage sealed { public: AddQuestionPage(); protected: void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; void Accept_OnClick(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e); void Cancel_OnClick(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e); void AddPropertyButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void RemoverButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); private: ThreeTextBox AddDynamicField(); private: MainPageController^ FrameController; std::vector<std::pair<Windows::UI::Xaml::Controls::StackPanel^, ThreeTextBox>> pairsOfAnswers; void PriorityTextBox_KeyDown(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e); }; }
/*********************************************************************** created: 15/6/2004 author: Paul D Turner purpose: Implementation of List header segment widget. *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/widgets/ListHeaderSegment.h" #include "CEGUI/GUIContext.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/ImageManager.h" namespace CEGUI { const String ListHeaderSegment::EventNamespace("ListHeaderSegment"); const String ListHeaderSegment::WidgetTypeName("CEGUI/ListHeaderSegment"); /************************************************************************* Constants *************************************************************************/ // Event names const String ListHeaderSegment::EventSegmentClicked( "SegmentClicked" ); const String ListHeaderSegment::EventSplitterDoubleClicked( "SplitterDoubleClicked" ); const String ListHeaderSegment::EventSizingSettingChanged( "SizingSettingChanged" ); const String ListHeaderSegment::EventSortDirectionChanged( "SortDirectionChanged" ); const String ListHeaderSegment::EventMovableSettingChanged( "MovableSettingChanged" ); const String ListHeaderSegment::EventSegmentDragStart( "SegmentDragStart" ); const String ListHeaderSegment::EventSegmentDragStop( "SegmentDragStop" ); const String ListHeaderSegment::EventSegmentDragPositionChanged( "SegmentDragPositionChanged" ); const String ListHeaderSegment::EventSegmentSized( "SegmentSized" ); const String ListHeaderSegment::EventClickableSettingChanged( "ClickableSettingChanged" ); // Defaults const float ListHeaderSegment::DefaultSizingArea = 8.0f; const float ListHeaderSegment::SegmentMoveThreshold = 12.0f; /************************************************************************* Constructor for list header segment base class *************************************************************************/ ListHeaderSegment::ListHeaderSegment(const String& type, const String& name) : Window(type, name), d_sizingCursor(nullptr), d_movingCursor(nullptr), d_splitterSize(DefaultSizingArea), d_splitterHover(false), d_dragSizing(false), d_sortDir(SortDirection::NoSorting), d_segmentHover(false), d_segmentPushed(false), d_sizingEnabled(true), d_movingEnabled(true), d_dragMoving(false), d_allowClicks(true) { addHeaderSegmentProperties(); } /************************************************************************* Destructor for list header segment base class. *************************************************************************/ ListHeaderSegment::~ListHeaderSegment(void) { } /************************************************************************* Set whether this segment can be sized. *************************************************************************/ void ListHeaderSegment::setSizingEnabled(bool setting) { if (d_sizingEnabled != setting) { d_sizingEnabled = setting; // if sizing is now disabled, ensure sizing operation is cancelled if (!d_sizingEnabled && d_dragSizing) releaseInput(); WindowEventArgs args(this); onSizingSettingChanged(args); } } /************************************************************************* Set the current sort direction set for this segment. *************************************************************************/ void ListHeaderSegment::setSortDirection(SortDirection sort_dir) { if (d_sortDir != sort_dir) { d_sortDir = sort_dir; WindowEventArgs args(this); onSortDirectionChanged(args); invalidate(); } } /************************************************************************* Set whether drag moving is allowed for this segment. *************************************************************************/ void ListHeaderSegment::setDragMovingEnabled(bool setting) { if (d_movingEnabled != setting) { d_movingEnabled = setting; WindowEventArgs args(this); onMovableSettingChanged(args); } } /************************************************************************* Set whether the segment is clickable. *************************************************************************/ void ListHeaderSegment::setClickable(bool setting) { if (d_allowClicks != setting) { d_allowClicks = setting; WindowEventArgs args(this); onClickableSettingChanged(args); } } /************************************************************************* Handler called when segment is clicked. *************************************************************************/ void ListHeaderSegment::onSegmentClicked(WindowEventArgs& e) { fireEvent(EventSegmentClicked, e, EventNamespace); } /************************************************************************* Handler called when the sizer/splitter is double-clicked. *************************************************************************/ void ListHeaderSegment::onSplitterDoubleClicked(WindowEventArgs& e) { fireEvent(EventSplitterDoubleClicked, e, EventNamespace); } /************************************************************************* Handler called when sizing setting changes. *************************************************************************/ void ListHeaderSegment::onSizingSettingChanged(WindowEventArgs& e) { fireEvent(EventSizingSettingChanged, e, EventNamespace); } /************************************************************************* Handler called when the sort direction value changes. *************************************************************************/ void ListHeaderSegment::onSortDirectionChanged(WindowEventArgs& e) { invalidate(); fireEvent(EventSortDirectionChanged, e, EventNamespace); } /************************************************************************* Handler called when the drag-movable setting is changed. *************************************************************************/ void ListHeaderSegment::onMovableSettingChanged(WindowEventArgs& e) { fireEvent(EventMovableSettingChanged, e, EventNamespace); } /************************************************************************* Handler called when the user starts dragging the segment. *************************************************************************/ void ListHeaderSegment::onSegmentDragStart(WindowEventArgs& e) { fireEvent(EventSegmentDragStart, e, EventNamespace); } /************************************************************************* Handler called when the user stops dragging the segment (releases pointer) *************************************************************************/ void ListHeaderSegment::onSegmentDragStop(WindowEventArgs& e) { fireEvent(EventSegmentDragStop, e, EventNamespace); } /************************************************************************* Handler called when the drag position changes. *************************************************************************/ void ListHeaderSegment::onSegmentDragPositionChanged(WindowEventArgs& e) { invalidate(); fireEvent(EventSegmentDragPositionChanged, e, EventNamespace); } /************************************************************************* Handler called when the segment is sized. *************************************************************************/ void ListHeaderSegment::onSegmentSized(WindowEventArgs& e) { invalidate(); fireEvent(EventSegmentSized, e, EventNamespace); } /************************************************************************* Handler called when the clickable setting for the segment changes *************************************************************************/ void ListHeaderSegment::onClickableSettingChanged(WindowEventArgs& e) { fireEvent(EventClickableSettingChanged, e, EventNamespace); } /************************************************************************* Initialise and enter the drag moving state. *************************************************************************/ void ListHeaderSegment::initDragMoving(void) { if (d_movingEnabled) { // initialise drag moving state d_dragMoving = true; d_segmentPushed = false; d_segmentHover = false; d_dragPosition = glm::vec2(0, 0); // setup new indicator getGUIContext().setCursorImage(d_movingCursor); // Trigger the event WindowEventArgs args(this); onSegmentDragStart(args); } } /************************************************************************* Initialise the state for hovering over sizing area. *************************************************************************/ void ListHeaderSegment::initSizingHoverState(void) { // only react if settings are changing. if (!d_splitterHover && !d_segmentPushed) { d_splitterHover = true; // change the cursor. getGUIContext().setCursorImage(d_sizingCursor); // trigger redraw so 'sizing' area can be highlighted if needed. invalidate(); } // reset segment hover as needed. if (d_segmentHover) { d_segmentHover = false; invalidate(); } } /************************************************************************* Initialise the state for hovering over main segment area *************************************************************************/ void ListHeaderSegment::initSegmentHoverState(void) { // reset sizing area hover state if needed. if (d_splitterHover) { d_splitterHover = false; getGUIContext().setCursorImage(getEffectiveCursor()); invalidate(); } // set segment hover state if not already set. if ((!d_segmentHover) && isClickable()) { d_segmentHover = true; invalidate(); } } /************************************************************************* Return true if move threshold for initiating drag-moving has been exceeded. *************************************************************************/ bool ListHeaderSegment::isDragMoveThresholdExceeded(const glm::vec2& local_cursor) { // see if cursor has moved far enough to start move operation // calculate movement deltas. const float deltaX = local_cursor.x - d_dragPoint.x; const float deltaY = local_cursor.y - d_dragPoint.y; if ((deltaX > SegmentMoveThreshold) || (deltaX < -SegmentMoveThreshold) || (deltaY > SegmentMoveThreshold) || (deltaY < -SegmentMoveThreshold)) { return true; } else { return false; } } /************************************************************************* Handler for when cursor position changes in widget area (or captured) *************************************************************************/ void ListHeaderSegment::onCursorMove(CursorMoveEventArgs& e) { // base class processing Window::onCursorMove(e); // handle drag sizing if (d_dragSizing) { float delta = e.d_localPos.x - d_dragPoint.x; // store this so we can work out how much size actually changed const float orgWidth = d_pixelSize.d_width; // ensure that we only size to the set constraints. // NB: We are required to do this here due to our virtually unique sizing nature; the // normal system for limiting the window size is unable to supply the information we // require for updating our internal state used to manage the dragging, etc. const float maxWidth(CoordConverter::asAbsolute(d_maxSize.d_width, getRootContainerSize().d_width)); const float minWidth(CoordConverter::asAbsolute(d_minSize.d_width, getRootContainerSize().d_width)); const float newWidth = orgWidth + delta; if (maxWidth != 0.0f && newWidth > maxWidth) delta = maxWidth - orgWidth; else if (newWidth < minWidth) delta = minWidth - orgWidth; // update segment area rect const URect area(d_area.d_min.d_x, d_area.d_min.d_y, d_area.d_max.d_x + UDim(0, delta), d_area.d_max.d_y); setArea(area.d_min, area.getSize(), true); // move the dragging point so cursor remains 'attached' to edge of segment d_dragPoint.x += (d_pixelSize.d_width - orgWidth); WindowEventArgs args(this); onSegmentSized(args); } // handle drag moving else if (d_dragMoving) { const auto delta = e.d_localPos - d_dragPoint; d_dragPosition += delta; d_dragPoint = e.d_localPos; WindowEventArgs args(this); onSegmentDragPositionChanged(args); } // not sizing, is cursor in the widget area? else if (isHit(e.d_surfacePos)) { // cursor in sizing area & sizing is enabled if ((e.d_localPos.x > (d_pixelSize.d_width - d_splitterSize)) && d_sizingEnabled) { initSizingHoverState(); } // cursor not in sizing area and/or sizing not enabled else { initSegmentHoverState(); // if we are pushed but not yet drag moving if (d_segmentPushed && !d_dragMoving && isDragMoveThresholdExceeded(e.d_localPos)) initDragMoving(); } } // cursor is no longer within the widget area... else { // only change settings if change is required if (d_splitterHover) { d_splitterHover = false; getGUIContext().setCursorImage(getEffectiveCursor()); invalidate(); } // reset segment hover state if not already done. if (d_segmentHover) { d_segmentHover = false; invalidate(); } } ++e.handled; } /************************************************************************* Handler for when cursor is pressed *************************************************************************/ void ListHeaderSegment::onMouseButtonDown(MouseButtonEventArgs& e) { // base class processing Window::onMouseButtonDown(e); if (e.d_button == MouseButton::Left) { // ensure all inputs come to us for now if (captureInput()) { // store drag point for possible sizing or moving operation. d_dragPoint = e.d_localPos; // if the cursor is in the sizing area if (d_splitterHover) { if (isSizingEnabled()) { // setup the 'dragging' state variables d_dragSizing = true; } } else { d_segmentPushed = true; } } ++e.handled; } } //----------------------------------------------------------------------------// void ListHeaderSegment::onMouseButtonUp(MouseButtonEventArgs& e) { Window::onMouseButtonUp(e); if (e.d_button == MouseButton::Left) { // if we were pushed and cursor was released (activated) within our segment area if (d_segmentPushed && d_segmentHover) { WindowEventArgs args(this); onSegmentClicked(args); } else if (d_dragMoving) { getGUIContext().setCursorImage(getEffectiveCursor()); WindowEventArgs args(this); onSegmentDragStop(args); } // release our capture on the input data releaseInput(); ++e.handled; } } //----------------------------------------------------------------------------// void ListHeaderSegment::onDoubleClick(MouseButtonEventArgs& e) { if (d_splitterHover && !isDisabled() && e.d_button == MouseButton::Left) { WindowEventArgs args(this); onSplitterDoubleClicked(args); ++e.handled; } Window::onDoubleClick(e); } //----------------------------------------------------------------------------// void ListHeaderSegment::onCursorLeaves(CursorInputEventArgs& e) { // base class processing Window::onCursorLeaves(e); d_splitterHover = false; d_dragSizing = false; d_segmentHover = false; invalidate(); } //----------------------------------------------------------------------------// void ListHeaderSegment::onCaptureLost(WindowEventArgs& e) { // base class processing Window::onCaptureLost(e); // reset segment state d_dragSizing = false; d_segmentPushed = false; d_dragMoving = false; ++e.handled; } //----------------------------------------------------------------------------// void ListHeaderSegment::setSizingCursorImage(const String& name) { d_sizingCursor = &ImageManager::getSingleton().get(name); } //----------------------------------------------------------------------------// void ListHeaderSegment::setMovingCursorImage(const String& name) { d_movingCursor = &ImageManager::getSingleton().get(name); } //----------------------------------------------------------------------------// void ListHeaderSegment::addHeaderSegmentProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(ListHeaderSegment, bool, "Sizable", "Property to get/set the sizable setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setSizingEnabled, &ListHeaderSegment::isSizingEnabled, true /* TODO: Inconsistency */ ); CEGUI_DEFINE_PROPERTY(ListHeaderSegment, bool, "Clickable", "Property to get/set the click-able setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setClickable, &ListHeaderSegment::isClickable, true ); CEGUI_DEFINE_PROPERTY(ListHeaderSegment, bool, "Dragable", "Property to get/set the drag-able setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setDragMovingEnabled, &ListHeaderSegment::isDragMovingEnabled, true /* TODO: Inconsistency */ ); CEGUI_DEFINE_PROPERTY(ListHeaderSegment, ListHeaderSegment::SortDirection, "SortDirection", "Property to get/set the sort direction setting of the header segment. Value is the text of one of the SortDirection enumerated value names.", &ListHeaderSegment::setSortDirection, &ListHeaderSegment::getSortDirection, ListHeaderSegment::SortDirection::NoSorting ); CEGUI_DEFINE_PROPERTY(ListHeaderSegment, Image*, "SizingCursorImage", "Property to get/set the sizing cursor image for the List Header Segment. Value should be \"set:[imageset name] image:[image name]\".", &ListHeaderSegment::setSizingCursorImage, &ListHeaderSegment::getSizingCursorImage, nullptr ); CEGUI_DEFINE_PROPERTY(ListHeaderSegment, Image*, "MovingCursorImage", "Property to get/set the moving cursor image for the List Header Segment. Value should be \"set:[imageset name] image:[image name]\".", &ListHeaderSegment::setMovingCursorImage, &ListHeaderSegment::getMovingCursorImage, nullptr ); } }
// =============================================== // @file update.cpp // @author janeQuinn // @practical defender // @brief Update file for the defender game // =============================================== #include "defender.h" void Ship::update(float dt) { // clamp the x if(position.x < (level->position.x + 2.0/3.0) && position.x > (level->position.x)){ position.x += dt*velocity.x; } else if(position.x > (level->position.x + 2.0/3.0) ){ position.x = (level->position.x + 2.0/3.0); } if(position.x < level->position.x){ position.x = (level->position.x+0.02); } // clamp the y if(position.y < 0.9 && position.y > 0 ){ position.y += dt*velocity.y; } else if(position.y > 0.9){ position.y = 0.9; } if(position.y < 0) { position.y = 0.02; } // game over if(health < 5) gameState = GAME_QUIT; // ground and ceiling collision pointSceneryCollision(Vector2f(position.x, position.y+0.1), false, isAutoPilot); pointSceneryCollision(position, true, isAutoPilot); playerHealthCollision(Vector2f(position.x+0.1, position.y+0.05)); } void Bullet::update(float dt) { if (currentTime-timeToDie>1.5) { state = DEAD; } if(state == AWAKE){ position += dt*velocity; } } void Bomb::update(float dt) { if (position.y < 0.0) { state = DEAD; } if(state == AWAKE){ position += dt*velocity; if(isPointInsideCircle(position, true, 95)) state = DEAD; } } void Enemy::update(float dt) { position += dt*velocity; // limit firing of bullets to 5 a second if (currentTime-previousBulletTime>0.2) { Bullet & bullet = enemyBullets.allocate(); bullet.state = Entity::AWAKE; bullet.position = position - Vector2f(0.03,0.0); bullet.velocity.x = -1; bullet.timeToDie = currentTime; previousBulletTime = currentTime; } switch(type){ case (SIMPLE): if(position.y >= 0.8){ position.y = 0.78; velocity.y = -velocity.y; }else if(position.y <= 0.2){ position.y = 0.22; velocity.y = -velocity.y; } break; case (TRACKING): double angle = atan2(ship.position.y-position.y, ship.position.x-position.x); double speed = 0.3; velocity.x = speed*cos(angle); velocity.y = 2*speed*sin(angle); } } // =============================================== // Main Update // =============================================== void update(){ // Firing Ship Bullets if (fire && currentTime-previousBulletTime>0.2) { // limit firing of bullets to 5 a second Bullet & bullet = shipBullets.allocate(); bullet.state = Entity::AWAKE; bullet.position = ship.position + Vector2f(0.03,0.04); bullet.timeToDie = currentTime; fire = false; previousBulletTime = currentTime; } // Firing Ship Bombs if (fireBomb && currentTime-previousBombTime>0.5) { // limit firing of bombs to 2 a second Bomb & bomb = shipBombs.allocate(); bomb.state = Entity::AWAKE; bomb.position = ship.position + Vector2f(0.03,0.035); fireBomb = false; previousBombTime = currentTime; } // Level, Ship and Enemy updates level->update(dt); // level update ship.update(dt); // ship update for (int k=0; k<level->enemyLength; ++k) { if(fabs(level->enemies[k].position.x - ship.position.x) < 1.5 && level->enemies[k].health > 5){ level->enemies[k].state = Entity::AWAKE; }else level->enemies[k].state = Entity::ASLEEP; if(level->enemies[k].state == Entity::AWAKE){ level->enemies[k].update(dt); // enemy update playerEnemyCollision(level->enemies[k].position); } } // Ship Bombs for (int k=0; k < shipBombs.size();++k) { if(shipBombs[k].state == Entity::DEAD){ shipBombs.free(k); } else shipBombs[k].update(dt); } // Ship Bullets for (int k=0; k < shipBullets.size();++k) { if(shipBullets[k].state == Entity::DEAD){ shipBullets.free(k); } else{ shipBullets[k].update(dt); if(isPointInsideCircle(shipBullets[k].position, true, 20)){ shipBullets[k].state = Entity::DEAD; } } } // Enemy Bullets for (int k=0; k < enemyBullets.size();++k) { if(enemyBullets[k].state == Entity::DEAD){ enemyBullets.free(k); } else{ enemyBullets[k].update(dt); if(isPointInsideCircle(enemyBullets[k].position, false, 20)) { enemyBullets[k].state = Entity::DEAD; } } } } // =============================================== // Methods for Collision Detection // =============================================== bool pointLineCollision(Vector2f p, Vector2f a, Vector2f b, bool isGround, bool isAutoPilot) { Vector2f c = b-a; Vector2f normal = c.normal(); Vector2f other = p-a; // for autoPilot Vector2f otherGround = Vector2f(p.x+0.03,p.y-0.1)-a; // the bottom-right (tip) of the ship Vector2f otherCeiling = Vector2f(p.x,p.y+0.1)-a; // the top-left of the ship if(isAutoPilot){ if (isGround) { if (dot(otherGround,normal)< 0){ // a cheat auto-pilot ship.position.y += 0.1;//a.x*tan(fabs((b.y-a.y)/(b.x-a.x))); // trying to find slope } } else { if (dot(otherCeiling,normal)> 0){ // a cheat auto-pilot ship.position.y -= 0.1;//a.x*tan(fabs((b.y-a.y)/(b.x-a.x))); } } } if (isGround) return (dot(other,normal)< 0); else return (dot(other,normal)> 0); } void pointSceneryCollision(Vector2f p, bool isGround, bool isAutoPilot) { int length = level-> groundLength; Vector2f* points = level->ground; if(!isGround){ length = level->ceilingLength; points = level->ceiling; } int k=0; while(points[k+1].x<p.x) k=k+1; // decrease player health when touching the ground or ceiling if(pointLineCollision(p, points[k], points[k+1], isGround, isAutoPilot)) { ship.health -= 0.1; } } bool isPointInsideRectangle(Vector2f p, Vector2f box, float size) { return (p.x>=box.x-size && p.y>=box.y-size && p.x<=box.x+size && p.y<=box.y+size); } bool isPointInsideCircle(Vector2f p, bool isEnemy, int damage){ if(isEnemy) { for (int k=0; k<level->enemyLength; ++k) { if(level->enemies[k].state == Entity::AWAKE && p.x > level->enemies[k].position.x - 2 && p.x < level->enemies[k].position.x + 2) if (isPointInsideRectangle(p, level->enemies[k].position, 0.05)){ level->enemies[k].health -= damage; return true; } else return false; } } else if (isPointInsideRectangle(p, Vector2f(ship.position.x+0.05, ship.position.y+0.05), 0.05)){ ship.health -= 10; return true; } else false; } void playerEnemyCollision(Vector2f p) { if(isPointInsideRectangle(Vector2f(ship.position.x+0.1, ship.position.y+0.05), p, 0.05)) { ship.health = 2; } } void playerHealthCollision(Vector2f p) { int length = level-> healthLength; Vector2f* healths = level->health; int k=0; while(healths[k].x < p.x) k=k+1; // decrease player health when touching the ground or ceiling if(isPointInsideRectangle(p, healths[k], 0.05) ) { ship.health = 100; } }
//#include <opencv2/opencv.hpp> //using namespace cv; //using namespace std; // //bool check_match(Mat img, Point start, Mat mask, int mode = 0) //{ // for (int u = 0; u < mask.rows; u++) { // for (int v = 0; v < mask.cols; v++) { // Point pt(v, u); // int m = mask.at<uchar>(pt); // 마스크 계수 // int p = img.at<uchar>(start + pt); // 해당 위치 입력화소 // // bool ch = (p == 255); // 일치 여부 비교 // if (m == 1 && ch == mode) return false; // } // } // return true; //} // //void erosion(Mat img, Mat& dst, Mat mask) //{ // dst = Mat(img.size(), CV_8U, Scalar(0)); // if (mask.empty()) mask = Mat(3, 3, CV_8UC1, Scalar(0)); // // Point h_m = mask.size() / 2; // for (int i = h_m.y; i < img.rows - h_m.y; i++) { // for (int j = h_m.x; j < img.cols - h_m.x; j++) // { // Point start = Point(j, i) - h_m; // bool check = check_match(img, start, mask, 0); // dst.at<uchar>(i, j) = (check) ? 255 : 0; // } // } //} // //void dilation(Mat img, Mat& dst, Mat mask) //{ // dst = Mat(img.size(), CV_8U, Scalar(0)); // if (mask.empty()) mask = Mat(3, 3, CV_8UC1, Scalar(0)); // // Point h_m = mask.size() / 2; // for (int i = h_m.y; i < img.rows - h_m.y; i++) { // for (int j = h_m.x; j < img.cols - h_m.x; j++) // { // Point start = Point(j, i) - h_m; // bool check = check_match(img, start, mask, 1); // dst.at<uchar>(i, j) = (check) ? 0 : 255; // } // } //} // //void opening(Mat img, Mat& dst, Mat mask) //{ // Mat tmp; // erosion(img, tmp, mask); // dilation(tmp, dst, mask); //} // //void closing(Mat img, Mat& dst, Mat mask) //{ // Mat tmp; // dilation(img, tmp, mask); // erosion(tmp, dst, mask); //} // //int main() //{ // Mat image = imread("./morph_test1.jpg", 0); // CV_Assert(image.data); // Mat th_img, dst1, dst2, dst3, dst4; // threshold(image, th_img, 128, 255, THRESH_BINARY); // // Matx < uchar, 3, 3> mask; // mask << 0, 1, 0, // 1, 1, 1, // 0, 1, 0; // // opening(th_img, dst1, (Mat)mask); // closing(th_img, dst2, (Mat)mask); // morphologyEx(th_img, dst3, MORPH_OPEN, mask); // morphologyEx(th_img, dst4, MORPH_CLOSE, mask); // // // imshow("Original", image); // imshow("User_opening", dst1), imshow("User_closing", dst2); // imshow("OpenCV_opening", dst3), imshow("OpenCV_closing", dst4); // waitKey(); // return 0; //}
#include "boardbutton.h" #include <QtWidgets> BoardButton::BoardButton(QGraphicsItem *parent, QString text) : BoardPart(parent), m_text(text), click(false) { setCursor(Qt::OpenHandCursor); setAcceptedMouseButtons(Qt::LeftButton); } QRectF BoardButton::boundingRect() const { return QRectF(0, 0, 90, 50); } void BoardButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); painter->drawRoundedRect(0, 0, 90, 50, 25, 25, Qt::RelativeSize); QFont font = painter->font() ; font.setPointSize( 14 ); painter->setFont(font); painter->scale(1, 1.5); painter->drawText(-5, -35, 100, 100, Qt::AlignCenter, QString(m_text)); } bool BoardButton::getClick() { return click; } void BoardButton::setClick(bool booleanValue) { click = booleanValue; } void BoardButton::clickSlot() { click = true; emit clickSignal(); } void BoardButton::mousePressEvent(QGraphicsSceneMouseEvent *) { setCursor(Qt::ClosedHandCursor); } void BoardButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { setCursor(Qt::OpenHandCursor); if(event->button() == Qt::LeftButton) { emit mouseReleased(); click = true; QGraphicsObject::mouseReleaseEvent(event); // call default implementation } else { QGraphicsObject::mouseReleaseEvent(event); // call default implementation } } void BoardButton::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event); }
#include <stdio.h> #include <stdlib.h> #include <ctime> #include "smart_home_sql.h" using namespace std; void mainMenu() { printf("Enter the following:\n"); printf("1. To show users\n"); printf("2. To set active user\n"); printf("3. To add user\n"); printf("4. To control lock\n"); printf("5. To delete user\n"); printf("6. To exit\n"); } void showUsers() { showUsersSQL(); mainMenu(); return; } void setActiveUser(int *hour_start, int *hour_end, int *min_start, int *min_end, int *temperature) { char input[16]; printf("Set Active User by entering their username:\n"); scanf("%s", input); setActiveUserSQL(input, hour_start, hour_end, min_start, min_end, temperature); printf("%s set as active user\n", input); printf("Parameters: Start: %d:%d, Stop: %d:%d, Temperature: %d\n", *hour_start, *min_start, *hour_end, *min_end, *temperature); mainMenu(); return; } void addUser() { char username[16]; char start_time[6]; char end_time[6]; int temperature = 0; printf("Enter Username (15 characters max):\n"); scanf("%s", username); printf("Enter Light Start Time (HH:MM, 24 hour time):\n"); scanf("%s", start_time); printf("Enter Light End Time (HH:MM, 24 hour time):\n"); scanf("%s", end_time); printf("Enter Temperature (0-40):\n"); scanf("%d", &temperature); addUserSQL(username, start_time, end_time, temperature); printf("User Added\n"); mainMenu(); return; } void lockControl() { char input; printf("Enter the following:\n"); printf("1. Lock\n"); printf("2. Unlock\n"); printf("3. Return\n"); while(1) { scanf("%s", &input); if(input == '1') { printf("Lock\n"); } else if(input == '2') { printf("Unlock\n"); } else if(input == '3') { mainMenu(); return; } else { printf("ERROR: Invalid input.\n"); } } } void deleteUser() { char input[16]; printf("Delete user by entering their user name\n"); scanf("%s", input); deleteUserSQL(input); printf("User deleted\n"); mainMenu(); return; } void checkTime(int hour_start, int hour_end, int minute_start, int minute_end) { time_t time_check; struct tm *t; time_check = time(0); t = localtime(&time_check); if((hour_start < t->tm_hour) && (hour_end > t->tm_hour)) { printf("Light is ON\n"); } else if(hour_start == t->tm_hour) { if(minute_start < t->tm_min) { printf("Light is ON\n"); } else { printf("Light is OFF\n"); } } else if(hour_end == t->tm_hour) { if(minute_end > t->tm_min) { printf("Light is ON\n"); } else { printf("Light is OFF\n"); } } else { printf("Light is OFF\n"); } return; } int main() { int start_hour = 0; int end_hour = 0; int start_minute = 0; int end_minute = 0; int temperature = 20; char input; mainMenu(); while(1) { scanf("%s", &input); if(input == '1') { showUsers(); } else if(input == '2') { setActiveUser(&start_hour, &end_hour, &start_minute, &end_minute, &temperature); } else if(input == '3') { addUser(); } else if(input == '4') { lockControl(); } else if(input == '5') { deleteUser(); } else if(input == '6') { return 0; } else { printf("ERROR: Invalid input.\n"); } checkTime(start_hour, end_hour, start_minute, end_minute); } return 0; }
#pragma once #include "DrawingObject.h" #include <SFML/OpenGL.hpp> using namespace std; class DrawingGL : public DrawingObject { public: DrawingGL(std::string ressource); DrawingGL(void); ~DrawingGL(void); void Draw(sf::RenderWindow& renderWindow); bool isGL(); virtual void AI(sf::RenderWindow& renderWindow, std::vector<sf::Event> eventVector); virtual void setPosition( float x, float y ); virtual sf::Vector2f getPosition( ); virtual std::string gettype(); virtual void setColor( sf::Color color ); virtual void setSize( float x,float y ); virtual sf::Vector2f getSize(); private: GLuint texture; // Create a clock for measuring the time sf::Clock clock; };
#include <iostream> using namespace std; #include "add.h" void usage() { cerr << "usage: ./addCmdLine a b" << endl; } int main(int argc, char const *argv[]) { if (argc != 3) { usage(); return 1; } try { int a = stoi(argv[1]); int b = stoi(argv[2]); cout << "sum = " << addEm(a,b) << endl; } catch(invalid_argument e ) { usage(); return 1; } return 0; }