text
stringlengths
8
6.88M
#include <algorithm> #include <iostream> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int n; std::cin >> n; std::vector<int> input; input.reserve(n); for (int i = 0; i < n; ++i) { int a; std::cin >> a; input.emplace_back(a); } std::vector<int> stack; stack.reserve(n + 1); std::vector<char> result; result.reserve(n); auto now = input.begin(); for (int i = 1; i <= n; ++i) { stack.emplace_back(i); result.emplace_back('+'); while (!stack.empty()) { if (*now == stack.back()) { stack.pop_back(); result.emplace_back('-'); ++now; } else { break; } } } if (stack.empty()) { std::for_each(result.begin(), result.end(), [](char c) { std::cout << c << '\n'; }); } else { std::cout << "NO\n"; } return 0; }
#include "msg_0x36_blockaction_stc.h" namespace MC { namespace Protocol { namespace Msg { BlockAction::BlockAction() { _pf_packetId = static_cast<int8_t>(0x36); _pf_initialized = false; } BlockAction::BlockAction(int32_t _x, int16_t _y, int32_t _z, int8_t _byte1, int8_t _byte2, int16_t _blockId) : _pf_x(_x) , _pf_y(_y) , _pf_z(_z) , _pf_byte1(_byte1) , _pf_byte2(_byte2) , _pf_blockId(_blockId) { _pf_packetId = static_cast<int8_t>(0x36); _pf_initialized = true; } size_t BlockAction::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt32(_dst, _offset, _pf_x); _offset = WriteInt16(_dst, _offset, _pf_y); _offset = WriteInt32(_dst, _offset, _pf_z); _offset = WriteInt8(_dst, _offset, _pf_byte1); _offset = WriteInt8(_dst, _offset, _pf_byte2); _offset = WriteInt16(_dst, _offset, _pf_blockId); return _offset; } size_t BlockAction::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); _offset = ReadInt32(_src, _offset, _pf_x); _offset = ReadInt16(_src, _offset, _pf_y); _offset = ReadInt32(_src, _offset, _pf_z); _offset = ReadInt8(_src, _offset, _pf_byte1); _offset = ReadInt8(_src, _offset, _pf_byte2); _offset = ReadInt16(_src, _offset, _pf_blockId); _pf_initialized = true; return _offset; } int32_t BlockAction::getX() const { return _pf_x; } int16_t BlockAction::getY() const { return _pf_y; } int32_t BlockAction::getZ() const { return _pf_z; } int8_t BlockAction::getByte1() const { return _pf_byte1; } int8_t BlockAction::getByte2() const { return _pf_byte2; } int16_t BlockAction::getBlockId() const { return _pf_blockId; } void BlockAction::setX(int32_t _val) { _pf_x = _val; } void BlockAction::setY(int16_t _val) { _pf_y = _val; } void BlockAction::setZ(int32_t _val) { _pf_z = _val; } void BlockAction::setByte1(int8_t _val) { _pf_byte1 = _val; } void BlockAction::setByte2(int8_t _val) { _pf_byte2 = _val; } void BlockAction::setBlockId(int16_t _val) { _pf_blockId = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
/** * @file messagesystem.cpp * * @brief File containing information regaurding the message system implmenentaiton * @version 0.1 * @date 2021-08-02 * * @copyright Copyright (c) 2021 * */ #include "messagesystem.h" #include "messagemanager.h" #include "thread.h" #include "utils.h" #include "messagedecodersystem.h" #include "printer.h" #ifndef MESSAGESYSTEM_CPP #define MESSAGESYSTEM_CPP bool MessageSystem::startMessageSystem(MessageSystem::messageSystemConfig *config) { Thread::thread_config threadconfig{}; threadconfig.task = getTaskEntry(_run); threadconfig.stackDepth = 10000; PRINT("CREATING THREAD\n"); MessageSystem::MessageThreadHandle = Thread::create_thread(&threadconfig); return true; } // FIXME Kill message system causing core dump and program to reset // Below is an copy and paste of the core dump when this function was attempted to be called. /* Guru Meditation Error: Core 0 panic'ed (LoadStoreError). Exception was unhandled. Core 0 register dump: PC : 0x40092b05 PS : 0x00060233 A0 : 0x80091605 A1 : 0x3ffca310 A2 : 0x3ffc445c A3 : 0x3ffba54c A4 : 0x00000001 A5 : 0x00000001 A6 : 0x00060220 A7 : 0x00000000 A8 : 0x3f401480 A9 : 0x3f401480 A10 : 0x00000000 A11 : 0x00000000 A12 : 0x3ffbd80c A13 : 0x00000000 A14 : 0x00000000 A15 : 0x00008000 SAR : 0x00000010 EXCCAUSE: 0x00000003 EXCVADDR: 0x3f401488 LBEG : 0x400014fd LEND : 0x4000150d LCOUNT : 0xfffffff9 ELF file SHA256: 0000000000000000 Backtrace: 0x40092b05:0x3ffca310 0x40091602:0x3ffca330 0x400d3805:0x3ffca350 0x400d2f54:0x3ffca370 0x400d2a12:0x3ffca390 0x400d25a7:0x3ffca3d0 0x400d2f03:0x3ffca450 0x400901d2:0x3ffca480 Rebooting... */ bool MessageSystem::killMessageSystem() { Thread::delete_task(&MessageSystem::MessageThreadHandle); // I think something is wrong with this line return true; } void MessageSystem::_run(task_param_requirements) { MessageManager manager; // The funnel for messages from the different message sources while (true) { Message *msg = manager.getNewMessage(); if (msg == nullptr) { /** * @todo Actually implement a time that we need to wait. * */ delayTask(1000); // <------ FIX THIS !!!!!!!!!!! continue; } else { PRINT("\n\nNEW MESSAGE!!\n\n"); DecoderSystem::decode_execute(msg); } } } Thread::thread_handle MessageSystem::MessageThreadHandle; #endif
/************************************************************************************************** *Program: Delta *Programmer: Toben "Littlefoot" "Narcolapser" Archer *Date: 12 04 14 *Purpose: A class for managing the display of geometry. **********************/ #include "ResourceManager.cpp" #include "Mesh.cpp" #include "GeoObject.h" #include "Program.cpp" #include <stdio.h> #include <iostream> #include <sstream> #ifndef MODEL_H #define MODEL_H class Model: public GeoObject { public: Model(UID _meshID); Model(UID _meshID, float x, float y, float z); Model(xml_node& self, string path); ~Model(); void bindToProgram(Program* prog, GLint _local); void render(); virtual bool onEvent(const Event& event); private: Mesh* mesh; UID meshID; GLint local; }; /*.S.D.G.*/ #endif
#include <iostream> #include <pthread.h> #include <thread> int Global; void *Thread1(void *x) { Global = 42; return x; } int main() { pthread_t t; pthread_create(&t, NULL, Thread1, NULL); Global = 43; pthread_join(t, NULL); return Global; }
#include <bits/stdc++.h> using namespace std; long long int N,M,i; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> M; if(N%2==0) i = N; else i = N+1; for(;i<=M;i+=2){ cout << i << '\n'; } return 0; }
#include<stdio.h> #include<conio.h> #include<stdlib.h> struct nodo { int info; struct nodo *sig; }; struct nodo *raiz=NULL; struct nodo *fondo=NULL; void insertar(int x) { struct nodo *nuevo; nuevo=malloc(sizeof(struct nodo)); nuevo->info=x; nuevo->sig=NULL; if (vacia()) { raiz = nuevo; fondo = nuevo; } else { fondo->sig = nuevo; fondo = nuevo; } } int extraer() { if (!vacia()) { int informacion = raiz->info; struct nodo *bor = raiz; if (raiz == fondo) { raiz = NULL; fondo = NULL; } else { raiz = raiz->sig; } free(bor); return informacion; } else return -1; } void imprimir() { struct nodo *reco = raiz; printf("Listado de todos los elementos de la cola.\n"); while (reco != NULL) { printf("%i - ", reco->info); reco = reco->sig; } printf("\n"); } void liberar() { struct nodo *reco = raiz; struct nodo *bor; while (reco != NULL) { bor = reco; reco = reco->sig; free(bor); } } void main() { insertar(5); insertar(10); insertar(50); imprimir(); printf("Extraemos uno de la cola: %i\n", extraer()); imprimir(); liberar(); getch(); return 0; }
#include "ListOfConstantLengthReads.h" #include "ReadsListTypes.h" namespace PgSAIndex { template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::ListOfConstantLengthReads(uint_read_len readLength, uint_reads_cnt readsCount, uint_pg_len pseudoGenomeLength) : readLength(readLength) { this->readsCount = readsCount; this->pseudoGenomeLength = pseudoGenomeLength; this->pgReadsList = new uchar[(readsCount + 1) * (uint_max) LIST_ELEMENT_SIZE](); this->curRawIdx = 0; this->maxPos = 0; this->isSortRequired = false; this->duplicateFilterK = -1; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::ListOfConstantLengthReads(uint_read_len readLength, std::istream& src) : readLength(readLength) { src >> readsCount; src >> pseudoGenomeLength; int srchelper; src >> srchelper; duplicateFilterK = srchelper; src.get(); //"\n"; this->pgReadsList = (uchar*) PgSAHelpers::readArray(src, sizeof (uchar) * (readsCount + 1) * (uint_max) LIST_ELEMENT_SIZE); this->isSortRequired = false; generateReverseIndex(); this->pgReadsListEnd = this->pgReadsList + (uint_max) readsCount * LIST_ELEMENT_SIZE; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::~ListOfConstantLengthReads() { delete[] (this->pgReadsList); if (this->readsListIdx != 0) delete[] (this->readsListIdx); } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::addImpl(uint_pg_len pos, uint_read_len len, uint_reads_cnt idx) { if (maxPos <= pos) maxPos = pos; else isSortRequired = true; *((uint_pg_len*) (this->pgReadsList + curRawIdx)) = pos; *((uint_reads_cnt*) (this->pgReadsList + curRawIdx + ORIGINAL_INDEX_OFFSET)) = idx; curRawIdx += LIST_ELEMENT_SIZE; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::validateImpl() { if (curRawIdx != readsCount * (uint_max) LIST_ELEMENT_SIZE) cout << "WARNING: Reads list generation failed: " << curRawIdx / LIST_ELEMENT_SIZE << " elements instead of " << readsCount << "\n"; if (isSortRequired) { qsort(this->pgReadsList, readsCount, sizeof (uchar) * LIST_ELEMENT_SIZE, elementsCompare); isSortRequired = false; } // add guard *((uint_pg_len*) (this->pgReadsList + curRawIdx)) = this->pseudoGenomeLength; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::writeImpl(std::ostream& dest) { if (isSortRequired) cout << "WARNING: Reads list invalid!"; dest << readsCount << "\n"; dest << pseudoGenomeLength << "\n"; dest << (int) duplicateFilterK << "\n"; PgSAHelpers::writeArray(dest, this->pgReadsList, sizeof (uchar) * (readsCount + 1) * (uint_max) LIST_ELEMENT_SIZE); } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::generateReverseIndex() { readsListIdx = new uint_reads_cnt[readsCount]; for (uint_reads_cnt i = 0; i < readsCount; i++) readsListIdx[this->getReadOriginalIndexImpl(i)] = i; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::buildLUTImpl() { while (pseudoGenomeLength >> lookupStepShift++ > readsCount); lookup.resize((pseudoGenomeLength >> lookupStepShift) + 2); // cout << ((pseudoGenomeLength >> lookupStepShift) + 2) << " " << lookup.max_size() << "\n"; uint_pg_len j = 0; uint_reads_cnt i = 0; while (i < readsCount) { uint_pg_len nextReadPos = getReadPositionImpl(i + 1); while ((j << lookupStepShift) < nextReadPos) lookup[j++] = i; i++; } lookup[j] = readsCount; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> uint_reads_cnt ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::findFurthestReadContainingImpl(uint_pg_len pos) { uint_reads_cnt lIdx = lookup[pos >> lookupStepShift]; uint_reads_cnt rIdx = lookup[(pos >> lookupStepShift) + 1] + 1; if (rIdx > readsCount) rIdx = readsCount; if ((getReadPositionImpl(lIdx) > pos) || (getReadPositionImpl(rIdx) <= pos)) cout << "whoops\n"; uint_reads_cnt mIdx; long long int cmpRes = 0; while (lIdx < rIdx) { mIdx = (lIdx + rIdx) / 2; cmpRes = (long long int) pos - (long long int) getReadPositionImpl(mIdx); if (cmpRes >= 0) lIdx = mIdx + 1; else if (cmpRes < 0) rIdx = mIdx; } return lIdx - 1; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> inline uint_reads_cnt ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::clearAllOccurFlagsAndCountSingleOccurrencesImpl() { uint_reads_cnt count = 0; for (typename vector<uchar*>::iterator it = occurFlagsReadsList.begin(); it != occurFlagsReadsList.end(); ++it) { if (hasOccurOnceFlagByAddress(*it)) count++; clearOccurFlagsByAddress(*it); } occurFlagsReadsList.clear(); return count; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> inline void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::clearAllOccurFlagsAndPushSingleOccurrencesFlattenImpl(vector<uint_flatten_occurrence_max>& flattenOccurrences) { for (typename vector<pair < uchar*, uint_read_len>>::iterator it = occurFlagsOccurrencesList.begin(); it != occurFlagsOccurrencesList.end(); ++it) { if (this->hasOccurOnceFlagByAddress((*it).first)) flattenOccurrences.push_back(((uint_flatten_occurrence_max) this->getReadOriginalIndexByAddress((*it).first)) * this->getMaxReadLength() + (*it).second); this->clearOccurFlagsByAddress((*it).first); } occurFlagsOccurrencesList.clear(); } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> inline uint_reads_cnt ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::clearAllOccurFlagsImpl() { uint_reads_cnt readsWithOccurFlagCount = occurFlagsReadsList.size(); for (typename vector<uchar*>::iterator it = occurFlagsReadsList.begin(); it != occurFlagsReadsList.end(); ++it) clearOccurFlagsByAddress(*it); occurFlagsReadsList.clear(); return readsWithOccurFlagCount; } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> inline void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::clearOccurFlagsByAddress(uchar* address) { flagsVariableByAddress(address) &= ~(OCCURFLAGS_MASK); } template<typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, uchar FLAGS_OFFSET> inline void ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>::clearOccurFlagsImpl(uint_reads_cnt idx) { clearOccurFlagsByAddress(idx2Address(idx)); } template class ListOfConstantLengthReads<uint_read_len_min, uint_reads_cnt_std, uint_pg_len_std, 9, 4>; template class ListOfConstantLengthReads<uint_read_len_std, uint_reads_cnt_std, uint_pg_len_std, 9, 4>; template class ListOfConstantLengthReads<uint_read_len_min, uint_reads_cnt_std, uint_pg_len_max, 13, 8>; template class ListOfConstantLengthReads<uint_read_len_std, uint_reads_cnt_std, uint_pg_len_max, 13, 8>; }
// // EPITECH PROJECT, 2018 // zappy // File description: // ServPanel.hpp // #include "ServPanel.hpp" ServPanel::ServPanel() { srvClient = std::make_shared<SrvClient>(); } ServPanel::~ServPanel() { } void ServPanel::setVisible(bool visible, int id) { for (std::vector<EditBox>::iterator it = list.begin(); it != list.end(); ++it) { if (id == (*it).getId()) { (*it).setVisible(visible); return; } } std::cout << "ServPanel::setVisible() can't find id " << id << "\n"; } void ServPanel::setString(int id) { for (std::vector<EditBox>::iterator it = list.begin(); it != list.end(); ++it) { if ((*it).getId() == id) { if (id == EditBox::PORT) port = (*it).getText(); else if (id == EditBox::WIDTH) width = (*it).getText(); else if (id == EditBox::HEIGHT) height = (*it).getText(); else if (id == EditBox::CLIENT) client = (*it).getText(); else if (id == EditBox::FREQ) freq = (*it).getText(); else if (id == EditBox::TEAM) team = (*it).getText(); else if (id == EditBox::NAME1 || id == EditBox::NAME2 || id == EditBox::NAME3 || id == EditBox::NAME4) srvClient->addClient((*it).getText()); return; } } std::cout << "ServPanel::setString() can't find id " << id << "\n"; } void ServPanel::addEditBox(EditBox editBox) { list.push_back(editBox); } const wchar_t *ServPanel::getText(int id) { for (std::vector<EditBox>::iterator it = list.begin(); it != list.end(); ++it) { if (id == (*it).getId()) return (*it).getText(); } return (L"ServPanel::getText() can't find id"); }
#pragma once #include "defines.hpp" #include <cmath> #include <vector> #include <iomanip> #include <fstream> #include <memory> #include <map> #include <queue> #include <map> #include <string> #include <array> #include <climits> #include <cstdlib> #include <iterator> #include <algorithm> #include <type_traits> #include <numeric> #include <iostream> #include <exception> #include <opencv2/opencv.hpp> #ifdef _MSC_VER #define PAUSE_EXIT(code) do {system("pause"); std::exit(code);} while(0) #else //ndef(_MSC_VER) #define PAUSE_EXIT(code) do {std::exit(code);} while(0) #endif //ndef(_MSC_VER) using namespace std; namespace tp3 { vector<cv::Mat> lireVideo(const string nomFichier); cv::Mat_<cv::Vec3f> calculerForce(const cv::Mat_<cv::Vec3f>& Gx, const cv::Mat_<cv::Vec3f>& Gy); cv::Mat calcArete(cv::Mat_<cv::Vec3f> force, float seuil); cv::Mat_<cv::Vec3f> calcConvo(const cv::Mat& image, const cv::Mat_<float>& noyau); void appliquerFiltre(const cv::Mat& image, cv::Mat& gradients, const cv::Mat_<float>& kernel, const int ligneDest, const int colonneDest, const int canal); template<typename T, int nChannels=1> inline bool isEqual(const cv::Mat& a, const cv::Mat& b) { if(a.empty() && b.empty()) return true; if(a.dims!=b.dims || a.size!=b.size || a.type()!=b.type()) return false; CV_Assert(a.total()*a.elemSize()==b.total()*b.elemSize() && a.dims==2); for(int i=0; i<a.rows; ++i) for(int j=0; j<a.cols; ++j) for(int c=0; c<nChannels; ++c) if(a.ptr<T>(i,j)[c]!=b.ptr<T>(i,j)[c]) return false; return true; } template<typename T, size_t nChannels=1> inline bool isNearlyEqual(const cv::Mat& a, const cv::Mat& b, double dMaxDiff) { if(a.empty() && b.empty()) return true; if(a.dims!=b.dims || a.size!=b.size || a.type()!=b.type()) return false; CV_Assert(a.total()*a.elemSize()==b.total()*b.elemSize() && a.dims==2); for(int i=0; i<a.rows; ++i) for(int j=0; j<a.cols; ++j) for(int c=0; c<nChannels; ++c) if(std::abs(double(a.ptr<T>(i,j)[c])-double(b.ptr<T>(i,j)[c]))>dMaxDiff) return false; return true; } } // namespace tp3
// // Created by tonell_m on 21/01/17. // #include "../include/Pos.hh" Pos::Pos(const int x, const int y) : x(x), y(y) { } Pos::Pos(Pos const &cpy) : x(cpy.x), y(cpy.y) { } Pos::~Pos() { } Pos& Pos::operator=(Pos const &pos) { if (this != &pos) { this->x = pos.x; this->y = pos.y; } return *this; }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 1111111; bool alive[N]; char w[111]; inline void readq(bool& a, bool& b) { char c= getchar(); while (c != '+' && c != '-') c= getchar(); a = (c == '+'); c = getchar(); b = (c == 'L'); } inline void readi(int& x) { char c = getchar(); while (c < '0' || c > '9') c = getchar(); x = 0; do { x = x * 10 + c - '0'; c = getchar(); } while (c >= '0' && c <= '9'); } int main() { //freopen(".in", "r", stdin); //freopen(".out", "w", stdout); int t; readi(t); deque<pair<int, int> > q; deque<pair<int, int> > d1, d2; for (int iter = 1; iter <= t; ++iter) { pair<int, int> c; bool p, l; readq(p, l); if (p) { int x; readi(x); c = make_pair(x, iter); alive[iter] = true; if (l) { q.push_front(c); } else { q.push_back(c); } } else { if (l) { c = q.front(); q.pop_front(); } else { c = q.back(); q.pop_back(); } alive[c.second] = false; } int ans = -1; while (!qq.empty()) { c = qq.top(); if (!alive[c.second]) qq.pop(); else { ans = -c.first; break; } } printf("%d\n", ans); } return 0; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar void getSumOfMultipes() { int number; int sum = 0; int scan; scan = scanf( "%d", &number ); for( int i = 3; i < number; i++ ) { if( i % 3 == 0 || i % 5 == 0 ) { sum += i; } } printf( "%d\n", sum ); } int main() { int numTestCases; int scan; scan = scanf( "%d", &numTestCases ); while( numTestCases > 0 ) { getSumOfMultipes(); numTestCases--; } return 0; }
#include "gui.h" #include "input.h" rect::rect(float x,float y,float width,float height) { _x = x; _y = y; _width = width; _height = height; } bool rect::point_inside(glm::vec2 p) { return ( p.x>_x && p.x<_x+_width&& p.y>_y && p.y<_y+_height ); } bool rect::point_inside(float px,float py) { return ( px>_x && px<_x+_width&& py>_y && py<_y+_height ); } std::unordered_map<char,character> gui::_freetype_char; std::string gui::_focused_name = ""; std::vector<std::pair<key,std::pair<char,char>>> text_key = { {key::A,{'a','A'}}, {key::B,{'b','B'}}, {key::C,{'c','C'}}, {key::D,{'d','D'}}, {key::E,{'e','E'}}, {key::F,{'f','F'}}, {key::G,{'g','G'}}, {key::H,{'h','H'}}, {key::I,{'i','I'}}, {key::J,{'j','J'}}, {key::K,{'k','K'}}, {key::L,{'l','L'}}, {key::M,{'m','M'}}, {key::N,{'n','N'}}, {key::O,{'o','O'}}, {key::P,{'p','P'}}, {key::Q,{'q','Q'}}, {key::R,{'r','R'}}, {key::S,{'s','S'}}, {key::T,{'t','T'}}, {key::U,{'u','U'}}, {key::V,{'v','V'}}, {key::W,{'w','W'}}, {key::X,{'x','X'}}, {key::Y,{'y','Y'}}, {key::Z,{'z','Z'}}, {key::ONE,{'1','!'}}, {key::TWO,{'2','@'}}, {key::THREE,{'3','#'}}, {key::FOUR,{'4','$'}}, {key::FIVE,{'5','%'}}, {key::SIX,{'6','^'}}, {key::SEVEN,{'7','&'}}, {key::EIGHT,{'8','*'}}, {key::NINE,{'9','('}}, {key::ZERO,{'0',')'}}, {key::LEFTBRACKET,{'[','{'}}, {key::RIGHTBRACKET,{']','}'}}, {key::COMMA,{',','<'}}, {key::SPACE,{' ',' '}}, {key::MINUS,{'-','_'}}, {key::EQUALS,{'=','+'}}, {key::PERIOD,{'.','>'}}, {key::APOSTROPHE,{'\'','\"'}}, {key::SLASH,{'/','?'}}, {key::BACKSLASH,{'\\','|'}}, {key::SEMICOLON,{';',':'}} }; shader* gui::_text_shader = 0; uint gui::_text_pos = 0; void gui::text_area(rect r,std::string name,std::string& text) { int f = has_focus(name); int pi = r.point_inside(input::get_mouse_posf()); float c = 1.0 * f +(0.9*pi+ 0.8*(1-pi))*(1-f); renderer::use_program(0); glColor3f(1,1,1); renderer::simple_quad(r._x,r._y,r._x+r._width,r._y+r._height); glColor3f(c,c,c); renderer::simple_quad(r._x+0.01f,r._y+0.01f,r._x+r._width-0.01f,r._y+r._height-0.01f); std::string display_text; display_text = text.substr(0,_text_pos); if(f)display_text.push_back('|'); display_text += text.substr(_text_pos); #define RTEXT(x) renderer::simple_text(r._x+0.01f,r._y+(r._height *0.8f),r._width,(r._height *1.6f),_text_shader->get_id(),x) RTEXT(display_text); if(!f) { if(input::get_mouse_press(mouse_button::BUTTON_LEFT) && pi) { set_focus(name); _text_pos = text.size(); } } else { #define GETKEY(x) (input::get_key_press(x) && input::get_key_prev_releas(x)) for(int i=0;i<text_key.size();i++) { if(GETKEY(text_key[i].first)) { int m = input::get_key_press(key::LSHIFT); char letter = text_key[i].second.second * m + text_key[i].second.first *(1-m); text.insert(text.begin()+_text_pos,letter); _text_pos++; } } if(GETKEY(key::BACKSPACE)) { if(text.size()>=_text_pos && text.size()>0 && _text_pos>0) { text.erase(text.begin()+(--_text_pos)); } } if(GETKEY(key::DELETE)) { if(text.size()>_text_pos) text.erase(text.begin()+_text_pos); } if(GETKEY(key::LEFT) && _text_pos > 0) { _text_pos--; } if(GETKEY(key::RIGHT) && _text_pos < text.size()) { _text_pos++; } if(GETKEY(key::RETURN)) set_focus(""); #undef GETKEY #undef RTEXT } } bool gui::button(rect r,std::string name) { glColor3f(0,0,0); renderer::simple_quad(r._x+0.01f,r._y+0.01f,r._x+0.01f+r._width,r._y+0.01f+r._height); glColor3f(1,1,1); renderer::simple_quad(r._x,r._y,r._x+r._width,r._y+r._height); return (r.point_inside(input::get_mouse_posf()) && input::get_mouse_press(mouse_button::BUTTON_LEFT)); } void gui::init() { FT_Library freetype; FT_Face face; if(FT_Init_FreeType(&freetype)) std::cout << "freetype failed to initialize" << std::endl; if(FT_New_Face(freetype,"cour.ttf",0,&face)) std::cout << "failed to load freetype face" << std::endl; FT_Set_Pixel_Sizes(face,0,48); renderer::pixel_storei(pname::UNPACK_ALIGNMENT,1); for (uint8 c = 0; c < 128; c++) { if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "failed to load char: " << c << std::endl; continue; } uint texture; renderer::gen_textures(1, &texture); renderer::bind_texture(target::TEXTURE_2D,texture); renderer::teximage2d( target::TEXTURE_2D, 0, internal_format::RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, format::RED, type::UNSIGNED_BYTE, face->glyph->bitmap.buffer ); renderer::texparameteri(target::TEXTURE_2D, pname::TEXTURE_WRAP_S, param::CLAMP_TO_EDGE); renderer::texparameteri(target::TEXTURE_2D, pname::TEXTURE_WRAP_T, param::CLAMP_TO_EDGE); renderer::texparameteri(target::TEXTURE_2D, pname::TEXTURE_MIN_FILTER, param::LINEAR); renderer::texparameteri(target::TEXTURE_2D, pname::TEXTURE_MAG_FILTER, param::LINEAR); uint advance = face->glyph->advance.x; int w = face->glyph->bitmap.width; int h = face->glyph->bitmap.rows; int bearingx = face->glyph->bitmap_left; int bearingy = face->glyph->bitmap_top; character character(texture, advance, glm::ivec2(w,h),glm::ivec2(bearingx,bearingy)); _freetype_char[c] = character; } renderer::pixel_storei(pname::PACK_ALIGNMENT,1); FT_Done_Face(face); FT_Done_FreeType(freetype); _text_shader = new shader("text_shader.glsl"); }
#pragma once #include "Task.h" #include "R2D2.h" #include "Robot.h" #include "Xwing.h" #include "SoundTestTask.h" #include "Billboard.h" namespace T3D { class AnimationTest : public Task { public: float variance = 0.2f; float elapsedTime = 0; R2D2 * r2d2; Robot * robot; Xwing * xwing; Music * music; GameObject * credits; SoundTestTask * sounds; GameObject * camera; GameObject * cameraTargetObject = NULL; AnimationTest(T3DApplication * app); ~AnimationTest(); void update(float dt); void moveAndRotate(GameObject * object, float time, Vector3 position, Quaternion rotation); bool time(float target); Quaternion getLookAt(Vector3 target, GameObject* object); void AnimationTest::move(GameObject * object, float time, Vector3 position); void rotate(GameObject * object, float time, Quaternion rotation); }; }
/**************************************** Zerus97 *****************************************/ #include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define getl(s) getline(cin,s); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define vi vector<int> #define vll vector<ll> #define mii map<int,int> #define mlli map<ll,int> #define mib map<int,bool> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define D(v,status) cout<<status<<" "<<v<<endl; #define INF 1000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) #define CONTEST 1 using namespace std; int main() { string ss; cin>>ss; int len = ss.length(); if(len==1) { if((ss[0]-'0')%8==0) { cout<<"YES"<<endl; cout<<ss<<endl; return 0; } } else if(len==2) { int pos1 = (ss[0]-'0')*10 + (ss[1]-'0'); if(pos1%8==0) { cout<<"YES"<<endl; cout<<pos1<<endl; return 0; } int pos2 = (ss[0]-'0'); if(pos2%8==0) { cout<<"YES"<<endl; cout<<pos2<<endl; return 0; } int pos3 = (ss[1]-'0'); if(pos3%8==0) { cout<<"YES"<<endl; cout<<pos3<<endl; return 0; } } else if(len>=3) { loop(lv1,0,len-1) { loop(lv2,lv1+1,len-1) { loop(lv3,lv2+1,len-1) { int pos1 = (ss[lv1]-'0')*100 + (ss[lv2]-'0')*10 + (ss[lv3]-'0'); if(pos1%8==0) { cout<<"YES"<<endl; cout<<pos1<<endl; return 0; } int pos2 = (ss[lv1]-'0')*10 + (ss[lv2]-'0'); if(pos2%8==0) { cout<<"YES"<<endl; cout<<pos2<<endl; return 0; } int pos3 = (ss[lv2]-'0')*10 + (ss[lv3]-'0'); if(pos3%8==0) { cout<<"YES"<<endl; cout<<pos3<<endl; return 0; } int pos4 = (ss[lv1]-'0')*10 + (ss[lv3]-'0'); if(pos4%8==0) { cout<<"YES"<<endl; cout<<pos4<<endl; return 0; } int pos5 = (ss[lv1]-'0'); if(pos5%8==0) { cout<<"YES"<<endl; cout<<pos5<<endl; return 0; } int pos6 = (ss[lv2]-'0'); if(pos6%8==0) { cout<<"YES"<<endl; cout<<pos6<<endl; return 0; } int pos7 = (ss[lv3]-'0'); if(pos7%8==0) { cout<<"YES"<<endl; cout<<pos7<<endl; return 0; } } } } } cout<<"NO"<<endl; return 0; }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "acceleration_module.hpp" #include "join_interface.hpp" #include "memory_manager_interface.hpp" namespace orkhestrafs::dbmstodspi { /** * @brief Class to write in the join operation acceleration module settings. */ class Join : public AccelerationModule, public JoinInterface { private: public: ~Join() override = default; /** * @brief Constructor to set the memory manager instance to access memory * mapped registers. * @param memory_manager Memory manager instance to access memory mapping. * @param module_position Position of the module in the bitstream. */ explicit Join(MemoryManagerInterface* memory_manager, int module_position) : AccelerationModule(memory_manager, module_position){}; /** * @brief Set stream parameters. * @param output_stream_chunk_count How many chunks of data are used for the * output data. * @param first_input_stream_id Input stream A. * @param second_input_stream_id Input stream B. * @param output_stream_id Output stream ID. */ void DefineOutputStream(int output_stream_chunk_count, int first_input_stream_id, int second_input_stream_id, int output_stream_id) override; /** * @brief Set first input stream chunk count. * @param chunk_count How many chunks are used for each record. */ void SetFirstInputStreamChunkCount(int chunk_count) override; /** * @brief Set first input stream chunk count. * @param chunk_count How many chunks are used for each record. */ void SetSecondInputStreamChunkCount(int chunk_count) override; /** * @brief Configure the element selection after join. * @param output_chunk_id Which output chunk should the element be put to. * @param input_chunk_id Which input chunk should the element be taken from. * @param data_position Which position should be the element be taken from and * put to. * @param is_element_from_second_stream Is the next element going to be from * first or second stream. */ void SelectOutputDataElement(int output_chunk_id, int input_chunk_id, int data_position, bool is_element_from_second_stream) override; /** * @brief Write into the module configuration to start prefetching data. */ void StartPrefetchingData() override; /** * @brief Write into the reset register to reset the module. */ void Reset() override; }; } // namespace orkhestrafs::dbmstodspi
// // Created by jwscoggins on 12/12/20. // #ifndef SIM960_GENERICNUMBER_H #define SIM960_GENERICNUMBER_H #include <type_traits> template<typename T, std::size_t width> class GenericNumber { public: GenericNumber(T val = static_cast<T>(0)) : _val(val) { } [[nodiscard]] [[maybe_unused]] constexpr auto get() const noexcept { return _val; } [[maybe_unused]] void set(T value) noexcept { _val = value; } private: T _val : width; }; template<typename T, std::size_t width> bool operator==(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return a.get() == b.get(); } template<typename T, std::size_t width> bool operator!=(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return a.get() != b.get(); } template<typename T, std::size_t width> GenericNumber<T, width> operator+(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return GenericNumber<T, width>(a.get() + b.get()); } template<typename T, std::size_t width> GenericNumber<T, width> operator-(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return GenericNumber<T, width>(a.get() - b.get()); } template<typename T, std::size_t width> GenericNumber<T, width> operator*(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return GenericNumber<T, width>(a.get() * b.get()); } template<typename T, std::size_t width> GenericNumber<T, width> operator/(const GenericNumber<T, width>& a, const GenericNumber<T, width>& b) noexcept { return GenericNumber<T, width>(a.get() / b.get()); } #endif //SIM960_GENERICNUMBER_H
char val; int leftorright; int downorup,baseycorrection; int cworccw,basethetacorrection; int hitcommand,encoderangle,prevangleconstant; int senseValue, pwmvalue; int angleconstant; void setup() { Serial.begin(9600); Serial3.begin(9600); } void loop() { Serial3.write('z'); delay(1); Serial.println("REQUEST SENT____________________"); if (Serial3.available() > 15 ) { Serial.println("________________RESPONSE RECEIVED"); val = Serial3.read(); if (val == 'a') { leftorright = Serial3.parseInt(); downorup = Serial3.parseInt(); baseycorrection=Serial3.parseInt(); cworccw=Serial3.parseInt(); basethetacorrection=Serial3.parseInt(); hitcommand=Serial3.parseInt(); encoderangle=Serial3.parseInt(); } Serial.println(leftorright); Serial.println(downorup); Serial.println(baseycorrection); Serial.println(cworccw); Serial.println(basethetacorrection); Serial.println(hitcommand); Serial.println(encoderangle); } }
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * 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. * * ***** END GPL LICENSE BLOCK ***** */ #include "KhaWrapper.h" #include "Kore/Sources/Kore/pch.h" #include "Kore/Sources/Kore/Application.h" #include "Kore/Sources/Kore/IO/FileReader.h" #include "Kore/Sources/Kore/Graphics/Graphics.h" #include "Kore/Sources/Kore/Graphics/Shader.h" #include "Kore/Backends/OpenGL2/Sources/Kore/ogl.h" #include <stdio.h> using namespace Kore; void khaStart() { //printf("OpenGL version supported by this platform (%s): \n", glGetString(GL_VERSION)); Application* app = new Application(0, nullptr, 1024, 768, 0, false, "BlenderKore"); //app->setCallback(update); //app->start(); } void khaUpdate() { Graphics::begin(); kha_run_callback(); Graphics::end(); //Graphics::swapBuffers(); }
#include "Game.h" // public Game::Game() { mWireFrame = false; mRained = false; mRenderManager = NULL; mCamera = NULL; mFrustum = NULL; mLight = NULL; mMaterial0 = NULL; mMaterial1 = NULL; mCube = NULL; mSphere = NULL; mSkySphere = NULL; mSkyPlane = NULL; } Game::~Game() { SafeDeletePtr(mSkyPlane); SafeDeletePtr(mSkySphere); SafeDeletePtr(mSphere); SafeDeletePtr(mCube); SafeDeletePtr(mMaterial1); SafeDeletePtr(mMaterial0); SafeDeletePtr(mLight); SafeDeletePtr(mFrustum); SafeDeletePtr(mCamera); SafeDeletePtr(mRenderManager); } void Game::Initialize() { InitializeRenderResource(); InitializeGameObject(); } void Game::Update(FLOAT delta) { UpdateRenderResource(delta); UpdateGameObject(delta); if (Input.KeyUp(DIK_1)) mWireFrame = !mWireFrame; if (Input.KeyUp(DIK_2)) mRained = !mRained; if (Input.KeyUp(DIK_ESCAPE)) PostQuitMessage(0); } void Game::PreRender() { } void Game::Render() { D3DXVECTOR3 camPos = mCamera->GetPosition(); // SkySphere { mRenderManager->SetRasterizerState(RS_CullNone); mRenderManager->SetDepthStencilState(DS_DepthDisable); mRenderManager->SetShader(L"SkySphere"); mSkySphere->SetPosition(camPos.x, camPos.y, camPos.z); mSkySphere->SetBuffer(); mRenderManager->SetIAParameterAndDraw(mSkySphere); } // SkyPlane { mRenderManager->SetRasterizerState(RS_CullBack); mRenderManager->SetBlendState(BS_SkyPlane); mRenderManager->SetShader(L"SkyPlane"); mRenderManager->SetTexture(L"Cloud", 0); mRenderManager->SetTexture(L"Noise", 1); mSkyPlane->SetPosition(camPos.x, camPos.y, camPos.z); mSkyPlane->SetBuffer(); mRenderManager->SetIAParameterAndDraw(mSkyPlane); } mRenderManager->SetBlendState(BS_Default); mRenderManager->SetDepthStencilState(DS_Default); // Terrain { mRenderManager->SetRasterizerState(mWireFrame ? RS_WireFrame_CullBack : RS_CullBack); mRenderManager->SetShader(L"Terrain"); mRenderManager->SetTexture(mTerrain->GetHeightmap(), 0); mRenderManager->SetTexture(L"Blendmap", 1); mRenderManager->SetTextureArray(L"LayermapArray", 2); mTerrain->SetBuffer(); mRenderManager->SetIAParameterAndDraw(mTerrain); } //mRenderManager->SetRasterizerState(RS_Default); // TODO:: Normal값 적용할 것 // Tree { // Trunk vector<wstring> imgTrunk; vector<wstring> imgLeaf; imgTrunk.push_back(L"Trunk1"); imgTrunk.push_back(L"Trunk2"); imgTrunk.push_back(L"Trunk3"); imgLeaf.push_back(L"Leaf1"); imgLeaf.push_back(L"Leaf2"); imgLeaf.push_back(L"Leaf3"); for (int i = 0; i < gCFTree.Sort; i++) { mRenderManager->SetShader(L"Trunk"); mRenderManager->SetTexture(imgTrunk[i].c_str(), 0); mTrunk[i].SetBuffer(); mRenderManager->SetIAParameterAndDraw(&mTrunk[i]); } // Leaf mRenderManager->SetBlendState(BS_Alpha); for (int i = 0; i < gCFTree.Sort; i++) { mRenderManager->SetShader(L"Leaf"); mRenderManager->SetTexture(imgLeaf[i].c_str(), 0); mLeaf[i].SetBuffer(); mRenderManager->SetIAParameterAndDraw(&mLeaf[i]); } } mRenderManager->SetBlendState(BS_Default); // Rain if (mRained) { mRenderManager->SetShader(L"Rain"); mRain->SetBuffer(); mRenderManager->SetIAParameterAndDraw(mRain); } // Cube (Material0) { mRenderManager->SetShader(L"Cube"); mCube->SetBuffer(); mRenderManager->SetTexture(L"Trapezoid", 0); mRenderManager->SetIAParameterAndDraw(mCube); } // Sphere (Material1) { mRenderManager->SetShader(L"Sphere"); mSphere->SetPosition(5.0F, 0.0F, 0.0F); mSphere->SetBuffer(); mRenderManager->SetTexture(L"Earth", 0); mRenderManager->SetIAParameterAndDraw(mSphere); } } // private void Game::InitializeRenderResource() { // Camera, Frustum mCamera = new Camera; mCamera->Initialize(); mCamera->SetPosition(0.0F, 0.0F, -10.0F); mFrustum = new Frustum; // Light, Material mLight = new Light; mLight->Initialize(); D3DXVECTOR4 ambient; D3DXVECTOR4 diffuse; D3DXVECTOR4 specular; FLOAT specularPower; // Specular x ambient = D3DXVECTOR4(0.15F, 0.15F, 0.15F, 1.0F); diffuse = D3DXVECTOR4(1.0F, 1.0F, 1.0F, 1.0F); specular = D3DXVECTOR4(0.0F, 0.0F, 0.0F, 1.0F); specularPower = 0.0F; mMaterial0 = new Material; mMaterial0->Initialize(); mMaterial0->SetMaterial(ambient, diffuse, specular, specularPower); // Specular o ambient = D3DXVECTOR4(0.15F, 0.15F, 0.15F, 1.0F); diffuse = D3DXVECTOR4(1.0F, 1.0F, 1.0F, 1.0F); specular = D3DXVECTOR4(1.0F, 1.0F, 1.0F, 1.0F); specularPower = 32.0F; mMaterial1 = new Material; mMaterial1->Initialize(); mMaterial1->SetMaterial(ambient, diffuse, specular, specularPower); // Shader, Texture mRenderManager = new RenderManager; mRenderManager->Initialize(); mRenderManager->AddShader(L"Cube", IL_PosTexNor::sElementDesc, IL_PosTexNor::sElementCount, false); // Material 0 mRenderManager->AddShader(L"Sphere", IL_PosTexNor::sElementDesc, IL_PosTexNor::sElementCount, false); // Material 1 mRenderManager->AddShader(L"SkySphere", IL_Pos::sElementDesc, IL_Pos::sElementCount, false); mRenderManager->AddShader(L"SkyPlane", IL_PosTex::sElementDesc, IL_PosTex::sElementCount, false); mRenderManager->AddShader(L"Terrain", IL_PosTex::sElementDesc, IL_PosTex::sElementCount, true); mRenderManager->AddShader(L"Rain", IL_PosInst::sElementDesc, IL_PosInst::sElementCount, false); mRenderManager->AddShader(L"Trunk", IL_PosTexInst::sElementDesc, IL_PosTexInst::sElementCount, false); mRenderManager->AddShader(L"Leaf", IL_PosTexInst::sElementDesc, IL_PosTexInst::sElementCount, false); mRenderManager->AddTexture(L"Test", TE_GIF); mRenderManager->AddTexture(L"Trapezoid", TE_JPG); mRenderManager->AddTexture(L"Earth", TE_PNG); mRenderManager->AddTexture(L"Cloud", TE_DDS); mRenderManager->AddTexture(L"Noise", TE_DDS); mRenderManager->AddTexture(L"Blendmap", TE_DDS); vector<wstring> layermap; wstring path = L"Data\\Texture\\"; layermap.push_back(path + gCFTerrain.Layermap0); layermap.push_back(path + gCFTerrain.Layermap1); layermap.push_back(path + gCFTerrain.Layermap2); layermap.push_back(path + gCFTerrain.Layermap3); mRenderManager->AddTextureArray(L"LayermapArray", layermap, TE_DDS); mRenderManager->AddTexture(L"Trunk1", TE_DDS); mRenderManager->AddTexture(L"Trunk2", TE_DDS); mRenderManager->AddTexture(L"Trunk3", TE_DDS); mRenderManager->AddTexture(L"Leaf1", TE_DDS); mRenderManager->AddTexture(L"Leaf2", TE_DDS); mRenderManager->AddTexture(L"Leaf3", TE_DDS); } void Game::InitializeGameObject() { mCube = new Cube; mCube->Initialize(); mSphere = new Sphere; mSphere->Initialize(); mSkySphere = new SkySphere; mSkySphere->Initialize(); mSkyPlane = new SkyPlane; mSkyPlane->Initialize(); mTerrain = new Terrain; mTerrain->Initialize(); mRain = new Rain; mRain->Initialize(); mTrunk = new Trunk[gCFTree.Sort]; mLeaf = new Leaf[gCFTree.Sort]; FLOAT scale = 0.2F; for (int i = 0; i < gCFTree.Sort; i++) { mTrunk[i].Initialize(mTerrain, scale); mLeaf[i].Initialize(&mTrunk[i], scale); scale += 0.1F; } } void Game::UpdateRenderResource(FLOAT delta) { // Camera, Frustum mCamera->Update(delta); mCamera->UpdateReflection(0.0F); mCamera->SetBuffer(); // TODO:: Frustum이 이상합니다.. 내가 이상한 것 같지만 일단 이상합니다 D3DXMATRIX view = mCamera->GetView(); D3DXMATRIX proj = mCamera->GetProjection(); D3DXMATRIX viewProj; D3DXMatrixMultiply(&viewProj, &view, &proj); mFrustum->SetFrustum(viewProj); // Light, Material mLight->Update(delta); mLight->SetBuffer(); mMaterial0->SetBuffer(RB_Material0); mMaterial1->SetBuffer(RB_Material1); } void Game::UpdateGameObject(FLOAT delta) { mSkyPlane->Update(delta); if (mRained) mRain->Update(delta, mCamera, mFrustum); for (int i = 0; i < gCFTree.Sort; i++) { mTrunk[i].Update(mFrustum); mLeaf[i].Update(mFrustum); } }
#ifndef QT_MAIN_CONTENT_H #define QT_MAIN_CONTENT_H #include <memory> #include <QWidget> class QtMainContent : public QWidget { Q_OBJECT public: QtMainContent(); private: void populate(QWidget* parent); }; #endif // QT_MAIN_CONTENT_H
//args.cpp //Aaron Nicanor //anicanor #include <iostream> using namespace std; int main(int argc, char *argv[]){ for(int i = 1; i < argc; i++){ cout<<argv[i]<<endl; } return 0; }
#pragma once #include "plbase/PluginBase.h" #include "CTaskSimple.h" #include "RenderWareTypes.h" #include "CVector.h" #pragma pack(push, 1) class PLUGIN_API CTaskSimpleJetpack : public CTaskSimple { public: __int8 byte8; __int8 byte9; __int8 byteA; __int8 byteB; __int8 byteC; __int8 byteD; __int8 byteE; __int8 fF[1]; __int32 dword10; __int32 dword14; float dword18; __int32 dword1C; __int32 dword20; __int32 dword24; __int32 dword28; __int32 dword2C; __int32 dword30; __int32 dword34; __int32 dword38; float dword3C; RpClump *m_pJetpackObject; __int32 dword44; CVector dword48; __int32 dword54; __int32 dword58; __int32 dword5C; class CObject *pcobject60; void *m_apPparticles[2]; // CParticle * float m_fParticleIntensity; }; #pragma pack(pop) //VALIDATE_SIZE(CTaskSimpleJetpack, 0x70);
/* ID: dhyanes1 LANG: C++ PROG: hotel */ #include <cstdio> #include <algorithm> #include <map> #include <set> #include <queue> using namespace std; int main(void) { FILE *fin,*fout; fin=fopen("hotel.in","r"); fout = fopen("hotel.out","w"); map<int,set<int> > free; int n,m; fscanf(fin, "%d %d", &n ,&m); for (int i = 0; i < m; ++i) { int type; fscanf(fin, "%d", &type); int no, st; if (type == 1) { fscanf(fin, "%d", &no); st = 1; } else { fscanf(fin, "%d %d", &st, &no); } } fclose(fout); fclose(fin); return 0; }
#include <bits/stdc++.h> long long t,n,x,a[1000001],sum,half,first; using namespace std; // 1 2 3 4 5 6 7 int main() { cin>>t; for(int i = 0; i < t; i++){ cin>>x>>n; a[x] = 2; sum = n*(n+1)/2 - x; if(sum % 2 == 1 || n == 2) cout<<"impossible"<<endl; else{ first = 0; half = sum / 2; for(int i = n; i >= 1; i--){ if(half - first <= n && a[half-first] != 1 && half-first != x){ a[half-first] = 1; first = half; break; } if(first+i > half || i == x || ((half-first-i) == x)) continue; else{ a[i] = 1; first += i; } if(first == half ) break; } if(first == half) for(int i = 1; i <= n; i++) cout<<a[i]; else cout<<"impossible"; cout<<endl; } for(int i = 1;i <= n; i++) a[i] = 0; } }
#include <unordered_map> #include <iostream> struct T : public std::string { T(const char * s) : std::string(s) { std::cerr << "construct" << std::endl; } ~T(){ std::cerr << "destruct" << std::endl; } }; namespace std { template<> struct hash<T> { size_t operator()(const T& s) const { std::cerr << "hash" << std::endl; return 0; } }; } int main() { std::unordered_map<T, int> h; std::cerr << h.count("qwe") << std::endl; return 0; }
/// \file NiCfEventAction.cc /// \brief Implementation of the NiCfEventAction class; adapted from /// Geant4 example B5 B5EventAction.cc #include "NiCfEventAction.hh" #include "NiCfTrajectory.hh" #include "NiCfTrackingAction.hh" #include "NiCfConstants.hh" #include "NiCfAnalysis.hh" #include "G4Event.hh" #include "G4RunManager.hh" #include "G4EventManager.hh" #include "G4HCofThisEvent.hh" #include "G4VHitsCollection.hh" #include "G4SDManager.hh" #include "G4SystemOfUnits.hh" #include "G4VTrajectory.hh" #include "G4TrajectoryContainer.hh" #include "G4ios.hh" //#include "g4analysis.hh" using std::array; using std::vector; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... NiCfEventAction::NiCfEventAction() : G4UserEventAction() // std::array<T, N> is an aggregate that contains a C array. // To initialize it, we need outer braces for the class itself // and inner braces for the C array { // set printing per each event G4RunManager::GetRunManager()->SetPrintProgress(1); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... NiCfEventAction::~NiCfEventAction() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void NiCfEventAction::BeginOfEventAction(const G4Event*) { // Find hit collections and histogram Ids by names (just once) // and save them in the data members of this class } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void NiCfEventAction::EndOfEventAction(const G4Event* event) { // // Fill histograms & ntuple // // Get analysis manager auto analysisManager = G4AnalysisManager::Instance(); G4cout << "END OF EVENT" << G4endl; // Loop through all trajectories. G4TrajectoryContainer * tc = event->GetTrajectoryContainer(); if(tc) { for(unsigned int i = 0; i < tc->size(); i++) { NiCfTrajectory * tr = dynamic_cast<NiCfTrajectory*>((*tc)[i]); G4ThreeVector posInit = tr->GetInitialPosition(); G4ThreeVector posFinal = tr->GetFinalPosition(); G4ThreeVector momentumInit = tr->GetInitialMomentum(); G4ThreeVector momentumFinal = tr->GetFinalMomentum(); // Fill all columns in the NTuple. analysisManager->FillNtupleIColumn(0,event->GetEventID()); analysisManager->FillNtupleSColumn(1,tr->GetParticleName()); analysisManager->FillNtupleIColumn(2,tr->GetTrackID()); analysisManager->FillNtupleIColumn(3,tr->GetParentID()); analysisManager->FillNtupleDColumn(4,tr->GetMass()); analysisManager->FillNtupleDColumn(5,posInit[0]); analysisManager->FillNtupleDColumn(6,posInit[1]); analysisManager->FillNtupleDColumn(7,posInit[2]); analysisManager->FillNtupleDColumn(8,tr->GetInitialTime()); analysisManager->FillNtupleDColumn(9,posFinal[0]); analysisManager->FillNtupleDColumn(10,posFinal[1]); analysisManager->FillNtupleDColumn(11,posFinal[2]); analysisManager->FillNtupleDColumn(12,tr->GetFinalTime()); analysisManager->FillNtupleDColumn(13,momentumInit[0]); analysisManager->FillNtupleDColumn(14,momentumInit[1]); analysisManager->FillNtupleDColumn(15,momentumInit[2]); analysisManager->FillNtupleDColumn(16,momentumFinal[0]); analysisManager->FillNtupleDColumn(17,momentumFinal[1]); analysisManager->FillNtupleDColumn(18,momentumFinal[2]); analysisManager->FillNtupleSColumn(19,tr->GetInitialVolume()); analysisManager->FillNtupleSColumn(20,tr->GetFinalVolume()); // Add an NTuple row. analysisManager->AddNtupleRow(); } } // Clear the trajectory map. NiCfTrackingAction::ClearTrajectoryMap(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
/* * @lc app=leetcode.cn id=38 lang=cpp * * [38] 外观数列 */ // @lc code=start #include<iostream> #include<string> #include<sstream> using namespace std; class Solution { public: string countAndSay(int n) { string s="1"; for(int i=0;i<n-1;i++) { string last=s.substr(0,1); int cnt=1; string tmp; stringstream ss(tmp); for(int j=1;j<s.size();j++){ if(s.substr(j,1)==last){ cnt++; }else{ ss<<cnt<<last; last=s[j]; cnt=1; } } if(tmp.empty()){ //cout<<cnt<<last<<endl; ss<<cnt<<last; } tmp = ss.str(); s = tmp; } return s; } }; // @lc code=end
#include "SinhVien.h" void SinhVien::Nhap() { /*fflush(stdin); cout << "\nNhap vao ma so: "; getline(cin, MaSo);*/ fflush(stdin); cout << "\nNhap vao ho ten: "; getline(cin, HoTen); int luachon; do{ cout << "\n------------- Menu -------------\n"; cout << "\n1. Nhap thong tin mon hoc"; cout << "\n2. Thoat"; cout << "\n--------------------------------\n"; do{ cout << "\nNhap vao lua chon: "; cin >> luachon; if(luachon != 1 && luachon != 2) { cout << "\nLua chon khong hop le. Xin kiem tra lai !"; } }while(luachon != 1 && luachon != 2); if(luachon == 1) { MonHoc mh; mh.Nhap(); ListMonHoc.push_back(mh); } }while(luachon != 2); } void SinhVien::Xuat() { cout << "\nMa so: " << MaSo; cout << "\nHo ten: " << HoTen; int size = ListMonHoc.size(); for(int i = 0; i < size; i++) { cout << "\nMon hoc thu " << i + 1 << "\n"; ListMonHoc[i].Xuat(); } cout << "\nDiem trung binh = " << TinhDiemTrungBinh(); } istream& operator >>(istream &is, SinhVien &x) { /*fflush(stdin); cout << "\nNhap vao ma so: "; getline(is, x.MaSo);*/ fflush(stdin); cout << "\nNhap vao ho ten: "; getline(is, x.HoTen); int luachon; do{ cout << "\n------------- Menu -------------\n"; cout << "\n1. Nhap thong tin mon hoc"; cout << "\n2. Thoat"; cout << "\n--------------------------------\n"; do{ cout << "\nNhap vao lua chon: "; is >> luachon; if(luachon != 1 && luachon != 2) { cout << "\nLua chon khong hop le. Xin kiem tra lai !"; } }while(luachon != 1 && luachon != 2); if(luachon == 1) { MonHoc mh; mh.Nhap(); x.ListMonHoc.push_back(mh); } }while(luachon != 2); return is; } ostream& operator <<(ostream &os, SinhVien x) { os << "\nMa so: " << x.MaSo; os << "\nHo ten: " << x.HoTen; int size = x.ListMonHoc.size(); for(int i = 0; i < size; i++) { os << "\nMon hoc thu " << i + 1 << "\n"; x.ListMonHoc[i].Xuat(); } return os; } SinhVien::SinhVien(void) { MaSo = "69"; HoTen = "Son dep chai"; } SinhVien::SinhVien(string hoten, string maso, vector<MonHoc> list) { HoTen = hoten; MaSo = maso; int size = list.size(); for(int i = 0; i < size; i++) { ListMonHoc.push_back(list[i]); } } SinhVien::SinhVien(const SinhVien &x) { MaSo = x.MaSo; HoTen = x.HoTen; int size = x.ListMonHoc.size(); // Cách 1: ListMonHoc.resize(size); for(int i = 0; i < size; i++) { ListMonHoc.push_back(x.ListMonHoc[i]); // Cách 1: ListMonHoc[i] = x.ListMonHoc[i]; } } SinhVien::~SinhVien(void) { } float SinhVien::TinhDiemTrungBinh() { int tongsochi = 0; float tongdiem = 0; int size = ListMonHoc.size(); for(int i = 0; i < size; i++) { tongsochi += ListMonHoc[i].Getter_SoChi(); tongdiem += ListMonHoc[i].Getter_Diem() * ListMonHoc[i].Getter_SoChi(); } return tongdiem / tongsochi; } string SinhVien::XepLoai() { float Dtb = TinhDiemTrungBinh(); // Cách nhập môn làm /*if(Dtb >= 9 && Dtb <= 10) { return "Xuat Sac"; } else if(Dtb >= 8 && Dtb < 9) { return "Gioi"; } else if(Dtb >= 7 && Dtb < 8) { return "Kha"; }*/ // Cách hay hơn chút xíu if(Dtb < 2) { return "Kem"; } if(Dtb < 5) { return "Yeu"; } if(Dtb < 6) { return "Trung Binh"; } if(Dtb < 7) { return "Trung Binh Kha"; } if(Dtb < 8) { return "Kha"; } if(Dtb < 9) { return "Gioi"; } return "Xuat Sac"; } string SinhVien::Getter_MaSo() { return MaSo; } void SinhVien::Setter_MaSo(string ms) { MaSo = ms; } void SinhVien::Setter_HoTen(string ht) { HoTen = ht; } string SinhVien::Getter_HoTen() { return HoTen; } void SinhVien::Setter_ListMonHoc(MonHoc mh) { ListMonHoc.push_back(mh); } vector<MonHoc> SinhVien:: Getter_ListMonHoc() { return ListMonHoc; }
#ifndef SESSION_H #define SESSION_H #include "ballstate.h" #include "worker.h" #include "render.h" #include <QObject> #include <QThread> #include <QString> class Session : public QObject { Q_OBJECT public: Session(QObject *parent = 0); ~Session(); public slots: void start(); void stop(); void queryNewState(); void updateState(BallState state); void submitFrame(QImage frame); private: BallState ballState_; bool isRunning_ = false; Worker worker_; Render render_; QThread workerThread_; QThread renderThread_; //QString stateFile_ = "jumping_ball_state.txt"; QString stateFile_ = "ball_state.db"; void loadState(); void saveState(); signals: void stopAll(); void getNewState(BallState state); void drawFrame(BallState state); void showFrame(QImage frame); }; #endif // SESSION_H
#pragma once #include "main.h" #include <utility> template <typename T> static inline void nativePush(T val) { static_assert(sizeof(T) <= sizeof(UINT64), "Type is too large"); UINT64 val64 = 0; *reinterpret_cast<T *>(&val64) = val; nativePush64(val64); } template <typename R> static inline R invoke(UINT64 hash) { nativeInit(hash); return *reinterpret_cast<R *>(nativeCall()); } template <typename R, class ... Args> static inline R invoke(UINT64 hash, Args&& ... args) { nativeInit(hash); (nativePush(std::forward<Args>(args)), ...); return *reinterpret_cast<R*>(nativeCall()); }
// Fill out your copyright notice in the Description page of Project Settings. #include "Stucchi.h" #include "ShipAIController.h" #include "StucchiPawn.h" AShipAIController::AShipAIController(const FObjectInitializer & OI) : Super(OI), possessed(nullptr) { PrimaryActorTick.bCanEverTick = true; } void AShipAIController::Possess(APawn* PossessedPawn) { possessed = dynamic_cast<AStucchiPawn*>(PossessedPawn); // set the pawn as possessed by the AIController base class only if it can be a AStucchiPawn type if (possessed != nullptr){ // ** Added for Step 11 possessed->SetAlternativeShoot(true); // ** END SetPawn(PossessedPawn); } } void AShipAIController::UnPossess() { possessed = nullptr; SetPawn(nullptr); } void AShipAIController::Tick(float DeltaTime) { if (possessed != nullptr) { possessed->FireShot(FVector::ForwardVector); } }
#pragma once #include "rpc_common.hpp" #include <hash_map> #include <boost/mpl/assert.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/at.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/front.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/identity.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_arity.hpp> namespace rpc{ namespace detail{ /** * 本类用以从某输入archive中反序列化参数列表, * 并以该参数列表调用指定的函数、获取返回值。 * 本类为虚基类。参数列表个数、类型皆由其子类决定。 */ class UnserializerAndCaller : private boost::noncopyable{ public: /** * 从ar中解析出参数列表,并执行函数,返回值序列化到ret串中。 * @param iar_params 参数输入流。从中获得函数的各参数。 * @param oar_result 接收运算返回值的输出流。 */ virtual void unserializeAndCall ( iarchive& iar_params, oarchive& oar_result ) = 0; /** * 虚析构函数。 */ virtual ~UnserializerAndCaller(){} }; template <class RetType> class UnserializerAndCaller0: public UnserializerAndCaller{ public: typedef RPC_FUNCTION_CLASS<RetType(void)> func_type; protected: func_type func; public: UnserializerAndCaller0(const func_type& fnc):func(fnc) {} virtual void unserializeAndCall( iarchive& iar_params, oarchive& oar_result ) { RetType retVal = func(); oar_result << packet( false, remote_call_error(), std::string() ); oar_result << retVal; } }; #define UAC_BEGIN \ template <class RetType, #define UAC_PROTO(i) >\ class UnserializerAndCaller ## i: public UnserializerAndCaller{\ public:\ typedef RPC_FUNCTION_CLASS<RetType( #define UAC_BODY(i) )> func_type;\ protected:\ func_type func;\ public:\ UnserializerAndCaller ## i(const func_type& fnc):func(fnc)\ {}\ \ virtual void unserializeAndCall( iarchive& iar_params, oarchive& oar_result )\ { #define UAC_END \ oar_result << packet( false, remote_call_error(), std::string() );\ oar_result << retVal;\ }\ }; #define UAC_iar(i) T ## i t ## i; iar_params>>t ## i; //UnserializerAndCaller1: UAC_BEGIN class T1 UAC_PROTO(1) const T1& UAC_BODY(1) UAC_iar(1) RetType retVal = func(t1); UAC_END; //UnserializerAndCaller2: UAC_BEGIN class T1, class T2 UAC_PROTO(2) const T1&, const T2& UAC_BODY(2) UAC_iar(1) UAC_iar(2) RetType retVal = func(t1, t2); UAC_END; //UnserializerAndCaller3: UAC_BEGIN class T1, class T2, class T3 UAC_PROTO(3) const T1&, const T2&, const T3& UAC_BODY(3) UAC_iar(1) UAC_iar(2) UAC_iar(3) RetType retVal = func(t1, t2, t3); UAC_END; //UnserializerAndCaller4: UAC_BEGIN class T1, class T2, class T3, class T4 UAC_PROTO(4) const T1&, const T2&, const T3&, const T4& UAC_BODY(4) UAC_iar(1) UAC_iar(2) UAC_iar(3) UAC_iar(4) RetType retVal = func(t1, t2, t3, t4); UAC_END; //UnserializerAndCaller5: UAC_BEGIN class T1, class T2, class T3, class T4, class T5 UAC_PROTO(5) const T1&, const T2&, const T3&, const T4&, const T5& UAC_BODY(5) UAC_iar(1) UAC_iar(2) UAC_iar(3) UAC_iar(4) UAC_iar(5) RetType retVal = func(t1, t2, t3, t4, t5); UAC_END; // RetType=void, template specialization template <> class UnserializerAndCaller0<void>: public UnserializerAndCaller{ public: typedef RPC_FUNCTION_CLASS<void(void)> func_type; protected: func_type func; public: UnserializerAndCaller0(const func_type& fnc):func(fnc) {} virtual void unserializeAndCall( iarchive& iar_params, oarchive& oar_result ) { func(); oar_result << packet( false, remote_call_error(), std::string() );\ } }; #define void_UAC_BEGIN \ template < #define void_UAC_PROTO(i) >\ class UnserializerAndCaller ## i < void, #define void_UAC_PROTO_NEXT >\ : public UnserializerAndCaller{\ public:\ typedef RPC_FUNCTION_CLASS< void ( #define void_UAC_BODY(i) )> func_type;\ protected:\ func_type func;\ public:\ UnserializerAndCaller ## i(const func_type& fnc):func(fnc)\ {}\ \ virtual void unserializeAndCall( iarchive& iar_params, oarchive& oar_result )\ { #define void_UAC_END \ oar_result << packet( false, remote_call_error(), std::string() );\ }\ }; #define void_UAC_iar(i) T ## i t ## i; iar_params>>t ## i; //UnserializerAndCaller1: void_UAC_BEGIN class T1 void_UAC_PROTO(1) T1 void_UAC_PROTO_NEXT const T1& void_UAC_BODY(1) void_UAC_iar(1) func(t1); void_UAC_END; //UnserializerAndCaller2: void_UAC_BEGIN class T1, class T2 void_UAC_PROTO(2) T1, T2 void_UAC_PROTO_NEXT const T1&, const T2& void_UAC_BODY(2) void_UAC_iar(1) void_UAC_iar(2) func(t1, t2); void_UAC_END; //UnserializerAndCaller3: void_UAC_BEGIN class T1, class T2, class T3 void_UAC_PROTO(3) T1, T2, T3 void_UAC_PROTO_NEXT const T1&, const T2&, const T3& void_UAC_BODY(3) void_UAC_iar(1) void_UAC_iar(2) void_UAC_iar(3) func(t1, t2, t3); void_UAC_END; //UnserializerAndCaller4: void_UAC_BEGIN class T1, class T2, class T3, class T4 void_UAC_PROTO(4) T1, T2, T3, T4 void_UAC_PROTO_NEXT const T1&, const T2&, const T3&, const T4& void_UAC_BODY(4) void_UAC_iar(1) void_UAC_iar(2) void_UAC_iar(3) void_UAC_iar(4) func(t1, t2, t3, t4); void_UAC_END; //UnserializerAndCaller5: void_UAC_BEGIN class T1, class T2, class T3, class T4, class T5 void_UAC_PROTO(5) T1, T2, T3, T4, T5 void_UAC_PROTO_NEXT const T1&, const T2&, const T3&, const T4&, const T5& void_UAC_BODY(5) void_UAC_iar(1) void_UAC_iar(2) void_UAC_iar(3) void_UAC_iar(4) void_UAC_iar(5) func(t1, t2, t3, t4, t5); void_UAC_END; typedef RPC_SHARED_PTR<detail::UnserializerAndCaller> UnserializerAndCallerPtr; } /** * 函数集。 */ class function_set : private boost::noncopyable{ typedef stdext::hash_map<std::string, detail::UnserializerAndCallerPtr> map_type; map_type id2funcmap; boost::recursive_mutex mtx; public: function_set(){} /** * 往函数集中新增一个函数。 * @param funcId 用来标识此函数的id。8位字符串类型。 * @param func 函数。 * @exception func_id_already_exists 集中已存在一个相同名称的函数。 */ template<class FuncType> void add(const std::string& func_id, FuncType* func) throw(func_id_already_exists) { add<FuncType>(func_id, RPC_FUNCTION_CLASS<FuncType>(func)); } /** * 往函数集中新增一个函数。 * @param func_id 用来标识此函数的id。8位字符串类型。 * @param func 函数。 * @exception func_id_already_exists 集中已存在一个相同名称的函数。 */ template<class Signature> void add(const std::string& func_id, const typename RPC_FUNCTION_CLASS<Signature>& func) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; typename registerFunctionImplStruct<Signature, function_types::function_arity<Signature>::value> obj; obj.invoke(func_id, func, this); } /** * 从函数集中移除一个函数。 * @param func_id 用来标识此函数的id。8位字符串类型。 * @exception func_id_not_found 集中不存在此名称的RPC函数。 */ void remove(std::string func_id) throw(func_id_not_found) { boost::recursive_mutex::scoped_lock lck(mtx); map_type::const_iterator itr; if ( (itr=id2funcmap.find(func_id)) != id2funcmap.end() ) { id2funcmap.erase(itr); }else{ throw func_id_not_found(); } } /** * 执行一个RPC函数。 * @param func_id 用来标识此函数的id。8位字符串类型。 * @exception func_id_not_found 集中不存在此名称的RPC函数。 */ void invoke(const std::string& func_id, iarchive& iar_params, oarchive& oar_result ) throw(func_id_not_found, boost::archive::archive_exception) { boost::recursive_mutex::scoped_lock lck(mtx); map_type::const_iterator itr; if ( (itr=id2funcmap.find(func_id)) != id2funcmap.end() ) { try { (*itr).second->unserializeAndCall(iar_params, oar_result); } catch ( const boost::archive::archive_exception& e ) { oar_result << packet( false, remote_call_error(remote_call_error::func_call_error, "Invalid parameter: \""+std::string( e.what() )+"\"."), std::string() ); } catch ( const std::exception& e ) { oar_result << packet( false, remote_call_error(remote_call_error::func_call_error, "Exception: \""+std::string( e.what() )+"\"."), std::string() ); } catch ( ... ) { oar_result << packet( false, remote_call_error(remote_call_error::func_call_error, "Unknown exception." ), std::string() ); } } else { oar_result << packet( false, remote_call_error(remote_call_error::func_not_found, "RPC function \""+func_id+"\" not found."), std::string() ); } } private: #pragma region registerFunctionImpl functions template<class Signature, int ArgCount> struct registerFunctionImplStruct{ }; template<class Signature> struct registerFunctionImplStruct<Signature, 0> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; ths->registerFunctionImpl<function_types::result_type<Signature>::type>(funcId, func); } }; template<class Signature> struct registerFunctionImplStruct<Signature, 1> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; ths->registerFunctionImpl<function_types::result_type<Signature>::type, boost::mpl::at_c<ArgTypes, 0>::type>(funcId, func); } }; template<class Signature> struct registerFunctionImplStruct<Signature, 2> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; ths->registerFunctionImpl<function_types::result_type<Signature>::type, boost::mpl::at_c<ArgTypes, 0>::type, boost::mpl::at_c<ArgTypes, 1>::type>(funcId, func); } }; template<class Signature> struct registerFunctionImplStruct<Signature, 3> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; ths->registerFunctionImpl<function_types::result_type<Signature>::type, boost::mpl::at_c<ArgTypes, 0>::type, boost::mpl::at_c<ArgTypes, 1>::type, boost::mpl::at_c<ArgTypes, 2>::type>(funcId, func); } }; template<class Signature> struct registerFunctionImplStruct<Signature, 4> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; ths->registerFunctionImpl<function_types::result_type<Signature>::type, boost::mpl::at_c<ArgTypes, 0>::type, boost::mpl::at_c<ArgTypes, 1>::type, boost::mpl::at_c<ArgTypes, 2>::type, boost::mpl::at_c<ArgTypes, 3>::type>(funcId, func); } }; template<class Signature> struct registerFunctionImplStruct<Signature, 5> { void invoke(const std::string& funcId, const typename RPC_FUNCTION_CLASS<Signature>& func, function_set* ths) throw(func_id_already_exists) { using namespace boost; typedef function_types::parameter_types<Signature>::type ArgTypes; ths->registerFunctionImpl<function_types::result_type<Signature>::type, boost::mpl::at_c<ArgTypes, 0>::type, boost::mpl::at_c<ArgTypes, 1>::type, boost::mpl::at_c<ArgTypes, 2>::type, boost::mpl::at_c<ArgTypes, 3>::type, boost::mpl::at_c<ArgTypes, 4>::type>(funcId, func); } }; #pragma endregion template<class RetType> void registerFunctionImpl(const std::string& funcId, const typename detail::UnserializerAndCaller0<RetType>::func_type& func) throw(func_id_already_exists) { boost::recursive_mutex::scoped_lock lck(mtx); map_type::iterator itr ; if( (itr=this->id2funcmap.find(funcId)) != this->id2funcmap.end() ){ throw func_id_already_exists(); }else{ this->id2funcmap[funcId] = detail::UnserializerAndCallerPtr(new detail::UnserializerAndCaller0<RetType>(func)); } } #define registerFunction_BEGIN \ template<class RetType, #define registerFunction_PROTO(i) >\ void registerFunctionImpl(const std::string& funcId,\ const typename detail::UnserializerAndCaller ## i<RetType, #define registerFunction_BODY(i) >::func_type& func)\ throw(func_id_already_exists)\ {\ boost::recursive_mutex::scoped_lock lck(mtx);\ map_type::iterator itr ;\ if( (itr=this->id2funcmap.find(funcId)) != this->id2funcmap.end() ){\ throw func_id_already_exists();\ }else{\ this->id2funcmap[funcId] = detail::UnserializerAndCallerPtr(new detail::UnserializerAndCaller ## i<RetType, #define registerFunction_END >(func));\ }\ }\ //registerFunction: 1 param registerFunction_BEGIN class T1 registerFunction_PROTO(1) T1 registerFunction_BODY(1) T1 registerFunction_END; //registerFunction: 2 param registerFunction_BEGIN class T1, class T2 registerFunction_PROTO(2) T1, T2 registerFunction_BODY(2) T1, T2 registerFunction_END; //registerFunction: 3 param registerFunction_BEGIN class T1, class T2, class T3 registerFunction_PROTO(3) T1, T2, T3 registerFunction_BODY(3) T1, T2, T3 registerFunction_END; //registerFunction: 4 param registerFunction_BEGIN class T1, class T2, class T3, class T4 registerFunction_PROTO(4) T1, T2, T3, T4 registerFunction_BODY(4) T1, T2, T3, T4 registerFunction_END; //registerFunction: 5 param registerFunction_BEGIN class T1, class T2, class T3, class T4, class T5 registerFunction_PROTO(5) T1, T2, T3, T4, T5 registerFunction_BODY(5) T1, T2, T3, T4, T5 registerFunction_END; }; typedef RPC_SHARED_PTR<function_set> function_set_ptr; }
#include <ros/ros.h> #include <stdio.h> #include <stdlib.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/video/tracking.hpp> #include <PerFoRoControl/SelectTarget.h> #include <PerFoRoControl/MODE.h> #include <person_tracking/TrackedObject.h> using namespace cv; using namespace std; static const std::string OPENCV_WINDOW = "Track Pant Window"; class TrackPant { public: TrackPant(); ~TrackPant() {cv::destroyWindow(OPENCV_WINDOW);} protected: /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pant_pub_; ros::Publisher track_pant_pub_; ros::Subscriber target_pant_sub_; ros::Subscriber mode_sub_; Mat frame; float maxDistance, distPrevCurrent; int dilation_size, erosion_size; Mat elemDilate, elemErode; Mat structure_elem; bool IMSHOW; int trackObject; Rect selection; Scalar mColorRadius; Scalar mLowerBound; Scalar mUpperBound; Point selectCentroid, selectCenter, origin; int rectOffset; double minDistThresh; double distThresh; int missCount; KalmanFilter KF; Point kalmanEstimatePt; bool selectObject; int navX, navY, prevmsg = 1, PerFoRoMode = 0; person_tracking::TrackedObject pant_msg; void drawArrow(Mat image, Point p, Point q, Scalar color, int arrowMagnitude, int thickness, int line_type, int shift); void ImageCallback(const sensor_msgs::ImageConstPtr& msg); void SelectTargetPantCallback(const PerFoRoControl::SelectTarget msg); void ModeCallback(const PerFoRoControl::MODE msg); void initTracker(); Point kalmanTracker(Point centroid); };
#include "Box.h" Box::Box() { velocity = sf::Vector2f(10, 0); scale = 20; } Box::~Box() { } void Box::update(float dt) { changePos = velocity * scale * dt; move(changePos); } void Box::setVelocity(sf::Vector2f vel) { velocity = vel; } void Box::collisionResponse() { velocity = -velocity; }
#include "Poly.h" #include <iostream> Poly::Poly() { m_first = nullptr; } Poly::Poly(int high, int *coeffArray)//应对传入的high和数组进行检查,第一个参数为最高项指数,数组元素个数应为high+1 { m_high = high; m_first = new PolyNode(); PolyNode *p = m_first; for (int i = 0; i < high ; i++)//若为high+1,最后会多申请一个内存空间,里面值默认为0 { p->index = i; p->coeff = coeffArray[i]; p->next = new PolyNode(); p = p->next; } p->index = high; p->coeff = coeffArray[high]; } PolyNode* Poly::getFirst() const { return m_first; } void Poly::show() const { if (m_first != nullptr) { PolyNode *p = m_first; std::cout << p->coeff;//指数为0的项不显示x^0部分 p = p->next; while (p != nullptr) { if (p->coeff != 0)//系数为0的项不显示 { std::cout << "+" << p->coeff << "x^" << p->index; } p = p->next; } std::cout << std::endl; } } void Poly::add(const Poly &poly1, const Poly &poly2, Poly &poly) { PolyNode *p1 = poly1.getFirst(); PolyNode *p2 = poly2.getFirst(); PolyNode *p = poly.getFirst(); while (p1 != nullptr && p2 != nullptr) { p->index = p1->index; p->coeff = p1->coeff + p2->coeff; p1 = p1->next; p2 = p2->next; p = p->next; } if (p1 == nullptr) { while (p2 != nullptr) { p->index = p2->index; p->coeff = p2->coeff; p2 = p2->next; p = p->next; } } else { while (p1 != nullptr) { p->index = p1->index; p->coeff = p1->coeff; p1 = p1->next; p = p->next; } } }
/* * redblacktree.h * * Created on: Apr 27, 2017 * Author: Benjamin Kleinberg * * This is a red black tree structure that inherits from a binary search tree. * A red black tree has the following properties: * 1) All the nodes are red or black * 2) The root node is black * 3) The null leaf nodes are black * 4) All red nodes have two black children * 5) Every simple path from a node to a null leaf has the same number of black nodes * * These properties make the tree approximately balanced, which results in a height * of O(log(n)), where n is the number of elements in the tree. */ #ifndef REDBLACKTREE_H_ #define REDBLACKTREE_H_ #include"binarytree.h" #include"redblacknode.h" #include"int.h" class RedBlackTree : public BinaryTree { private: static RedBlackNode* makeNode(Int val, int color); virtual void insertNode(RedBlackNode* node); void deleteFixup(RedBlackNode* parent, RedBlackNode* error); void insertFixup(RedBlackNode* parent, RedBlackNode* error); public: RedBlackTree(); virtual ~RedBlackTree(); RedBlackNode* rotateLeft(RedBlackNode* node); RedBlackNode* rotateRight(RedBlackNode* node); void rotateEdge(RedBlackNode* parent, RedBlackNode* child); virtual int insertVal(Int val); virtual int deleteVal(Int val); }; #endif /* REDBLACKTREE_H_ */
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 __MAIN_SCENE_H__ #define __MAIN_SCENE_H__ #include "cocos2d.h" #include "player.h" #include "monster.h" #include "AudioEngine.h" //音效引擎 #include <vector> void attack_sound(std::string gun_name); class MainScene : public cocos2d::Scene { public: enum Direction { UP, DOWN, LEFT, RIGHT }; //std::vector<Sprite> monster_group; virtual bool init() override; static cocos2d::Scene* scene(); bool onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event); bool onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event); //Direction Judgedirection(const Vec2& mon_pos); void menuCloseCallback(Ref* sender); void scheduleBlood(float delta); void addhp(float delta); void always_move(float delta); void always_attack_normal(float delta); void always_attack_uzi(float delta); void addBarrel(const cocos2d::Vec2& s); void addBox(const cocos2d::Vec2& pos); void change_weapon_animation(const std::string& weapon_name, bool out_of_bullet = false); void judge_and_attack(); //void mov_monsters(float delta); bool onContactBegin_player_box(cocos2d::PhysicsContact& contact); bool onContactBegin_bullet_barrel(cocos2d::PhysicsContact& contact); bool onContactBegin_player_fireball(cocos2d::PhysicsContact& contact); bool onContactBegin_bullet_monster(cocos2d::PhysicsContact& contact); void level_up(); // implement the "static create()" method manually void monster_move(float dt); //用于僵尸移动调度器 void monster_attack(float dt); //用于僵尸攻击调度器 void monster_death(float dt); //用于僵尸死亡调度器 void border(float dt); //边界控制 void addBigMonster(int birth_point); //增加一个boss void addSmallMonster(int birth_point); //增加一个boss void set_z_oder(float dt); //对所有项目进行渲染顺序的调整,解决覆盖问题 int get_z_odre(cocos2d::Node* spr); static int read_highest_score_from_file(); void save_highest_score(); //如果当前分数高于历史最高分,则保存当前分数 CREATE_FUNC(MainScene); private: player* _player; int score=0; static std::string filename; int current_level = 0; std::map<cocos2d::EventKeyboard::KeyCode, bool> keys; std::vector<BigMonster*> _BigMonster; std::vector<SmallMonster*> _SmallMonster; cocos2d::Label* current_score_label; cocos2d::Label* current_level_label; }; #endif // __HELLOWORLD_SCENE_H__
#include <bandit/bandit.h> #include <rint.hpp> #include <iostream> using namespace rint; using namespace snowhouse; using namespace bandit; template<auto min, auto max, typename E> void expect_value_type() { bool const is_same = std::is_same< typename ranged_int<min, max>::value_type, E>::value; AssertThat(is_same, IsTrue()); } template<typename E> void expect_value_type_for_limits() { expect_value_type<std::numeric_limits<E>::min(), std::numeric_limits<E>::max(), E>(); } template<typename T> auto make_ranged_int_with_min() { return ranged_int<std::numeric_limits<T>::min(), 0> {std::numeric_limits<T>::min()}; } go_bandit([]{ describe("selecting type", []{ it("shall be uint8", []{ expect_value_type_for_limits<std::uint8_t>(); }); it("shall be int8", []{ expect_value_type_for_limits<std::int8_t>(); }); it("shall be uint16", []{ expect_value_type_for_limits<std::uint16_t>(); expect_value_type<std::numeric_limits<std::uint16_t>::min(), std::numeric_limits<std::uint8_t>::max()+1, std::uint16_t>(); }); it("shall be int16", []{ expect_value_type_for_limits<std::int16_t>(); expect_value_type<std::numeric_limits<std::int8_t>::min()-1, std::numeric_limits<std::uint8_t>::max()+1, std::int16_t>(); }); it("shall be uint32", []{ expect_value_type_for_limits<std::uint32_t>(); expect_value_type<std::numeric_limits<std::uint32_t>::min(), std::numeric_limits<std::uint16_t>::max()+1, std::uint32_t>(); }); it("shall be int32", []{ expect_value_type_for_limits<std::int32_t>(); expect_value_type<std::numeric_limits<std::int16_t>::min()-1, std::numeric_limits<std::int16_t>::max()+1, std::int32_t>(); }); }); describe("min max", []() { it("min shall be smaller then max", []{ ranged_int<29, 30>{}; }); }); describe("equality comparision", []() { it("two rint shall be equal", []{ AssertThat((ranged_int<0, 30>{1}), Equals((ranged_int<0, 30>{1}))); AssertThat((ranged_int<0, 30>{1}), Equals((ranged_int<0, 40>{1}))); }); it("two rint shall not be equal", []{ AssertThat((ranged_int<0, 30>{1}), Is().Not().EqualTo((ranged_int<0, 30>{2}))); AssertThat((ranged_int<0, 30>{1}), Is().Not().EqualTo((ranged_int<0, 40>{2}))); }); }); describe("comparision operator", []() { it("greater", []{ AssertThat((ranged_int<0, 30>{2}), IsGreaterThan((ranged_int<0, 30>{1}))); AssertThat((ranged_int<0, 30>{2}), IsGreaterThan((ranged_int<0, 40>{1}))); }); it("less", []{ AssertThat((ranged_int<0, 30>{1}), IsLessThan((ranged_int<0, 30>{2}))); AssertThat((ranged_int<0, 30>{1}), IsLessThan((ranged_int<0, 40>{2}))); }); }); describe("cast function", []() { it("shall throw when converting negative val to unsigned", []{ AssertThrows(std::out_of_range, (to_integral<std::uint8_t>(ranged_int<-10, 30>{-2}))); AssertThrows(std::out_of_range, (to_integral<std::uint16_t>(ranged_int<-10, 30>{-2}))); AssertThrows(std::out_of_range, (to_integral<std::uint32_t>(ranged_int<-10, 30>{-2}))); }); it("shall throw when converting out of range value", []{ AssertThrows(std::out_of_range, (to_integral<std::int8_t>(make_ranged_int_with_min<std::int32_t>()))); AssertThrows(std::out_of_range, (to_integral<std::int16_t>(make_ranged_int_with_min<std::int32_t>()))); AssertThrows(std::out_of_range, (to_integral<std::int16_t>( ranged_int<0, std::numeric_limits<std::uint16_t>::max() >{ std::numeric_limits<std::uint16_t>::max()}))); }); }); });
#ifndef __SCENE_MANAGER_H__ #define __SCENE_MANAGER_H__ #include "MainMenu.h" USING_NS_CC; #define TRANSITION_DURATION 1.2f class SceneManager : public CCObject { public: SceneManager(void); ~SceneManager(void); static void goMenu(); static void goPlay(); static void goStop(); static void go(CCLayer* layer); static void push(CCLayer* layer); static void pop(); static CCScene* wrap(CCLayer* layer); //去CreditsLayer那边去 static int nIdx; //声明静态旗标 static CCTransitionScene* createTransition(float t,CCScene* s); //用来返回 CCTransitionScene 对象,具体看.cpp中的实现 }; #endif
//******************************************************************************* //* Copyright (c) 2013. Federal University of Para (UFPA), Brazil and * //* University of Bern (UBern), Switzerland * //* Developed by Research Group on Computer Network and Multimedia * //* Communication (GERCOM) of UFPA in collaboration to Communication and * //* Distributed Systems (CDS) research group of UBern. * //* All rights reserved * //* * //* Permission to use, copy, modify, and distribute this protocol and its * //* documentation for any purpose, without fee, and without written * //* agreement is hereby granted, provided that the above copyright notice, * //* and the author appear in all copies of this protocol. * //* * //* Module: Application to camera nodes with node mobility and QoE-aware FEC* //* * //* Ref.: Z. Zhao, T. Braun, D. Rosário, E. Cerqueira, R. Immich, and * //* M. Curado, “QoE-aware FEC mechanism for intrusion detection in * //* multi-tier wireless multimedia sensor networks,” * //* in Proceedings of the 1st International Workshop on Wireless * //* Multimedia Sensor Networks (WiMob’12 WSWMSN), Barcelona, Spain, * //* oct. 2012, pp. 697–704. * //* * //* Version: 2.0 * //* Authors: Denis do Rosário <denis@ufpa.br> * //* * //******************************************************************************/ #include "WingoApp.h" #include "WiseDebug.h" #include "math.h" //Biblioteca matematica #include "time.h" //Biblioteca para escolher aleatorio #include "algorithm" #include <list> #include <cctype> Define_Module(WingoApp); WingoApp::WingoApp() { } WingoApp::~WingoApp() { } void WingoApp::initialize() { WiseBaseApplication::initialize(); isSink = par("isSink"); in_coligate = par("in_coligate"); type = par("type"); destino_final = par("destino_final"); isSource = par("isSource"); timeToSend = par("timeToSend"); idVideo = -1; cModule* mod = getParentModule()->getModuleByRelativePath("MobilityManager"); headOn = false; //cModule* OraculoSrcmod = getParentModule()->getModuleByRelativePath("MobilityManager"); //OraculoSrc = check_and_cast <VirtualMobilityManager*>(getParentModule()->getParentModule()->getParentModule()->getSubmodule("node",rcvPackets->getSrc_final())->getSubmodule("MobilityManager")); mobilityModule = check_and_cast<VirtualMobilityManager*>(mod); location = mobilityModule->getLocation(); tempLocation = mobilityModule->getLocation(); macModule = check_and_cast <VirtualMac*>(getParentModule()->getSubmodule("Communication")->getSubmodule("MAC")); //trace() << "Tamanho do buffer: " << macModule->getBufferSize() << " pkts"; //trace() << "taxa de envio: " << macModule->dataRate_out << " mbits/s"; //trace() << "taxa de recepcao: " << macModule->dataRate_in << " mbits/s"; if(isSource){ if(type == 1){ //Se o valor da variavel type no arquivo .ini for igual a 1, então executar estas ações (Valor modificado no arquivo .ini) setTimer(GROUP, timeToSend); //ID origem e ID destino idOrig = self; idDst = destino_final; }else{ setTimer(REQUEST_MULTIMEDIA, timeToSend); } } } void WingoApp::finish() { WiseBaseApplication::finish(); crtlIterator = set.begin(); while(crtlIterator != set.end()){ video cls = *crtlIterator; fclose(cls.pFile); crtlIterator = set.erase(crtlIterator); } cOwnedObject *Del=NULL; int OwnedSize = this->defaultListSize(); for(int i=0; i<OwnedSize; i++){ Del = this->defaultListGet(0); this->drop(Del); delete Del; } } void WingoApp::timerFiredCallback(int index){ switch (index) { case REQUEST_MULTIMEDIA:{ trace() << "####################REQUEST_MULTIMEDIA###########################"; idVideo ++; WiseApplicationPacket* m = new WiseApplicationPacket("request multimedia", MULTIMEDIA_REQUEST_MESSAGE); m->setIdNode(self); m->setIdVideo(idVideo); send(m, "toSensorDeviceManager"); trace() << "sender restart round to " << idVideo << "\n"; //if (idVideo < 0) //qtd de vídeos a serem transmitidos // setTimer(REQUEST_MULTIMEDIA, 20); break; } case TRACE_MOVEMENT:{ location = mobilityModule->getLocation(); if (tempLocation.x != location.x || tempLocation.y != location.y){ tempLocation = mobilityModule->getLocation(); WiseApplicationPacket* m = new WiseApplicationPacket("update location", MOBILE_MESSAGE); m->setSource(self); m->setX(location.x); m->setY(location.y); send(m, "toSensorDeviceManager"); } setTimer(TRACE_MOVEMENT, 5); break; } case GROUP:{ trace() << "********************GROUP***************************"; location = mobilityModule->getLocation(); //Localização do nó if(headOn){ trace() << "LIDER-Enviando mensagem de novo para todos..."; WiseApplicationPacket *beacon1 = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); beacon1->setAppPacketKind(APP_LEADER); beacon1->setSource(self); beacon1->setSrc_head(SourceHead); beacon1->setHead(true); toNetworkLayer(beacon1, BROADCAST_NETWORK_ADDRESS);//envio da msg externa em broadcast para os outros nós headOn = false; } if(isSource){ if(mobilityModule->getSpeed() >= 5.0 && mobilityModule->getSpeed() <= 100.0){ trace() << "NÓ-INICIAL: " << self; trace() << "SPPED LEADER: " << mobilityModule->getSpeed(); vOrig = mobilityModule->getSpeed(); //Velocidade do Lider xOrig = location.x; yOrig = location.y; } } gama = mobilityModule->getSpeed()+167.0+(rand() % 5); WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); //Cria um pacote que será enviado para os demais nós beacon->setX(location.x); beacon->setY(location.y); beacon->setSource(self); beacon->setSpeed(mobilityModule->getSpeed()); beacon->setGama_s(gama); beacon->setDestino_final(idDst); beacon->setAppPacketKind(APP_NTFY); beacon->setSrc_final(idOrig); beacon->setXOrig(xOrig); beacon->setYOrig(yOrig); beacon->setVOrig(vOrig); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS); //envio da msg externa em broadcast para os outros nos trace() << "WVL - 1° Etapa para coligação"; trace() << "Node " << self << " is moving at " << mobilityModule->getSpeed() << "m/s"; trace() << "Node " << self << " location x: " << location.x << " location y: " << location.y; trace() << "Node " << self << " sending a GROUP-NTFY message to network layer in broadcast"; trace() << "Valor para participar da coligação, GAMA: " << gama << "\n"; setTimer(SELECTION, 0.05); break; } case SELECTION:{ trace() << "!!!!!!!!!!!!!!!!!!!!SELECTION!!!!!!!!!!!!!!!!!!!!!!!!!!!"; if(carList.size() != 0){ cS = 0; for(list<CarMovements>::iterator it = carList.begin(); it != carList.end();it++){ trace() << "New_car "; trace() << "ID: " << it->idCar; trace() << "X: " << it->xCar; trace() << "Y: " << it->yCar; trace() << "Velocidade: " << it->vCar; trace() << "UFI: " << it->ufCar << "\n"; if(cS == 0){ menorS = abs(it->ufCar-gama); posMenor = 0; }else{ if(abs(it->ufCar-gama) < menorS){ posMenor = cS; menorS = abs(it->ufCar-gama); } } cS++; //Incrementa o valor de cS } carEsc = carList.begin(); advance(carEsc, posMenor); //Carro escolhido pelo menor valor de UFi trace() << "Carro escolhido: " << carEsc->idCar; trace() << "Velocidade de Coligação: " << vOrig; trace() << "Velocidade atual do nó: " << carEsc->vCar; trace() << "X destino: " << carEsc->xCar; trace() << "Y destino: " << carEsc->yCar; trace() << "Valor da UFi: " << carEsc->ufCar << "\n"; WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); beacon->setDestinationX(mobilityModule->getX_Final()); beacon->setDestinationY(mobilityModule->getY_Final()); beacon->setDestination(carEsc->idCar); beacon->setSpeed_final(vOrig); beacon->setDestino_final(destino_final); beacon->setSrc_final(idOrig); beacon->setX(location.x); beacon->setY(location.y); beacon->setAppPacketKind(APP_CRTY); beacon->setSource(self); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS);//envio da msg externa em broadcast para os outros nós WiseApplicationPacket *ctlMsg = new WiseApplicationPacket("next hop", APPLICATION_PLATOON); //informar o routing do next hop ctlMsg->setNextHop(carEsc->idCar); //colocar qual sera o proximo salto ctlMsg->setSource(idOrig); //colocar o nó que originou a criacao do platoon ctlMsg->setDestination(destino_final); //colocar qual sera o proximo salto toNetworkLayer(ctlMsg, BROADCAST_NETWORK_ADDRESS); //envio da msg externa em broadcast para os outros nos if (self == idOrig){ trace() << "NADA!!!\n"; //setTimer(REQUEST_MULTIMEDIA, 0); } setTimer(REPEAT, 0.8); }else{ trace() << "Lista vazia, não há candidatos para coligação\n"; setTimer(GROUP, 0.1); } break; } case REPEAT:{ trace() << "++++++++++++++++++++REPEAT+++++++++++++++++++++++++++"; if(headOn == false){ trace() << "NOVO Lider não respondeu\n"; carList.clear(); setTimer(GROUP, 0.1); }else{ trace() << "NOVO Lider respondeu\n"; cancelTimer(GROUP); //Cancela qualquer nova coligação que esteja acontecendo cancelTimer(SELECTION); } break; } } } void WingoApp::AddReceivedTrace(double time, bool generateTrace, TraceInfo tParam) { if (generateTrace){ if(set.empty()){ writeRdTrace(tParam.nodeId,tParam.seqNum); //trace() << "Frame " << tParam.id << " added"; } for (crtlIterator = set.begin(); crtlIterator != set.end(); crtlIterator++){ video info = *crtlIterator; /* * Test if the output file is already created * If the packtes is for the current seq number save the frame on the output file * else close the file and create the new output file with the new seq number */ if (tParam.nodeId == info.ch && tParam.seqNum == info.sn){ fprintf(info.pFile, "%f id %d udp %d\n",time, tParam.idFrame, tParam.byteLength); WiseApplicationPacket *pktTrace = new WiseApplicationPacket("received video frame", APPLICATION_STATISTICS_MESSAGE); pktTrace->setIdVideo(info.sn); pktTrace->setIdNode(info.ch); pktTrace->setIdFrame(0); toNetworkLayer(pktTrace, BROADCAST_NETWORK_ADDRESS); //trace() << "Frame " << tParam.id << " added"; } else if (tParam.nodeId != info.ch || tParam.seqNum != info.sn){ fclose(info.pFile); crtlIterator = set.erase(crtlIterator); writeRdTrace(tParam.nodeId, tParam.seqNum); } } } } bool WingoApp::FillPacketPool(int packet_uid, int fec_data_size, const u_char *tmp_packet, int nodeId) { // carregando os campos fec_frames temp; temp.fhs = (int) tmp_packet[0]; // fec header size temp.k = (int) tmp_packet[1]; // number of packets without redundancy temp.n = (int) tmp_packet[2]; // number of redundant pkts temp.eid = (int) tmp_packet[4]; // evalvid id temp.fds = fec_data_size; // fec data size temp.nodeId = nodeId; // source node Id temp.count = 0; // TODO: verificar // preciso ajustar os uid dos pacotes, pq senao posso ficar com id's diferentes no sd_file e rd_file // TODO: melhorar a explicacao da necessidade de ajuste do uid int adjusted_uid = (packet_uid-tmp_packet[3])+temp.count; temp.packet_uid.push_back(adjusted_uid); // reservando espaco para o array dinamico (utilizado array pq o fec decode nao aceita vector) temp.idx = new int[temp.k]; temp.idx[temp.count] = (int)tmp_packet[3]; // reservando espaco para o buffer temp.payload = (u_char**)malloc(temp.k * sizeof(void *)); for (int i = 0 ; i < temp.k ; i++ ) temp.payload[i] = (u_char*)malloc(temp.fds); memmove(temp.payload[temp.count], tmp_packet+temp.fhs, temp.fds); temp.count++; pktPool.push_back(temp); trace() << " pktPool size " << pktPool.size(); return true; } bool WingoApp::rebuildFECBlock(int nodeId, int seqNum, int index){ if (pktPool[index].count>0) { trace() << " rebuildFECBlock::received " << pktPool[index].count << " of " << pktPool[index].n << " k: " << pktPool[index].k << " eid: " << pktPool[index].eid << " for node id " << pktPool[index].nodeId; int k(pktPool[index].k); int n(pktPool[index].n); int sz(pktPool[index].fds); ReedSolomonFec neoFec; void *newCode = neoFec.create(k,n); if (neoFec.decode((fec_parms *)newCode, (void**)pktPool[index].payload, pktPool[index].idx, sz)) { //trace() << " rebuildFECBlock::detected singular matrix ..." << " n " << n; } u_char **d_original = (u_char**)neoFec.safeMalloc(k * sizeof(void *), "d_original ptr"); for (int i = 0 ; i < k ; i++ ) { d_original[i] = (u_char*)neoFec.safeMalloc(sz, "d_original data"); } neoFec.BuildSampleData(d_original, k, sz); int errors(0); for (int i=0; i<k; i++){ if (bcmp(d_original[i], pktPool[index].payload[i], sz )) { errors++; trace() << " " << errors << " - rebuildFECBlock::error reconstructing block " << i << " k " << k << " n " << n; } } int included = 0; // adiciono o log separadamente da validacao pq algumas vezes dava erro em relacao aos pacotes // recuperados ... ex recebia 1,2,4 de 4 ... mas o fec recuperava 2,3,4 ocasionando pois nao // havia o ID do pacote 3 (que foi perdido) // entao desconsidero quais foram recuperados e adiciono os que possuem ID valido for (int i=0; i<k-errors; i++) { TraceInfo tParam; tParam.idFrame = pktPool[index].packet_uid[i]; tParam.byteLength = sz + 5; tParam.nodeId = nodeId; tParam.seqNum = seqNum; AddReceivedTrace(SIMTIME_DBL(simTime()), true, tParam); included ++; trace() << " whith FEC included => node id " << tParam.nodeId << " seq number " << tParam.seqNum << " frame id " << tParam.idFrame << "\n"; if (included == pktPool[index].k){ WiseApplicationPacket *pktTrace = new WiseApplicationPacket("received video frame", APPLICATION_STATISTICS_MESSAGE); pktTrace->setIdVideo(tParam.seqNum); pktTrace->setIdNode(tParam.nodeId); pktTrace->setIdFrame(1); toNetworkLayer(pktTrace, BROADCAST_NETWORK_ADDRESS); } } neoFec.destroy((fec_parms*)newCode); if (d_original != NULL) { for (int i = 0 ; i < k ; i++ ){ free(d_original[i]); d_original[i] = NULL; } } free(d_original); d_original = NULL ; ClearPacketPool(index); trace() << " pktPool size " << pktPool.size(); return true; } return false; } bool WingoApp::ClearPacketPool(int index) { pktPool.erase(pktPool.begin()+index); return true; } bool WingoApp::enoughPacketsReceived(int index, int indexEidPkts) { trace() << " enoughPacketsReceived"; trace() << " discard_eid_packets: " << discardEidPkts[indexEidPkts].discard_eid_packets << " count: " << pktPool[index].count << " k-1: " << pktPool[index].k-1; if ( (discardEidPkts[indexEidPkts].discard_eid_packets == 0) && (pktPool[index].count > (pktPool[index].k-1)) ) { trace() << " true"; return true; } trace() << " false\n"; return false; } void WingoApp::handleMobilityControlMessage(MobilityManagerMessage* pkt) { } void WingoApp::fromNetworkLayer(cPacket* msg, const char* src, double rssi, double lqi) { switch (msg->getKind()) { case APPLICATION_MESSAGE:{ WiseApplicationPacket *rcvPackets = check_and_cast<WiseApplicationPacket*>(msg); //Enviar mensagem caso queira coligar ou descoligar switch (rcvPackets->getAppPacketKind()) { case APP_NTFY:{ location = mobilityModule->getLocation(); if(location.x > rcvPackets->getX()){ trace() << "ZDI=IN"; if(in_coligate == false){ trace() << "IN_GROUP=FALSE"; trace() << "DISTÂNCIA: " << sqrt(pow((location.x-rcvPackets->getX()),2)+pow((location.y-rcvPackets->getY()),2)); distanciaPontos = sqrt(pow((location.x-rcvPackets->getX()),2)+pow((location.y-rcvPackets->getY()),2)); trace() << "VEL=" << mobilityModule->getSpeed(); if(mobilityModule->getSpeed() != 0.0 && mobilityModule->getSpeed() <= 100.0 && mobilityModule->getSpeed() >= 5.0){ trace() << "VEL=OK"; trace() << "FINAL_TIME: " << mobilityModule->getStartTime_Final(); if(simTime() > mobilityModule->getStartTime_Final()){ trace() << "DEAD_NODE=TRUE"; MobilityManagerMessage* pkt = new MobilityManagerMessage("teste", MOBILE_MESSAGE); //envio de uma msg interna para o MM pkt->setMobilePacketKind(NODE_DIE); toMobilityManager(pkt); }else{ trace() << "ALIVE_NODE=TRUE"; lucro=10;//Valor Qualquer, apenas pra passar da condição uf = (mobilityModule->getSpeed() + distanciaPontos + (rand() % 5)); xOrig = rcvPackets->getXOrig(); yOrig = rcvPackets->getYOrig(); idDst = rcvPackets->getDestino_final(); vOrig = rcvPackets->getVOrig(); if(lucro > 0){ trace() << "LUCRO=TRUE"; if(self == rcvPackets->getDestino_final()){ trace() << "DIST_FINAL=TRUE"; //Verificar a distância do nó destino, o nó não pode estar muito distante do nó que irá enviar. if((sqrt(pow((location.x-rcvPackets->getX()),2)+pow((location.y-rcvPackets->getY()),2))) <= 250.0){ trace() << "DIST=IN"; trace() << "WVL - 2° Etapa para coligação"; trace() << "WINGO_COLIGATE-O nó: " << self << " pode participar da coligação. Sua velocidade é: " << mobilityModule->getSpeed() << "."; trace() << "VELOCIDADE DO NÓ: " << mobilityModule->getSpeed(); trace() << "VELOCIDADE DA FONTE: " << rcvPackets->getSpeed(); SourceHead = rcvPackets->getSource(); WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); //Cria um pacote que será enviado para os demais nós beacon->setX(location.x); beacon->setY(location.y); beacon->setSource(self); beacon->setDestination(rcvPackets->getSource()); beacon->setSpeed(mobilityModule->getSpeed()); beacon->setUf(uf); beacon->setAppPacketKind(APP_CNNC); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS); //envio da msg externa em broadcast para os outros nos /*OraculoSrclocation = OraculoSrc->getLocation(); trace() << "INFORMAÇÕES DO ORACULO"; trace() << OraculoSrc->getId(); trace() << OraculoSrclocation.x; trace() << OraculoSrclocation.y; trace() << OraculoSrc->getSpeed();*/ }else{ trace() << "DIST=OUT"; } }else{ trace() << "DIST_FINAL=FALSE"; if((sqrt(pow((location.x-rcvPackets->getX()),2)+pow((location.y-rcvPackets->getY()),2))) <= 250.0){ trace() << "DIST=IN"; trace() << "WVL - 2° Etapa para coligação"; trace() << "WINGO_COLIGATE-O nó: " << self << " pode participar da coligação. Sua velocidade é: " << mobilityModule->getSpeed() << "."; trace() << "VELOCIDADE DO NÓ: " << mobilityModule->getSpeed(); trace() << "VELOCIDADE DA FONTE: " << rcvPackets->getSpeed(); SourceHead = rcvPackets->getSource(); WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); //Cria um pacote que será enviado para os demais nós beacon->setX(location.x); beacon->setY(location.y); beacon->setSource(self); beacon->setDestination(rcvPackets->getSource()); beacon->setSpeed(mobilityModule->getSpeed()); beacon->setUf(uf); beacon->setAppPacketKind(APP_CNNC); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS); //envio da msg externa em broadcast para os outros nos /*OraculoSrc = check_and_cast <VirtualMobilityManager*>(getParentModule()->getParentModule()->getParentModule()->getSubmodule("node",rcvPackets->getSrc_final())->getSubmodule("MobilityManager")); OraculoSrclocation = OraculoSrc->getLocation(); trace() << "INFORMAÇÕES DO ORACULO"; trace() << OraculoSrc->getId(); trace() << OraculoSrclocation.x; trace() << OraculoSrclocation.y; trace() << OraculoSrc->getSpeed();*/ }else{ trace() << "DIST=OUT"; } } }else{ trace() << "LUCRO=FALSE"; } } } }else{ trace() << "IN_GROUP=TRUE"; } }else{ trace() << "ZDI=OUT"; if(self == rcvPackets->getDestino_final()){ trace() << "Caso especial. Nó destino ficou para trás."; trace() << "Achamos o destino final."; SourceHead = rcvPackets->getSource(); uf = (mobilityModule->getSpeed() + distanciaPontos + (rand() % 5)); xOrig = rcvPackets->getXOrig(); yOrig = rcvPackets->getYOrig(); idDst = rcvPackets->getDestino_final(); vOrig = rcvPackets->getVOrig(); WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); //Cria um pacote que será enviado para os demais nós beacon->setX(location.x); beacon->setY(location.y); beacon->setSource(self); beacon->setDestination(rcvPackets->getSource()); beacon->setSpeed(mobilityModule->getSpeed()); beacon->setUf(uf); beacon->setAppPacketKind(APP_CNNC); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS); //envio da msg externa em broadcast para os outros nos } } trace() << "\n"; break; } case APP_CNNC:{ trace() << "Nó " << self << " recebeu CNNC do nó " << rcvPackets->getSource(); if(self == rcvPackets->getDestination()){ //Somente o nó que enviou o COLIGATE-NTFY poderá receber o COLIGATE-CRTY trace() << "WVL - 3° Etapa para coligação"; in_coligate = true; if(rcvPackets->getSpeed() != 0.0){ //Informações dos carros que responderam o NTFY auxMovementsCar.idCar = rcvPackets->getSource(); auxMovementsCar.xCar = rcvPackets->getX(); auxMovementsCar.yCar = rcvPackets->getY(); auxMovementsCar.vCar = rcvPackets->getSpeed(); auxMovementsCar.ufCar = rcvPackets->getUf(); carList.push_back(auxMovementsCar); }else{ trace() << "O nó: " << rcvPackets->getSource() << " não pode participar pois tem velocidade igual a 0."; } } break; } case APP_CRTY:{ if(self == rcvPackets->getDestination()){ //Somente o nó que enviou o COLIGATE-CNNC e foi escolhido poderá receber o COLIGATE-CRTY destino_final = rcvPackets->getDestino_final(); vOrig = rcvPackets->getSpeed_final(); idOrig = rcvPackets->getSrc_final(); trace() << "WVL - 4° Etapa para coligação"; trace() << "velocidade antiga: " << mobilityModule->getSpeed(); trace() << "Velocidade futura: " << rcvPackets->getSpeed_final(); MobilityManagerMessage* pkt = new MobilityManagerMessage("teste", MOBILE_MESSAGE); //envio de uma msg interna para o MM pkt->setMobilePacketKind(COLIGATE); pkt->setXCoorDestination(rcvPackets->getDestinationX()); pkt->setYCoorDestination(rcvPackets->getDestinationY()); pkt->setXSrc(rcvPackets->getX()); pkt->setYSrc(rcvPackets->getY()); pkt->setSpeed_final(rcvPackets->getSpeed_final()); //A velocidade final deve ser a menor toMobilityManager(pkt); in_coligate = true; if(destino_final != self){ trace() << "Novo lider platoon..."; headOn = true; carList.clear(); //Limpa a lista de carros, para escolher novos carros WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); beacon->setAppPacketKind(APP_LEADER); beacon->setSource(self); beacon->setSrc_head(SourceHead); beacon->setHead(true); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS);//envio da msg externa em broadcast para os outros nós trace() << "LIDER-Enviando mensagem de novo para todos...\n"; setTimer(GROUP, 0.1); }else{ trace() << "Chegou no destino."; WiseApplicationPacket *beacon = new WiseApplicationPacket("BEACON MSG TO GAME THEORY", APPLICATION_MESSAGE); beacon->setAppPacketKind(APP_LEADER); beacon->setSource(self); beacon->setSrc_head(SourceHead); beacon->setHead(true); toNetworkLayer(beacon, BROADCAST_NETWORK_ADDRESS);//envio da msg externa em broadcast para os outros nós trace() << "LIDER_DESTINO-Enviando mensagem de novo para todos...\n"; } } break; } case APP_LEADER:{ trace() << "Mensagem do Novo Lider " << rcvPackets->getSource() << " recebida. Antigo lider: " << rcvPackets->getSrc_head(); if(self == rcvPackets->getSrc_head()){ trace() << "Eu era o antigo lider"; headOn = rcvPackets->getHead(); if(headOn){ trace() << "Novo head: True\n"; }else{ trace() << "Novo head: False\n"; } } break; } } break; } case MULTIMEDIA_PACKET:{ WiseApplicationPacket *rcvPackets = check_and_cast<WiseApplicationPacket*>(msg); TraceInfo tParam = rcvPackets->getInfo(); //se o tamanho do fec_header for 0, singifica que eh um pacote no fec if(rcvPackets->getFecPktArraySize() == 0){ trace() << "APP- Node " << self << " received an " << rcvPackets->getInfo().frameType << "-frame with packet number " << rcvPackets->getInfo().idFrame << " from node " << rcvPackets->getInfo().nodeId << " for video id " << rcvPackets->getIdVideo() << " -- whithout FEC"; int indexPool = -1; for(int i =0; i<pktPool.size(); i++){ if(pktPool[i].nodeId == rcvPackets->getInfo().nodeId){ indexPool = i; break; } } if (indexPool != -1){ rebuildFECBlock(tParam.nodeId, tParam.seqNum, indexPool); for(int i =0; i<discardEidPkts.size(); i++){ if(discardEidPkts[i].nodeId == rcvPackets->getInfo().nodeId){ discardEidPkts[i].discard_eid_packets = 0; trace() << " discard_eid_packets " << discardEidPkts[i].discard_eid_packets; break; } } } // adicionar como pacote no fec AddReceivedTrace(SIMTIME_DBL(simTime()), true, tParam); WiseApplicationPacket *pktTrace = new WiseApplicationPacket("received video frame", APPLICATION_STATISTICS_MESSAGE); pktTrace->setIdVideo(tParam.seqNum); pktTrace->setIdNode(tParam.nodeId); pktTrace->setIdFrame(1); toNetworkLayer(pktTrace, BROADCAST_NETWORK_ADDRESS); trace() << "whithout FEC included => node id " << tParam.nodeId << " seq number " << tParam.seqNum << " frame id " << tParam.idFrame << "\n"; } else{ trace() << "APP- Node " << self << " received a frame number " << rcvPackets->getInfo().idFrame << " from node " << rcvPackets->getInfo().nodeId << " for video id " << rcvPackets->getIdVideo() << " -- whith FEC"; u_char* temp_packet = (u_char*)malloc(rcvPackets->getFecPktArraySize()); for(int i = 0; i < rcvPackets->getFecPktArraySize(); i++) temp_packet[i] = rcvPackets->getFecPkt(i); trace() << "packet data -- fec_header_size: " << rcvPackets->getFecPkt(0) << " k: " << rcvPackets->getFecPkt(1) << " n: " << rcvPackets->getFecPkt(2) << " i: " << rcvPackets->getFecPkt(3) << " evalvid id: " << rcvPackets->getFecPkt(4); int indexEidPkts = -1; for(int i =0; i<discardEidPkts.size(); i++){ if(discardEidPkts[i].nodeId == rcvPackets->getInfo().nodeId){ indexEidPkts = i; break; } } if(indexEidPkts == -1){ fec_parameters temp; temp.discard_eid_packets = 0; temp.nodeId = rcvPackets->getInfo().nodeId; discardEidPkts.push_back(temp); indexEidPkts = discardEidPkts.size() - 1; } int indexPool = -1; for(int i =0; i<pktPool.size(); i++){ if(pktPool[i].nodeId == rcvPackets->getInfo().nodeId){ indexPool = i; break; } } if (discardEidPkts[indexEidPkts].discard_eid_packets == 0 && indexPool == -1){ trace() << " significa que nao tenho nenhum bloco de fec na memoria para esse src, comecar um"; FillPacketPool(rcvPackets->getIdFrame(), rcvPackets->getByteLength()-temp_packet[0], temp_packet, rcvPackets->getInfo().nodeId); int indexPool = pktPool.size() - 1; trace() << " -- criando novo bloco para receber pacotes eid: " << pktPool[indexPool].eid << " k: " << pktPool[indexPool].k << " n: " << pktPool[indexPool].n << " nodeId: " << pktPool[indexPool].nodeId << " pktPool size " << pktPool.size(); trace() << "end"; } else if (discardEidPkts[indexEidPkts].discard_eid_packets == 0 && indexPool > -1){ // se for ==0 eh sinal que ainda nao antingiu o numero suficiente de pacotes // porem, preciso testar se ainda estou recebendo os pacotes com o mesmo EvalvidID // caso discard_eid_packets for > 0 ela retem o EID do ultimo bloco de fec recebido // possibilitando descartar caso sejam pacotes a mais ou comecar a montar o novo // bloco caso seja diferente int differentEID = -1; if (pktPool[indexPool].eid != temp_packet[4]) differentEID = indexPool; if(differentEID == -1){ trace() << " O bloco de fec que esta na memoria tenha o mesmo EID (" << pktPool[indexPool].eid << ") que o novo pacote"; memmove(pktPool[indexPool].payload[pktPool[indexPool].count], temp_packet+pktPool[indexPool].fhs, pktPool[indexPool].fds); pktPool[indexPool].idx[pktPool[indexPool].count] = (int) temp_packet[3]; //Ajustar os uid dos pacotes, pq senao posso ficar com id's diferentes no sd_file e rd_file // TODO: melhorar a explicacao da necessidade de ajuste do uid int adjusted_uid = (rcvPackets->getIdFrame()-(int)temp_packet[3])+pktPool[indexPool].count; pktPool[indexPool].packet_uid.push_back(adjusted_uid); pktPool[indexPool].count++; trace() << " packet pool data -- " << "fhs: " << pktPool[indexPool].fhs << " k: " << pktPool[indexPool].k << " n: " << pktPool[indexPool].n << " eid: " << pktPool[indexPool].eid << " count: " << pktPool[indexPool].count << " uid: " << adjusted_uid; trace() << "end"; } else if(differentEID != -1){ trace() << " ** Different Evalvid ID before packet pool clean, received eid: " << (int) temp_packet[4] << " packet pool eid: " << pktPool[indexPool].eid << " k: " << pktPool[indexPool].k << " n: " << pktPool[indexPool].n << " count: " << pktPool[indexPool].count << " nodeId: " << pktPool[indexPool].nodeId; rebuildFECBlock(tParam.nodeId, tParam.seqNum, differentEID); discardEidPkts[indexEidPkts].discard_eid_packets = 0; trace() << " discard_eid_packets " << discardEidPkts[indexEidPkts].discard_eid_packets; FillPacketPool(rcvPackets->getIdFrame(), rcvPackets->getByteLength()-temp_packet[0], temp_packet, rcvPackets->getInfo().nodeId); trace() << "end"; } } else if (discardEidPkts[indexEidPkts].discard_eid_packets != temp_packet[4]){ trace() << " recebi um numero suficiente de pacotes com FEC, descartar os mais com o mesmo EvalvidID"; discardEidPkts[indexEidPkts].discard_eid_packets = 0; trace() << " discard_eid_packets " << discardEidPkts[indexEidPkts].discard_eid_packets; FillPacketPool(rcvPackets->getIdFrame(), rcvPackets->getByteLength()-temp_packet[0], temp_packet, rcvPackets->getInfo().nodeId); trace() << "end"; } else{ trace() << " drop " << pktPool.size(); } int included = -1; for(int i =0; i<pktPool.size(); i++){ if(pktPool[i].nodeId == rcvPackets->getInfo().nodeId){ included = i; break; } } if (enoughPacketsReceived(included, indexEidPkts)){ trace() << " ++ criando novo bloco para receber pacotes (2) eid: " << pktPool[included].eid << " k: " << pktPool[included].k << " n: " << pktPool[included].n; discardEidPkts[indexEidPkts].discard_eid_packets = pktPool[included].eid; rebuildFECBlock(tParam.nodeId, tParam.seqNum, included); } free(temp_packet); } break; } case SCALAR_PACKET:{ WiseApplicationPacket *rcvPackets = check_and_cast<WiseApplicationPacket*>(msg); //trace() << "APP- Node " << self << " received a vibration report from node " << src << " with value " << rcvPackets->getSensedValue(); break; } } } /* * Create the output file and save it in a list */ void WingoApp::writeRdTrace(int id,int seqNum){ char fileTrace[50]; sprintf(fileTrace,"rd_sn_%i_nodeId_%i", seqNum,id); video temp; temp.ch = id; temp.sn = seqNum; temp.pFile = fopen(fileTrace, "a+"); set.push_back(temp); } void WingoApp::handleSensorReading(WiseSensorMessage* msg) { int msgKind = msg->getKind(); switch (msgKind) { case MULTIMEDIA:{ WiseApplicationPacket *pktTrace = new WiseApplicationPacket("SENDING MULTIMEDIA DATA", MULTIMEDIA_PACKET); pktTrace->setByteLength(msg->getByteLength()); pktTrace->setInfo(msg->getInfo()); pktTrace->setIdFrame(msg->getIdFrame()); pktTrace->setFrame(msg->getFrame()); pktTrace->setFecPktArraySize(msg->getFecPktArraySize()); for (int i = 0; i<msg->getFecPktArraySize(); i++) pktTrace->setFecPkt(i, msg->getFecPkt(i)); pktTrace->setIdVideo(msg->getInfo().seqNum); pktTrace->setX(location.x); pktTrace->setY(location.y); toNetworkLayer(pktTrace, BROADCAST_NETWORK_ADDRESS); //trace() << "Video id " << pktTrace->getIdVideo() << " frame id " << pktTrace->getFrame() << ", " << pktTrace->getInfo().frameType << "-frame " << pktTrace->getByteLength() << " bytes"; break; } } } void WingoApp::handleDirectApplicationMessage(WiseApplicationPacket* pkt) { //trace() << "direct app msg"; }
#include<iostream> #include<algorithm> using namespace std; int trans_pt(int arr[],int n) { int beg,end,mid; beg=0;end=n-1; while(beg<=end) { mid=(beg+end)/2; if(arr[mid]==1) { if(mid==0||arr[mid-1]==0&&mid>0) { return mid+1; } } else if(arr[mid]==0) { beg=mid+1; } else end=mid-1; } return -1; } int main() { int x,a[100]; cout<<"Enter length of array\n"; cin>>x; for(int i=0;i<x;i++) { cout<<"Enter element\n"; cin>>a[i]; cout<<endl; } sort(a,a+x); int q=trans_pt(a,x); if(q>=0) { cout<<"\nTransition Point found at "<<q<<" position\n"; } else cout<<"Transition point not found"; return 0; //time complexity is logn due to use of binary search }
// AV TODO: // 1. beatify console behavior if IO disconnected during typing /***C********************************************************************************************* ** ** SRC-FILE : cmd_proc.cpp ** ** PROJECT : BTCAR debug command user interface ** ** SRC-VERSION : ** ** DATE : ** ** AUTHOR : AV ** ** DESCRIPTION : Command line tool for BTCAR IO commands with autocomplete & history support. ** BTCAR IO commands are defines in BTCRA-DBG-CMD-LIB project. ** ** COPYRIGHT : ** ****C*E******************************************************************************************/ #include <windows.h> #include <wchar.h> #include <stdio.h> #include "cmd_line_wc.h" #include "cmd_lib.h" #include "dbg-ui.h" #include "dbg-ui_inp.h" // --- Internal function ------------------------------------------------------ // --- Globals ---------------------------------------------------------------- CMD_PROC_FLAGS gt_flags; int gn_action; #define CONSOLE_TITLE_LEN 128 WCHAR gca_console_title[CONSOLE_TITLE_LEN]; // ---------------------------------------------------------------------------- HANDLE gha_events[HANDLES_NUM]; HANDLE gh_io_pipe; OVERLAPPED gt_io_pipe_overlap = { 0 }; OVERLAPPED gt_io_pipe_rx_overlap = { 0 }; OVERLAPPED gt_io_pipe_tx_overlap = { 0 }; BYTE gba_io_pipe_rx_buff[IO_PIPE_RX_BUFF_LEN]; // ---------------------------------------------------------------------------- #define IO_PIPE_NAME_NUM 3 const WCHAR *gcaa_pipe_name_list[IO_PIPE_NAME_NUM] = { L"\\\\.\\pipe\\io_csr", L"\\\\.\\pipe\\io_avrb", L"\\\\.\\pipe\\io_avrf" }; const WCHAR *gpc_pipe_name = NULL; typedef struct t_io_ui_tag{ T_UI_CMD *pt_curr_cmd; }T_IO_UI; T_IO_UI gt_io_ui; #define MAX_IO_UI_CMD 100 T_UI_CMD gta_io_ui_cmd[MAX_IO_UI_CMD]; // AV TODO: Rework to dynamic allocation T_UI_CMD *gpt_io_ui_cmd = NULL; /***C*F****************************************************************************************** ** ** FUNCTION : get_command_line_args ** DATE : 01/20/2011 ** AUTHOR : AV ** ** DESCRIPTION : Parses command line argument ** ** PARAMETERS : ** ** RETURN-VALUE : ** ** NOTES : Not tested ** ***C*F*E***************************************************************************************************/ int get_command_line_args(int argc, WCHAR *argv[], int n_arg_num){ while(n_arg_num < argc){ if ( wcscmp(argv[n_arg_num], L"-h") == 0 || wcscmp(argv[n_arg_num], L"--help") == 0 ){ gn_action = SHOW_OPTIONS_HELP; break; } if ( wcscmp(argv[n_arg_num], L"-v") == 0 || wcscmp(argv[n_arg_num], L"--verbose") == 0 ){ n_arg_num++; gt_flags.verbose = FL_SET; continue; } if ( wcscmp(argv[n_arg_num], L"-c") == 0 || wcscmp(argv[n_arg_num], L"--command") == 0 ){ n_arg_num++; gn_action = SEND_COMMAND; continue; } if ( wcscmp(argv[n_arg_num], L"-no_io_start") == 0){ n_arg_num++; gt_flags.io_auto_start = FL_CLR; continue; } // If argument not regonized, then single command supposed break; } return n_arg_num; } void ui_cmd_field_dump (T_UI_CMD_FIELD* pt_cmd_fields) { T_UI_CMD_FIELD *pt_field = pt_cmd_fields; while (pt_field->pc_name) { if (pt_field->e_type == CFT_TXT) { wprintf(L" %-10s %d %d %s\n", pt_field->pc_name, pt_field->e_type, pt_field->n_len, pt_field->pc_str); } else if (pt_field->e_type == CFT_NUM) { wprintf(L" %-10s %d %d %d\n", pt_field->pc_name, pt_field->e_type, pt_field->n_len, pt_field->dw_val); } pt_field++; } return; } void ui_cmd_fields_free (T_UI_CMD_FIELD* pt_cmd_fields) { T_UI_CMD_FIELD *pt_field = pt_cmd_fields; while (pt_field->pc_name) { free(pt_field->pc_name); if (pt_field->e_type == CFT_TXT && pt_field->pc_str) { free(pt_field->pc_str); } pt_field++; } free(pt_cmd_fields); // AV TODO: rework to memfree() memset(gta_io_ui_cmd, 0, sizeof(gta_io_ui_cmd)); return; } void ui_cmd_dump (void) { T_UI_CMD *pt_cmd = &gta_io_ui_cmd[0]; while (pt_cmd->pc_name) { wprintf(L" %s\n", pt_cmd->pc_name); ui_cmd_field_dump(pt_cmd->pt_fields); pt_cmd++; } } void ui_cmds_free (void) { T_UI_CMD *pt_cmd = &gta_io_ui_cmd[0]; while (pt_cmd->pc_name) { ui_cmd_fields_free(pt_cmd->pt_fields); pt_cmd++; } } /***C*F****************************************************************************************** ** ** FUNCTION : ui_cmd_proc ** DATE : ** AUTHOR : AV ** ** DESCRIPTION : Check user input (parse command), write to DLE IO pipe if command OK ** ** PARAMETERS : ** ** RETURN-VALUE : returns TRUE if OK, FALSE otherwise ** ** NOTES : ** ***C*F*E***************************************************************************************************/ int ui_cmd_proc(WCHAR *pc_cmd_arg) { T_UI_CMD *pt_curr_cmd; WCHAR ca_cmd[CMD_LINE_LENGTH]; WCHAR *pc_cmd_token; // Make command local copy to use STRTOK wcscpy(ca_cmd, pc_cmd_arg); // Read command pc_cmd_token = wcstok(ca_cmd, L" "); if (!pc_cmd_token) return TRUE; pc_cmd_token = _wcsupr(pc_cmd_token); if (wcscmp(pc_cmd_token, L"QUIT") == 0 || wcscmp(pc_cmd_token, L"EXIT") == 0 || wcscmp(pc_cmd_token, L"Q") == 0 ) { gt_flags.exit = FL_SET; return FALSE; } if (wcscmp(pc_cmd_token, L"HELP") == 0) { show_cmd_help(gpt_io_ui_cmd); return TRUE; } // command processor starts here pt_curr_cmd = NULL; if (gpt_io_ui_cmd) { pt_curr_cmd = decomposite_cp_cmd(pc_cmd_arg, gpt_io_ui_cmd, FALSE); } if (pt_curr_cmd == NULL) { // Command not found or error in parameters return TRUE; } io_pipe_tx_str(pc_cmd_arg); return TRUE; } void ui_check (int *pn_prompt_restore) { // Try to initialize UI over IO pipe if not initialized yet. IO pipe must be connected if ((gt_flags.io_ui == FL_CLR || gt_flags.io_ui == FL_UNDEF) && gt_flags.io_conn != FL_SET) { // Do nothing if IO not connected } // UI init completed if (gt_flags.io_ui == FL_RISE) { wprintf(L"UI commands initialized\n"); SetConsoleTitle(gca_console_title); *pn_prompt_restore = TRUE; ui_cmd_dump(); gt_flags.io_ui = FL_SET; gpt_io_ui_cmd = gta_io_ui_cmd; } // Something goes wrong during UI init if (gt_flags.io_ui == FL_FALL) { wprintf(L"UI commands freed\n"); *pn_prompt_restore = TRUE; ui_cmds_free(); gt_flags.io_ui = FL_CLR; gpt_io_ui_cmd = NULL; } // Nothing to do. Everything is OK if (gt_flags.io_ui == FL_SET) { } } /***C*F****************************************************************************************** ** ** FUNCTION : io_pipe_rx_init ** ** AUTHOR : AV ** ** DESCRIPTION : Initiate IO asynchronous read ** ** PARAMETERS : ** ** RETURN-VALUE : returns TRUE if OK, FALSE otherwise ** ** NOTES : ** ***C*F*E***************************************************************************************************/ int io_pipe_rx_init (void){ int n_rc, n_gle; DWORD dw_n; n_rc = ReadFile( gh_io_pipe, //__in HANDLE hFile, gba_io_pipe_rx_buff, //__out LPVOID lpBuffer, IO_PIPE_RX_BUFF_LEN, //__in DWORD nNumberOfBytesToRead, &dw_n, //__out_opt LPDWORD lpNumberOfBytesRead, &gt_io_pipe_rx_overlap //__inout_opt LPOVERLAPPED lpOverlapped ); if(n_rc != 0) { return FALSE; } n_gle = GetLastError(); if (n_gle == ERROR_IO_PENDING) { gt_flags.io_conn = FL_SET; } else { gt_flags.io_conn = FL_FALL; } return TRUE; } int io_pipe_tx_str (WCHAR *p_io_msg) { int n_rc, n_gle; DWORD dw_n; // Send command n_rc = WriteFile( gh_io_pipe, //__in HANDLE hFile, p_io_msg, //__in LPCVOID lpBuffer, wcslen(p_io_msg)*2 + 2, //__in DWORD nNumberOfBytesToWrite, (+2 null termination) &dw_n, //__out_opt LPDWORD lpNumberOfBytesWritten, &gt_io_pipe_tx_overlap //__inout_opt LPOVERLAPPED lpOverlapped ); if (!n_rc){ n_gle = GetLastError(); if (n_gle != ERROR_IO_PENDING) { wprintf(L"Something wrong GLE=%d @ %d\n", n_rc, __LINE__); // AV TODO: restore prompt gt_flags.io_conn = FL_FALL; SetEvent(gha_events[HANDLE_IO_PIPE]); return FALSE; } } return TRUE; } T_UI_CMD_FIELD* io_pipe_rx_proc_ui_cmd_cdef (BYTE *pb_msg_buff_inp) { T_UI_IO_TLV t_tlv; DWORD dw_fld_cnt, dw_fld_cnt_ref; BYTE *pb_msg_buff = pb_msg_buff_inp; T_UI_CMD_FIELD *pt_cmd_fields, *pt_field; // Input buffer points to the begining of first FIELD TLV // Just count number of fields in TLV list to create fields array // Number of FLD_NAME TLVs is compared with reference in dedicated TLV. dw_fld_cnt = 0; dw_fld_cnt_ref = ~(0); pb_msg_buff = pb_msg_buff_inp; while (pb_msg_buff = get_tlv_tl(pb_msg_buff, &t_tlv)) { if (t_tlv.type == UI_IO_TLV_TYPE_CMD_FLD_CNT) { pb_msg_buff = get_tlv_v_dword(pb_msg_buff, &t_tlv); dw_fld_cnt_ref = t_tlv.val_dword; continue; } if (t_tlv.type == UI_IO_TLV_TYPE_FLD_NAME) { dw_fld_cnt++; } pb_msg_buff += t_tlv.len; } if (dw_fld_cnt != dw_fld_cnt_ref) { wprintf(L"Att: Something wrong @ $d - 0x%08X != 0x%08X", dw_fld_cnt, dw_fld_cnt_ref); return NULL; } // Allocate Fields array pt_cmd_fields = (T_UI_CMD_FIELD*)malloc((dw_fld_cnt + 1) * sizeof(T_UI_CMD_FIELD)); // +1 for NULL terminated array memset(pt_cmd_fields, 0, (dw_fld_cnt + 1) * sizeof(T_UI_CMD_FIELD)); // Fill up fields' data pt_field = NULL; pb_msg_buff = pb_msg_buff_inp; while (pb_msg_buff = get_tlv_tl(pb_msg_buff, &t_tlv)) { switch (t_tlv.type) { case UI_IO_TLV_TYPE_FLD_NAME: // Init or advance field pointer if (pt_field) pt_field++; else pt_field = &pt_cmd_fields[0]; pb_msg_buff = get_tlv_v_str(pb_msg_buff, &t_tlv); pt_field->pc_name = t_tlv.val_str; pt_field->n_len = -1; break; case UI_IO_TLV_TYPE_FLD_TYPE: pb_msg_buff = get_tlv_v_dword(pb_msg_buff, &t_tlv); pt_field->e_type = (E_CMD_FIELD_TYPE)t_tlv.val_dword; break; case UI_IO_TLV_TYPE_FLD_LEN: pb_msg_buff = get_tlv_v_dword(pb_msg_buff, &t_tlv); pt_field->n_len = t_tlv.val_dword; break; case UI_IO_TLV_TYPE_FLD_VAL: if (pt_field->e_type == CFT_NUM) { pb_msg_buff = get_tlv_v_dword(pb_msg_buff, &t_tlv); pt_field->dw_val = t_tlv.val_dword; } else // Assume: if (pt_field->e_type == CFT_TXT) { pb_msg_buff = get_tlv_v_str_n(pb_msg_buff, &t_tlv, pt_field->n_len); pt_field->pc_str = t_tlv.val_str; } break; default: // Not interesting TLV - just skip pb_msg_buff += t_tlv.len; } // Sanity checks if (!pb_msg_buff) { // Something bad happens ui_cmd_fields_free(pt_cmd_fields); return NULL; } } // End of FLD TLV loop // ui_cmd_field_dump(pt_cmd_fields); // AV TODO: temporary printout return pt_cmd_fields; } int io_pipe_rx_proc_ui_cmd (BYTE *pc_ui_init_msg, E_IO_UI_UI_CMD e_ui_cmd) { T_UI_IO_TLV t_tlv; BYTE *pb_msg_buff = pc_ui_init_msg; pb_msg_buff = get_tlv_tl(pb_msg_buff, &t_tlv); if (e_ui_cmd == IO_UI_UI_CMD_START) { // UI init START // Get & Parse welcome message wcscpy_s(gca_console_title, CONSOLE_TITLE_LEN, (WCHAR*)pb_msg_buff); // Init pointer for UI command definitions gt_io_ui.pt_curr_cmd = &gta_io_ui_cmd[0]; io_pipe_tx_str(L"ACK"); } else if (e_ui_cmd == IO_UI_UI_CMD_CDEF) { // UI init - Add command definition to cmd list pb_msg_buff = get_tlv_v_str(pb_msg_buff, &t_tlv); gt_io_ui.pt_curr_cmd->pc_name = t_tlv.val_str; gt_io_ui.pt_curr_cmd->pt_fields = io_pipe_rx_proc_ui_cmd_cdef(pb_msg_buff); gt_io_ui.pt_curr_cmd++; io_pipe_tx_str(L"ACK"); } else if (e_ui_cmd == IO_UI_UI_CMD_END) { // UI init END io_pipe_tx_str(L"READY"); gt_flags.io_ui = FL_RISE; } return TRUE; } /***C*F****************************************************************************************** ** ** FUNCTION : io_pipe_rx_proc ** DATE : ** AUTHOR : AV ** ** DESCRIPTION : Receives IO incoming messages and proceed depends on current mode ** ** PARAMETERS : ** ** RETURN-VALUE : returns TRUE if OK, FALSE otherwise ** ** NOTES : ** ***C*F*E***************************************************************************************************/ int io_pipe_rx_proc (int *pn_prompt_restore) { int n_rc, n_gle; DWORD dw_bytes_received; n_rc = GetOverlappedResult( gh_io_pipe, //__in HANDLE hFile, &gt_io_pipe_rx_overlap, //__in LPOVERLAPPED lpOverlapped, &dw_bytes_received, //__out LPDWORD lpNumberOfBytesTransferred, FALSE //__in BOOL bWait ); if (n_rc) { n_rc = io_pipe_rx_init(); if(!n_rc) return n_rc; } else { n_gle = GetLastError(); if (n_gle != ERROR_IO_INCOMPLETE){ gt_flags.io_conn = FL_FALL; SetEvent(gha_events[HANDLE_IO_PIPE]); wprintf(L"\nError reading IO pipe\n"); *pn_prompt_restore = TRUE; return TRUE; } } { // Determine msg type - UI_INIT, CMD_RESP, ... T_UI_IO_TLV t_tlv; BYTE *pb_msg_buff = (BYTE*)gba_io_pipe_rx_buff; pb_msg_buff = get_tlv_tl(pb_msg_buff, &t_tlv); if (t_tlv.type == UI_IO_TLV_TYPE_UI_CMD) { pb_msg_buff = get_tlv_v_dword(pb_msg_buff, &t_tlv); io_pipe_rx_proc_ui_cmd(pb_msg_buff, (E_IO_UI_UI_CMD)t_tlv.val_dword); } else if (t_tlv.type == UI_IO_TLV_TYPE_CMD_RSP) { // io_pipe_rx_proc_cmd_rsp() wprintf(L"\n%s\n", (WCHAR*)pb_msg_buff); pb_msg_buff += t_tlv.len; *pn_prompt_restore = TRUE; } else { // Something received while not expected!! wprintf(L"\nUnexpected message from IO - %s \n", gba_io_pipe_rx_buff); *pn_prompt_restore = TRUE; } } return TRUE; } /***C*F****************************************************************************************** ** ** FUNCTION : io_pipe_connect ** DATE : ** AUTHOR : AV ** ** DESCRIPTION : IO pipe state machine. Automatically connect/disconects from IO pipe ** ** PARAMETERS : ** ** RETURN-VALUE : returns TRUE if OK, FALSE otherwise ** ** NOTES : ** ***C*F*E***************************************************************************************************/ int io_pipe_connect (void) { int n_rc, n_gle; DWORD dwMode; // If pipe not selected yet, choose one from the list // Trying to connect to known named Pipes for (int n_i = 0; n_i < IO_PIPE_NAME_NUM; n_i ++) { const WCHAR *pc_try_pipe_name; pc_try_pipe_name = (gpc_pipe_name)? gpc_pipe_name : gcaa_pipe_name_list[n_i]; // Try to connect to existing IO pipe gh_io_pipe = CreateFile( pc_try_pipe_name, // pipe name GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES, // read and write access 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe FILE_FLAG_OVERLAPPED, //attributes NULL); // no template file if (gh_io_pipe != INVALID_HANDLE_VALUE) { gpc_pipe_name = pc_try_pipe_name; } // Once Pipe name selected - stick on it if (gpc_pipe_name) { break; } } if (gh_io_pipe == INVALID_HANDLE_VALUE) { n_gle = GetLastError(); n_rc = 0; goto io_pipe_connect_cleanup; } // The pipe connected; change to message-read mode. dwMode = PIPE_READMODE_MESSAGE; n_rc = SetNamedPipeHandleState( gh_io_pipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time if (!n_rc) { // Critical error! terminate application wprintf(L"SetNamedPipeHandleState failed. GLE=%d\n", GetLastError()); gt_flags.exit = FL_SET; // Critical error. Terminate application return FALSE; } io_pipe_connect_cleanup: // Log activity only if IO pipe connection status changed if (n_rc) { if (gt_flags.io_conn != FL_SET) { gt_flags.io_conn = FL_RISE; SetEvent(gha_events[HANDLE_IO_PIPE]); } } else { if (gt_flags.io_conn != FL_CLR) { gt_flags.io_conn = FL_FALL; SetEvent(gha_events[HANDLE_IO_PIPE]); } } return TRUE; } int io_pipe_check (int *pn_prompt_restore) { int n_rc, n_gle; // Try to connect to IO pipe periodically if not connected yet if (gt_flags.io_conn == FL_CLR) { n_rc = io_pipe_connect(); if (!n_rc) { n_gle = GetLastError(); wprintf(L"Can't open IO pipe %s. Error %d @ %d", gpc_pipe_name, n_gle, __LINE__); *pn_prompt_restore = TRUE; return FALSE; // Critical error } } // IO pipe just connected if (gt_flags.io_conn == FL_RISE) { // IO pipe connected. Try to initiate very first read transaction n_rc = io_pipe_rx_init(); if (n_rc) { wprintf(L"IO pipe %s connected. Sending INIT request...\n", gpc_pipe_name); *pn_prompt_restore = TRUE; gt_flags.io_conn = FL_SET; swprintf(gca_console_title, CONSOLE_TITLE_LEN, L"%s - Connected.", gpc_pipe_name); SetConsoleTitle(gca_console_title); // Send request for UI initialization io_pipe_tx_str(L"INIT"); } else { n_gle = GetLastError(); wprintf(L"Can't read from IO pipe. Error %d @ %d", gpc_pipe_name, n_gle, __LINE__); gt_flags.io_conn = FL_FALL; } } // Somethign wrong with IO pipe if (gt_flags.io_conn == FL_FALL) { wprintf(L"IO pipe disconnected\n"); *pn_prompt_restore = TRUE; gt_flags.io_conn = FL_CLR; CloseHandle(gh_io_pipe); swprintf(gca_console_title, CONSOLE_TITLE_LEN, L"%s - Disconnected.", gpc_pipe_name); SetConsoleTitle(gca_console_title); // Reset IO_UI gt_flags.io_ui = FL_FALL; } if (gt_flags.io_conn == FL_SET) { HANDLE h_temp; // Try to connect to IO pipe again. Just ot check it is alive. // If everything is OK, CreateFiles have to return ERROR_PIPE_BUSY h_temp = CreateFile( gpc_pipe_name, // pipe name GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES, // read and write access 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe FILE_FLAG_OVERLAPPED, // attributes NULL); // no template file if (h_temp == INVALID_HANDLE_VALUE) { n_gle = GetLastError(); if (n_gle == ERROR_PIPE_BUSY) { return TRUE; } } gt_flags.io_conn = FL_FALL; } return TRUE; } /***C*F****************************************************************************************** ** ** FUNCTION : CtrlHandler ** DATE : 01/20/2011 ** AUTHOR : AV ** ** DESCRIPTION : Program termination hook ** ** PARAMETERS : ** ** RETURN-VALUE : ** ** NOTES : ** ***C*F*E***************************************************************************************************/ BOOL CtrlHandler( DWORD fdwCtrlType ){ wprintf(L"\nUse 'quit' or just 'q' to save command history"); wprintf(L"\nHave a nice day!\n"); return FALSE; } /***C*F****************************************************************************************** ** ** FUNCTION : wmain ** DATE : ** AUTHOR : AV ** ** DESCRIPTION : ** ** PARAMETERS : ** ** RETURN-VALUE : ** ** NOTES : ** ***C*F*E***************************************************************************************************/ void wmain(int argc, WCHAR *argv[]){ int n_arg_num; WCHAR *pc_cmd; int n_rc, n_evt; int n_prompt_restore; void *pv_cmd_proc_info; // Default options gn_action = CMD_LINE_MODE; gt_flags.io_auto_start = FL_CLR; gt_flags.io_conn = FL_CLR; gt_flags.io_ui = FL_CLR; gt_flags.exit = FL_CLR; n_arg_num = get_command_line_args(argc, argv, 1); if (gn_action == SHOW_OPTIONS_HELP){ show_options_help(); return; } // Creat pipe IO connection event gha_events[HANDLE_IO_PIPE] = CreateEvent( NULL, // default security attribute FALSE, // manual-reset event FALSE, // initial state NULL); // unnamed event object // Creat command RX event gha_events[HANDLE_IO_PIPE_RX] = CreateEvent( NULL, // default security attribute FALSE, // manual-reset event FALSE, // initial state NULL); // unnamed event object gha_events[HANDLE_KEYBOARD] = GetStdHandle(STD_INPUT_HANDLE); gt_io_pipe_overlap.hEvent = gha_events[HANDLE_IO_PIPE]; gt_io_pipe_rx_overlap.hEvent = gha_events[HANDLE_IO_PIPE_RX]; swprintf(gca_console_title, CONSOLE_TITLE_LEN, L"Not connected"); SetConsoleTitle(gca_console_title); wprintf(L" \n"); wprintf(L" ----------------------\n"); wprintf(L" --- DBG UI console ---\n"); wprintf(L" ----------------------\n"); wprintf(L" \n"); // Catch console control events SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ); // Init command input processor // AV TODO: create cmd_history by pipe server name pv_cmd_proc_info = init_cmd_proc(L"cmd_hist.dat"); if (pv_cmd_proc_info == NULL) return; // Show initial prompt n_prompt_restore = TRUE; // Initial "magic punch" for IO connection SetEvent(gha_events[HANDLE_IO_PIPE]); // -------------------------- // --- Main wait loop // -------------------------- while(gt_flags.exit != FL_SET) { n_evt = WaitForMultipleObjects( HANDLES_NUM, // __in DWORD nCount, gha_events, // __in const HANDLE *lpHandles, FALSE, // __in BOOL bWaitAll, 100 // __in DWORD dwMilliseconds ); if (n_evt == WAIT_TIMEOUT) { // If nothing to do and IO is disconnected, then try to connect again if (gt_flags.io_conn == FL_CLR) { n_rc = io_pipe_check(&n_prompt_restore); if (!n_rc) return; } // Check other background task // ... ui_check(&n_prompt_restore); } else if (n_evt == WAIT_OBJECT_0 + HANDLE_IO_PIPE) { n_rc = io_pipe_check(&n_prompt_restore); if (!n_rc) return; } else if (n_evt == WAIT_OBJECT_0 + HANDLE_IO_PIPE_RX) { n_rc = io_pipe_rx_proc(&n_prompt_restore); if (!n_rc) return; } else if (n_evt == WAIT_OBJECT_0 + HANDLE_KEYBOARD) { pc_cmd = cmd_keys_pressed(pv_cmd_proc_info, &n_prompt_restore, gpt_io_ui_cmd); if (pc_cmd) { n_rc = ui_cmd_proc(pc_cmd); if (!n_rc) break; } } else { wprintf(L"?\n"); } if (n_prompt_restore) { cmd_proc_prompt(pv_cmd_proc_info); n_prompt_restore = FALSE; } } // End of While forever close_cmd_proc(pv_cmd_proc_info); return; } #if 0 int start_io(){ if (gt_flags.io_auto_start == FL_SET) { // Start IO process and pass outgoing pipe as STDIN WCHAR ca_cmd_line[1024]; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; BOOL bSuccess = FALSE; // Set up members of the PROCESS_INFORMATION structure. ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) ); // Set up members of the STARTUPINFO structure. // This structure specifies the STDIN and STDOUT handles for redirection. ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) ); siStartInfo.cb = sizeof(STARTUPINFO); wsprintf(ca_cmd_line, L"btcar-dbg-io-proc.exe %s", gpc_pipe_name); // Create the child process. bSuccess = CreateProcess( NULL, ca_cmd_line, // command line NULL, // process security attributes NULL, // primary thread security attributes FALSE, // handles are inherited CREATE_NEW_CONSOLE, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION // If an error occurs, exit the application. if ( !bSuccess ){ wprintf(L"Can't create IO process. Error @ %d", __LINE__); return FALSE; } } return TRUE; } #endif
#pragma once #define MEM_SIZE 256*4 class Mem { public: Mem(); ~Mem(); void InitMem(); int ReadMem(int index); std::wstring PrintMem(int page); private: static int m_memory[]; };
#ifndef IFACTORY_H #define IFACTORY_H #include <iostream> #include <map> #include "iproductregister.h" /* * 工厂模板类,用于获取和注册产品对象 * 模板参数 ProductType_t 表示的类是产品抽象类 */ template <class ProductType_t> class IFactory { public: // 获取工厂单例,工厂的实例是唯一的 static IFactory<ProductType_t> &getInstance() { static IFactory<ProductType_t> instance; return instance; } // 产品注册 void RegisterProduct(IProductRegister<ProductType_t> *pRegister, std::string strName) { m_ProductRegistry[strName] = pRegister; } // 根据产品名字,获取具体产品对象 ProductType_t *getProduct(std::string name) { // 从map中找到已经注册过的产品,并返回产品对象 if(m_ProductRegistry.find(name) != m_ProductRegistry.end()) return m_ProductRegistry[name]->createProduct(); // important // 未注册的产品,则提示找不到 std::cout << "this product isn't exist " << name << std::endl; return nullptr; } private: IFactory(){} ~IFactory(){} // 禁止外部拷贝跟赋值操作 IFactory(const IFactory &); const IFactory &operator=(const IFactory&); // 保存注册过的产品: key: 产品名字 value: 产品类型 std::map<std::string, IProductRegister<ProductType_t>*> m_ProductRegistry; }; #endif // IFACTORY_H
#include<iostream> using namespace std; //Khai bao struct Ngay { int Ngay; int Thang; int Nam; }; typedef struct Ngay NGAY; void Input_Ngay(NGAY &); void Out_Ngay(NGAY);
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #include "lipsync_dummy_input_mio.h" #include "pv_mime_string_utils.h" #include "oscl_file_server.h" #include "oscl_file_io.h" const uint32 KNumMsgBeforeFlowControl = 25; const uint32 Num_Audio_Bytes = 20; const uint32 KAudioMicroSecsPerDataEvent = 20000; const uint32 KVideoMicroSecsPerDataEvent = 100000; const uint32 TOTAL_BYTES_READ = 50; const uint32 One_Yuv_Frame_Size = 38016; #define InputFileName "test.yuv" #define DUMMY_MEDIADATA_POOLNUM 11 #define VOP_START_BYTE_1 0x00 #define VOP_START_BYTE_2 0x00 #define VOP_START_BYTE_3 0x01 #define VOP_START_BYTE_4 0xB6 #define GOV_START_BYTE_4 0xB3 #define H263_START_BYTE_1 0x00 #define H263_START_BYTE_2 0x00 #define H263_START_BYTE_3 0x80 #define BYTES_FOR_MEMPOOL_STORAGE 38100 #define BYTE_1 1 #define BYTE_2 2 #define BYTE_3 3 #define BYTE_4 4 #define BYTE_8 8 #define BYTE_16 16 // Logging macros #define LOG_STACK_TRACE(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, m) #define LOG_DEBUG(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, m) #define LOG_ERR(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_REL,iLogger,PVLOGMSG_ERR,m) uint32 g_iAudioTimeStamp = 0; uint32 g_iVideoTimeStamp = 0; uint32 g_count = 0; int32 g_DiffVidAudTS = 0; int32 g_SqrVidAudTS = 0; int32 g_RtMnSq = 0; LipSyncDummyInputMIO::LipSyncDummyInputMIO(const LipSyncDummyMIOSettings& aSettings) : OsclTimerObject(OsclActiveObject::EPriorityNominal, (aSettings.iMediaFormat.isAudio() ? "DummyAudioInputMIO" : "DummyVideoInputMIO")) , iCmdIdCounter(0) , iMediaBufferMemPool(NULL) , iAudioMIO(aSettings.iMediaFormat.isAudio()) , iVideoMIO(aSettings.iMediaFormat.isVideo()) , iState(STATE_IDLE) , iThreadLoggedOn(false) , iSeqNumCounter(0) , iTimestamp(0) , iFormat(aSettings.iMediaFormat) , iCompressed(iFormat.isCompressed()) , iMicroSecondsPerDataEvent(0) , iSettings(aSettings) , iVideoMicroSecondsPerDataEvent(0) , iAudioMicroSecondsPerDataEvent(0) { iParams = NULL; iAudioOnlyOnce = false; iVideoOnlyOnce = false; } PVMFStatus LipSyncDummyInputMIO::connect(PvmiMIOSession& aSession, PvmiMIOObserver* aObserver) { if (!aObserver) { return PVMFFailure; } int32 err = 0; OSCL_TRY(err, iObservers.push_back(aObserver)); OSCL_FIRST_CATCH_ANY(err, return PVMFErrNoMemory); aSession = (PvmiMIOSession)(iObservers.size() - 1); // Session ID is the index of observer in the vector return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::disconnect(PvmiMIOSession aSession) { uint32 index = (uint32)aSession; if (index >= iObservers.size()) { // Invalid session ID return PVMFFailure; } iObservers.erase(iObservers.begin() + index); return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PvmiMediaTransfer* LipSyncDummyInputMIO::createMediaTransfer(PvmiMIOSession& aSession, PvmiKvp* read_formats, int32 read_flags, PvmiKvp* write_formats, int32 write_flags) { OSCL_UNUSED_ARG(read_formats); OSCL_UNUSED_ARG(read_flags); OSCL_UNUSED_ARG(write_formats); OSCL_UNUSED_ARG(write_flags); uint32 index = (uint32)aSession; if (index >= iObservers.size()) { // Invalid session ID OSCL_LEAVE(OsclErrArgument); return NULL; } return (PvmiMediaTransfer*)this; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::deleteMediaTransfer(PvmiMIOSession& aSession, PvmiMediaTransfer* media_transfer) { uint32 index = (uint32)aSession; if (!media_transfer || index >= iObservers.size()) { // Invalid session ID OSCL_LEAVE(OsclErrArgument); } } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::QueryUUID(const PvmfMimeString& aMimeType, Oscl_Vector<PVUuid, OsclMemAllocator>& aUuids, bool aExactUuidsOnly, const OsclAny* aContext) { OSCL_UNUSED_ARG(aMimeType); OSCL_UNUSED_ARG(aExactUuidsOnly); int32 err = 0; OSCL_TRY(err, aUuids.push_back(PVMI_CAPABILITY_AND_CONFIG_PVUUID);); OSCL_FIRST_CATCH_ANY(err, OSCL_LEAVE(OsclErrNoMemory);); return AddCmdToQueue(QUERY_UUID, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::QueryInterface(const PVUuid& aUuid, PVInterface*& aInterfacePtr, const OsclAny* aContext) { if (aUuid == PVMI_CAPABILITY_AND_CONFIG_PVUUID) { PvmiCapabilityAndConfig* myInterface = OSCL_STATIC_CAST(PvmiCapabilityAndConfig*, this); aInterfacePtr = OSCL_STATIC_CAST(PVInterface*, myInterface); } else { aInterfacePtr = NULL; } return AddCmdToQueue(QUERY_INTERFACE, aContext, (OsclAny*)&aInterfacePtr); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::Init(const OsclAny* aContext) { if ((iState != STATE_IDLE) && (iState != STATE_INITIALIZED)) { OSCL_LEAVE(OsclErrInvalidState); return -1; } return AddCmdToQueue(INIT, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::Start(const OsclAny* aContext) { if (iState != STATE_INITIALIZED && iState != STATE_PAUSED && iState != STATE_STARTED) { OSCL_LEAVE(OsclErrInvalidState); return -1; } return AddCmdToQueue(START, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::Pause(const OsclAny* aContext) { if (iState != STATE_STARTED && iState != STATE_PAUSED) { OSCL_LEAVE(OsclErrInvalidState); return -1; } return AddCmdToQueue(PAUSE, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::Flush(const OsclAny* aContext) { if (iState != STATE_STARTED || iState != STATE_PAUSED) { OSCL_LEAVE(OsclErrInvalidState); return -1; } return AddCmdToQueue(FLUSH, aContext); } PVMFCommandId LipSyncDummyInputMIO::Reset(const OsclAny* aContext) { return AddCmdToQueue(RESET, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::DiscardData(PVMFTimestamp aTimestamp, const OsclAny* aContext) { OSCL_UNUSED_ARG(aContext); OSCL_UNUSED_ARG(aTimestamp); OSCL_LEAVE(OsclErrNotSupported); return -1; } PVMFCommandId LipSyncDummyInputMIO::DiscardData(const OsclAny* aContext) { OSCL_UNUSED_ARG(aContext); OSCL_LEAVE(OsclErrNotSupported); return -1; } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::Stop(const OsclAny* aContext) { if (iState != STATE_STARTED && iState != STATE_PAUSED && iState != STATE_STOPPED) { OSCL_LEAVE(OsclErrInvalidState); return -1; } return AddCmdToQueue(STOP, aContext); } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::AddCmdToQueue(LipSyncDummyInputMIOCmdType aType, const OsclAny* aContext, OsclAny* aData1) { if (aType == CMD_DATA_EVENT) OSCL_LEAVE(OsclErrArgument); LipSyncDummyInputMIOCmd cmd; cmd.iType = aType; cmd.iContext = OSCL_STATIC_CAST(OsclAny*, aContext); cmd.iData1 = aData1; cmd.iId = iCmdIdCounter; ++iCmdIdCounter; iCmdQueue.push_back(cmd); RunIfNotReady(); return cmd.iId; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::AddDataEventToQueue(uint32 aMicroSecondsToEvent) { LipSyncDummyInputMIOCmd cmd; cmd.iType = CMD_DATA_EVENT; iCmdQueue.push_back(cmd); RunIfNotReady(aMicroSecondsToEvent); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::DoRequestCompleted(const LipSyncDummyInputMIOCmd& aCmd, PVMFStatus aStatus, OsclAny* aEventData) { PVMFCmdResp response(aCmd.iId, aCmd.iContext, aStatus, aEventData); for (uint32 i = 0; i < iObservers.size(); i++) iObservers[i]->RequestCompleted(response); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::ThreadLogon() { if (!iThreadLoggedOn) { AddToScheduler(); iLogger = PVLogger::GetLoggerObject("LipSyncDummyInputMIO"); iThreadLoggedOn = true; } } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::ThreadLogoff() { if (iThreadLoggedOn) { RemoveFromScheduler(); iLogger = NULL; } } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::CancelAllCommands(const OsclAny* aContext) { OSCL_UNUSED_ARG(aContext); OSCL_LEAVE(OsclErrNotSupported); return -1; } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::CancelCommand(PVMFCommandId aCmdId, const OsclAny* aContext) { OSCL_UNUSED_ARG(aCmdId); OSCL_UNUSED_ARG(aContext); OSCL_LEAVE(OsclErrNotSupported); return -1; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::setPeer(PvmiMediaTransfer* aPeer) { iPeer = aPeer; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::useMemoryAllocators(OsclMemAllocator* write_alloc) { OSCL_UNUSED_ARG(write_alloc); OSCL_LEAVE(OsclErrNotSupported); } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::DoInit() { if (STATE_INITIALIZED == iState) { return PVMFSuccess; } // Create memory pool for the media data, using the maximum frame size found earlier int32 err = 0; OSCL_TRY(err, if (iMediaBufferMemPool) { OSCL_DELETE(iMediaBufferMemPool); iMediaBufferMemPool = NULL; } iMediaBufferMemPool = OSCL_NEW(OsclMemPoolFixedChunkAllocator, (DUMMY_MEDIADATA_POOLNUM, BYTES_FOR_MEMPOOL_STORAGE)); if (!iMediaBufferMemPool) OSCL_LEAVE(OsclErrNoMemory); ); OSCL_FIRST_CATCH_ANY(err, return PVMFErrNoMemory); // The first allocate call will set the chunk size of the memory pool. Use the max // frame size calculated earlier to set the chunk size. The allocated data will be // deallocated automatically as tmpPtr goes out of scope. OsclAny* tmpPtr = NULL; tmpPtr = iMediaBufferMemPool->allocate(BYTES_FOR_MEMPOOL_STORAGE); iMediaBufferMemPool->deallocate(tmpPtr); if (iAudioMIO) { iAudioMicroSecondsPerDataEvent = (int32)((1000 / iSettings.iAudioFrameRate)) * 1000; } else { iVideoMicroSecondsPerDataEvent = (int32)((1000 / iSettings.iVideoFrameRate)) * 1000; } iState = STATE_INITIALIZED; return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::DoStart() { if (STATE_STARTED == iState) { return PVMFSuccess; } iState = STATE_STARTED; RunIfNotReady(0); return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::DoPause() { iState = STATE_PAUSED; return PVMFSuccess; } PVMFStatus LipSyncDummyInputMIO::DoReset() { return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::DoFlush() { // This method should stop capturing media data but continue to send captured // media data that is already in buffer and then go to stopped state. // However, in this case of file input we do not have such a buffer for // captured data, so this behaves the same way as stop. return DoStop(); } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::DoStop() { iState = STATE_STOPPED; if (g_count == 0) { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "Can't calculate the value of RMS because the count value is zero. g_count=%d", g_count)); } else { g_RtMnSq = (int32)sqrt(g_SqrVidAudTS / g_count); PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "RMS value at input side . g_RtMnSq=%d", g_RtMnSq)); } return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::writeAsync(uint8 aFormatType, int32 aFormatIndex, uint8* aData, uint32 aDataLen, const PvmiMediaXferHeader& data_header_info, OsclAny* aContext) { OSCL_UNUSED_ARG(aFormatType); OSCL_UNUSED_ARG(aFormatIndex); OSCL_UNUSED_ARG(aData); OSCL_UNUSED_ARG(aDataLen); OSCL_UNUSED_ARG(data_header_info); OSCL_UNUSED_ARG(aContext); // This is an active data source. writeAsync is not supported. OSCL_LEAVE(OsclErrNotSupported); return -1; } LipSyncDummyInputMIO::~LipSyncDummyInputMIO() { if (iMediaBufferMemPool) { OSCL_DELETE(iMediaBufferMemPool); iMediaBufferMemPool = NULL; } // release semaphore } void LipSyncDummyInputMIO::Run() { if (!iCmdQueue.empty()) { LipSyncDummyInputMIOCmd cmd = iCmdQueue[0]; iCmdQueue.erase(iCmdQueue.begin()); switch (cmd.iType) { case INIT: DoRequestCompleted(cmd, DoInit()); break; case START: DoRequestCompleted(cmd, DoStart()); break; case PAUSE: DoRequestCompleted(cmd, DoPause()); break; case FLUSH: DoRequestCompleted(cmd, DoFlush()); break; case RESET: DoRequestCompleted(cmd, DoReset()); break; case STOP: DoRequestCompleted(cmd, DoStop()); break; case CMD_DATA_EVENT: DoRead(); break; case QUERY_UUID: case QUERY_INTERFACE: DoRequestCompleted(cmd, PVMFSuccess); break; case CANCEL_ALL_COMMANDS: case CANCEL_COMMAND: DoRequestCompleted(cmd, PVMFFailure); break; default: break; } } if (iPeer && iState == STATE_STARTED) { DoRead(); } if (!iCmdQueue.empty()) { // Run again if there are more things to process RunIfNotReady(); } } void LipSyncDummyInputMIO::writeComplete(PVMFStatus aStatus, PVMFCommandId write_id, OsclAny* aContext) { OSCL_UNUSED_ARG(aContext); if ((aStatus != PVMFSuccess) && (aStatus != PVMFErrCancelled)) { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "LipSyncDummyInputMIO::writeComplete: Error - writeAsync failed. aStatus=%d", aStatus)); OSCL_LEAVE(OsclErrGeneral); } for (int i = iSentMediaData.size() - 1; i >= 0; i--) { if (iSentMediaData[i].iId == write_id) { iMediaBufferMemPool->deallocate(iSentMediaData[i].iData); iSentMediaData.erase(&iSentMediaData[i]); return; } } // Error: unmatching ID. PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "LipSyncDummyInputMIO::writeComplete: Error - unmatched cmdId %d failed. QSize %d", write_id, iSentMediaData.size())); } PVMFStatus LipSyncDummyInputMIO::DoRead() { // Create new media data buffer int32 error = 0; uint8* data = NULL; uint32 writeAsyncID = 0; uint32 bytesToRead = 0; //Find the frame... if (iVideoMIO) { iParams = ShareParams::Instance(); data = (uint8*)iMediaBufferMemPool->allocate(BYTES_FOR_MEMPOOL_STORAGE); if ((iSettings.iMediaFormat == PVMF_MIME_M4V) || (iSettings.iMediaFormat == PVMF_MIME_ISO_AVC_SAMPLE_FORMAT)) { bytesToRead = TOTAL_BYTES_READ; iTimestamp = (int32)(iSeqNumCounter * 1000 / iSettings.iVideoFrameRate); ++iSeqNumCounter; } else if (iSettings.iMediaFormat == PVMF_MIME_H2631998 || iSettings.iMediaFormat == PVMF_MIME_H2632000) { if (error) { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "LipSyncDummyInputMIO::No buffer available for video MIO, wait till next data event")) RunIfNotReady(iVideoMicroSecondsPerDataEvent); return PVMFSuccess; } bytesToRead = TOTAL_BYTES_READ; iTimestamp += (uint32)(iSeqNumCounter * 1000 / iSettings.iVideoFrameRate); g_iVideoTimeStamp = iTimestamp; ++iSeqNumCounter; iParams->iCompressed = true; CalculateRMSInfo(g_iVideoTimeStamp, g_iAudioTimeStamp); } else if (iSettings.iMediaFormat == PVMF_MIME_YUV420 || iSettings.iMediaFormat == PVMF_MIME_RGB16) { if (error) { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PvmiMIOFileInput::No buffer available for Video MIO, wait till next data event")) RunIfNotReady(iVideoMicroSecondsPerDataEvent); return PVMFSuccess; } Oscl_FileServer fs; fs.Connect(); Oscl_File fileYUV; if (fileYUV.Open(InputFileName, Oscl_File::MODE_READ , fs)) { fs.Close(); PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PvmiMIOFileInput::Eror in reading the yuv file")) RunIfNotReady(); return PVMFFailure; } fileYUV.Read(data, One_Yuv_Frame_Size, sizeof(char)); fileYUV.Close(); fs.Close(); bytesToRead = One_Yuv_Frame_Size; iTimestamp = (int32)(iSeqNumCounter * 1000 / iSettings.iVideoFrameRate); g_iVideoTimeStamp = iTimestamp; ++iSeqNumCounter; iParams->iUncompressed = true; CalculateRMSInfo(g_iVideoTimeStamp, g_iAudioTimeStamp); } else { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PvmiMIOFileInput::HandleEventPortActivity: Error - Unsupported media format")); return PVMFFailure; } if (iCompressed) { AddMarkerInfo(data); } PvmiMediaXferHeader data_hdr; data_hdr.seq_num = iSeqNumCounter - 1; data_hdr.timestamp = iTimestamp; data_hdr.flags = 0; data_hdr.duration = 0; data_hdr.stream_id = 0; data_hdr.private_data_length = 0; if (!iPeer) { iMediaBufferMemPool->deallocate(data); PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "LipSyncDummyInputMIO::DoRead - Peer missing")); return PVMFSuccess; } writeAsyncID = iPeer->writeAsync(PVMI_MEDIAXFER_FMT_TYPE_DATA, 0, data, bytesToRead, data_hdr); if (!error) { // Save the id and data pointer on iSentMediaData queue for writeComplete call PvmiDummyMediaData sentData; sentData.iId = writeAsyncID; sentData.iData = data; iSentMediaData.push_back(sentData); LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::DoRead stats in writeAsync call ts is %d seqNum is %d, media type is %s", data_hdr.timestamp, data_hdr.seq_num, (iAudioMIO ? "Audio" : "Video"))); } else if (error == OsclErrBusy) { --iSeqNumCounter; PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "LipSyncDummyInputMIO::DoRead error occurred while writeAsync call, media_type is %s", (iAudioMIO ? "Audio" : "Video"))) iMediaBufferMemPool->deallocate(data); } else { iMediaBufferMemPool->deallocate(data); } } else if (iAudioMIO) { GenerateAudioFrame(data); if (iSettings.iMediaFormat == PVMF_MIME_AMR_IF2 || iSettings.iMediaFormat == PVMF_MIME_AMR_IETF || iSettings.iMediaFormat == PVMF_MIME_AMRWB_IETF || iSettings.iMediaFormat == PVMF_MIME_ADTS || iSettings.iMediaFormat == PVMF_MIME_ADIF || iSettings.iMediaFormat == PVMF_MIME_MP3) { if (error) { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PvmiMIOFileInput::No buffer available for audio MIO, wait till next data event")) RunIfNotReady(iAudioMicroSecondsPerDataEvent); return PVMFSuccess; } } else { PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PvmiMIOFileInput::HandleEventPortActivity: Error - Unsupported media format")); return PVMFFailure; } } uint32 aCurrentTime = 0; uint32 aInterval = 0; uint32 iTsmsec = 0; uint32 tick_ct_val = OsclTickCount::TickCount(); iTsmsec = OsclTickCount::TicksToMsec(tick_ct_val); aCurrentTime = iTsmsec * 1000; if (iAudioMIO) { ProcessAudioFrame(aCurrentTime, aInterval); } else { ProcessVideoFrame(aCurrentTime, aInterval); } return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::readAsync(uint8* data, uint32 max_data_len, OsclAny* aContext, int32* formats, uint16 num_formats) { OSCL_UNUSED_ARG(data); OSCL_UNUSED_ARG(max_data_len); OSCL_UNUSED_ARG(aContext); OSCL_UNUSED_ARG(formats); OSCL_UNUSED_ARG(num_formats); // This is an active data source. readAsync is not supported. OSCL_LEAVE(OsclErrNotSupported); return -1; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::readComplete(PVMFStatus aStatus, PVMFCommandId read_id, int32 format_index, const PvmiMediaXferHeader& data_header_info, OsclAny* aContext) { OSCL_UNUSED_ARG(aStatus); OSCL_UNUSED_ARG(read_id); OSCL_UNUSED_ARG(format_index); OSCL_UNUSED_ARG(data_header_info); OSCL_UNUSED_ARG(aContext); // This is an active data source. readComplete is not supported. OSCL_LEAVE(OsclErrNotSupported); return; } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::statusUpdate(uint32 status_flags) { if (status_flags == PVMI_MEDIAXFER_STATUS_WRITE) { if (iAudioMIO) { RunIfNotReady(iAudioMicroSecondsPerDataEvent); } else { RunIfNotReady(iVideoMicroSecondsPerDataEvent); } } else { // Ideally this routine should update the status of media input component. // It should check then for the status. If media input buffer is consumed, // media input object should be resheduled. // Since the Media fileinput component is designed with single buffer, two // asynchronous reads are not possible. So this function will not be required // and hence not been implemented. OSCL_LEAVE(OsclErrNotSupported); } } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::cancelCommand(PVMFCommandId aCmdId) { OSCL_UNUSED_ARG(aCmdId); // This cancel command ( with a small "c" in cancel ) is for the media transfer interface. // implementation is similar to the cancel command of the media I/O interface. OSCL_LEAVE(OsclErrNotSupported); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::cancelAllCommands() { OSCL_LEAVE(OsclErrNotSupported); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::setObserver(PvmiConfigAndCapabilityCmdObserver* aObserver) { OSCL_UNUSED_ARG(aObserver); } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::getParametersSync(PvmiMIOSession session, PvmiKeyType identifier, PvmiKvp*& parameters, int& num_parameter_elements, PvmiCapabilityContext context) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(context); parameters = NULL; num_parameter_elements = 0; PVMFStatus status = PVMFFailure; if (pv_mime_strcmp(identifier, OUTPUT_FORMATS_CAP_QUERY) == 0 || pv_mime_strcmp(identifier, OUTPUT_FORMATS_CUR_QUERY) == 0) { num_parameter_elements = 1; LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for OUTPUT_FORMATS_CAP_QUERY")); status = AllocateKvp(parameters, (PvmiKeyType)OUTPUT_FORMATS_VALTYPE, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); } else { parameters[0].value.pChar_value = OSCL_STATIC_CAST(char*, iFormat.getMIMEStrPtr()); } } else if (pv_mime_strcmp(identifier, VIDEO_OUTPUT_WIDTH_CUR_QUERY) == 0) { num_parameter_elements = 1; LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for VIDEO_OUTPUT_WIDTH_CUR_QUERY")); status = AllocateKvp(parameters, (PvmiKeyType)VIDEO_OUTPUT_WIDTH_CUR_VALUE, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } parameters[0].value.uint32_value = 176; } else if (pv_mime_strcmp(identifier, VIDEO_OUTPUT_HEIGHT_CUR_QUERY) == 0) { num_parameter_elements = 1; LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for VIDEO_OUTPUT_HEIGHT_CUR_QUERY")); status = AllocateKvp(parameters, (PvmiKeyType)VIDEO_OUTPUT_HEIGHT_CUR_VALUE, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } parameters[0].value.uint32_value = 144; } else if (pv_mime_strcmp(identifier, VIDEO_OUTPUT_FRAME_RATE_CUR_QUERY) == 0) { num_parameter_elements = 1; LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for VIDEO_OUTPUT_FRAME_RATE_CUR_QUERY")); status = AllocateKvp(parameters, (PvmiKeyType)VIDEO_OUTPUT_FRAME_RATE_CUR_VALUE, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } parameters[0].value.float_value = 15; } else if (pv_mime_strcmp(identifier, OUTPUT_TIMESCALE_CUR_QUERY) == 0) { LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for OUTPUT_TIMESCALE_CUR_QUERY")); num_parameter_elements = 1; status = AllocateKvp(parameters, (PvmiKeyType)OUTPUT_TIMESCALE_CUR_VALUE, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } else { if (iAudioMIO) { parameters[0].value.uint32_value = 8000; } else { parameters[0].value.uint32_value = 0; } } } else if (pv_mime_strcmp(identifier, PVMF_FORMAT_SPECIFIC_INFO_KEY) == 0) { status = PVMFFailure; } else if (pv_mime_strcmp(identifier, AUDIO_OUTPUT_SAMPLING_RATE_CUR_QUERY) == 0) { num_parameter_elements = 1; LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for AUDIO_OUTPUT_SAMPLING_RATE_CUR_QUERY")); status = AllocateKvp(parameters, (PvmiKeyType)AUDIO_OUTPUT_SAMPLING_RATE_CUR_QUERY, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "PvmiMIOFileInput::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } parameters[0].value.uint32_value = 8000; } else if (pv_mime_strcmp(identifier, AUDIO_OUTPUT_NUM_CHANNELS_CUR_QUERY) == 0) { LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::getParametersSync for AUDIO_OUTPUT_NUM_CHANNELS_CUR_QUERY")); num_parameter_elements = 1; status = AllocateKvp(parameters, (PvmiKeyType)AUDIO_OUTPUT_NUM_CHANNELS_CUR_QUERY, num_parameter_elements); if (status != PVMFSuccess) { LOG_ERR((0, "PvmiMIOFileInput::GetOutputParametersSync: Error - AllocateKvp failed. status=%d", status)); return status; } parameters[0].value.uint32_value = 2; } return status; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::AllocateKvp(PvmiKvp*& aKvp, PvmiKeyType aKey, int32 aNumParams) { LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::AllocateKvp")); uint8* buf = NULL; uint32 keyLen = oscl_strlen(aKey) + 1; int32 err = 0; OSCL_TRY(err, buf = (uint8*)iAlloc.allocate(aNumParams * (sizeof(PvmiKvp) + keyLen)); if (!buf) OSCL_LEAVE(OsclErrNoMemory); ); OSCL_FIRST_CATCH_ANY(err, LOG_ERR((0, "LipSyncDummyInputMIO::AllocateKvp: Error - kvp allocation failed")); return PVMFErrNoMemory; ); int32 i = 0; PvmiKvp* curKvp = aKvp = new(buf) PvmiKvp; buf += sizeof(PvmiKvp); for (i = 1; i < aNumParams; i++) { curKvp += i; curKvp = new(buf) PvmiKvp; buf += sizeof(PvmiKvp); } for (i = 0; i < aNumParams; i++) { aKvp[i].key = (char*)buf; oscl_strncpy(aKvp[i].key, aKey, keyLen); buf += keyLen; } return PVMFSuccess; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::VerifyAndSetParameter(PvmiKvp* aKvp, bool aSetParam) { OSCL_UNUSED_ARG(aSetParam); LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::VerifyAndSetParameter: aKvp=0x%x, aSetParam=%d", aKvp, aSetParam)); if (!aKvp) { LOG_ERR((0, "LipSyncDummyInputMIO::VerifyAndSetParameter: Error - Invalid key-value pair")); return PVMFFailure; } if (pv_mime_strcmp(aKvp->key, OUTPUT_FORMATS_VALTYPE) == 0) { return PVMFSuccess; } LOG_ERR((0, "LipSyncDummyInputMIO::VerifyAndSetParameter: Error - Unsupported parameter")); return PVMFFailure; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::releaseParameters(PvmiMIOSession session, PvmiKvp* parameters, int num_elements) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(num_elements); if (parameters) { iAlloc.deallocate((OsclAny*)parameters); return PVMFSuccess; } else { return PVMFFailure; } } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::createContext(PvmiMIOSession session, PvmiCapabilityContext& context) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(context); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::setContextParameters(PvmiMIOSession session, PvmiCapabilityContext& context, PvmiKvp* parameters, int num_parameter_elements) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(context); OSCL_UNUSED_ARG(parameters); OSCL_UNUSED_ARG(num_parameter_elements); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::DeleteContext(PvmiMIOSession session, PvmiCapabilityContext& context) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(context); } //////////////////////////////////////////////////////////////////////////// void LipSyncDummyInputMIO::setParametersSync(PvmiMIOSession session, PvmiKvp* parameters, int num_elements, PvmiKvp*& ret_kvp) { OSCL_UNUSED_ARG(session); PVMFStatus status = PVMFSuccess; ret_kvp = NULL; for (int32 i = 0; i < num_elements; i++) { status = VerifyAndSetParameter(&(parameters[i]), true); if (status != PVMFSuccess) { LOG_ERR((0, "LipSyncDummyInputMIO::setParametersSync: Error - VerifiyAndSetParameter failed on parameter #%d", i)); ret_kvp = &(parameters[i]); OSCL_LEAVE(OsclErrArgument); } } } //////////////////////////////////////////////////////////////////////////// PVMFCommandId LipSyncDummyInputMIO::setParametersAsync(PvmiMIOSession session, PvmiKvp* parameters, int num_elements, PvmiKvp*& ret_kvp, OsclAny* context) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(parameters); OSCL_UNUSED_ARG(num_elements); OSCL_UNUSED_ARG(ret_kvp); OSCL_UNUSED_ARG(context); OSCL_LEAVE(OsclErrNotSupported); return -1; } //////////////////////////////////////////////////////////////////////////// uint32 LipSyncDummyInputMIO::getCapabilityMetric(PvmiMIOSession session) { OSCL_UNUSED_ARG(session); return 0; } //////////////////////////////////////////////////////////////////////////// PVMFStatus LipSyncDummyInputMIO::verifyParametersSync(PvmiMIOSession session, PvmiKvp* parameters, int num_elements) { OSCL_UNUSED_ARG(session); OSCL_UNUSED_ARG(parameters); OSCL_UNUSED_ARG(num_elements); return PVMFErrNotSupported; } void LipSyncDummyInputMIO::AddMarkerInfo(uint8* aData) { if (iFormat == PVMF_MIME_H2632000) { //Set the first 3 bytes to H263 start of frame pattern // This is done so that videoparser nodes send this data out // This is useful when the video MIO is compressed. oscl_memset(aData, H263_START_BYTE_1, 1); oscl_memset(aData + BYTE_1, H263_START_BYTE_2, 1); oscl_memset(aData + BYTE_2, H263_START_BYTE_3, 1); oscl_memset(aData + BYTE_3, 0, 1); //Set the timestamp as the data inside it. ((uint32*)aData)[1] = iTimestamp; } else if (iFormat == PVMF_MIME_M4V) { //Add marker info for M4V oscl_memset(aData, VOP_START_BYTE_1, 1); oscl_memset(aData + BYTE_1, VOP_START_BYTE_2, 1); oscl_memset(aData + BYTE_2, VOP_START_BYTE_3, 1); oscl_memset(aData + BYTE_3, 0, 1); //Set the timestamp as the data inside it. ((uint32*)aData)[1] = iTimestamp; } } void LipSyncDummyInputMIO::CalculateRMSInfo(uint32 aVideoData, uint32 aAudioData) { g_DiffVidAudTS = aVideoData - aAudioData; g_SqrVidAudTS += (g_DiffVidAudTS * g_DiffVidAudTS); ++g_count; } void LipSyncDummyInputMIO::GenerateAudioFrame(uint8* aData) { uint32 bytesToRead = 0; int32 error = 0; uint32 writeAsyncID = 0; for (uint32 i = 0; i < iSettings.iNumofAudioFrame; i++) { bytesToRead = Num_Audio_Bytes; iTimestamp += (uint32)(iSeqNumCounter * 1000 / iSettings.iAudioFrameRate); g_iAudioTimeStamp = iTimestamp; ++iSeqNumCounter; aData = (uint8*)iMediaBufferMemPool->allocate(BYTES_FOR_MEMPOOL_STORAGE); if (error) { --iSeqNumCounter; } ((uint32*)aData)[0] = iTimestamp; oscl_memset(aData + BYTE_4, 0, BYTE_16); PvmiMediaXferHeader data_hdr; data_hdr.seq_num = iSeqNumCounter - 1; data_hdr.timestamp = iTimestamp; data_hdr.flags = 0; data_hdr.duration = 0; data_hdr.stream_id = 0; data_hdr.private_data_length = 0; uint32 err = WriteAsyncCall(error, aData, bytesToRead, data_hdr, writeAsyncID); if (!err) { // Save the id and data pointer on iSentMediaData queue for writeComplete call PvmiDummyMediaData sentData; sentData.iId = writeAsyncID; sentData.iData = aData; iSentMediaData.push_back(sentData); LOG_STACK_TRACE((0, "LipSyncDummyInputMIO::DoRead stats in writeAsync call ts is %d seqNum is %d, media type is %s", data_hdr.timestamp, data_hdr.seq_num, (iAudioMIO ? "Audio" : "Video"))); } else if (err == OsclErrBusy) { --iSeqNumCounter; PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "LipSyncDummyInputMIO::DoRead error occurred while writeAsync call, media_type is %s", (iAudioMIO ? "Audio" : "Video"))) iMediaBufferMemPool->deallocate(aData); } else { iMediaBufferMemPool->deallocate(aData); } } } uint32 LipSyncDummyInputMIO::WriteAsyncCall(int32 &aError, uint8 *aData, uint32 &aBytesToRead, PvmiMediaXferHeader& aData_hdr, uint32 &aWriteAsyncID) { uint32 err = OsclErrNone; OSCL_TRY(err, aWriteAsyncID = iPeer->writeAsync(PVMI_MEDIAXFER_FMT_TYPE_DATA, 0, aData, aBytesToRead, aData_hdr);); return err; } void LipSyncDummyInputMIO::ProcessAudioFrame(uint32 aCurrentTime, uint32 aInterval) { if (iAudioOnlyOnce == false) { RunIfNotReady(iAudioMicroSecondsPerDataEvent); iAudioOnlyOnce = true; } else { if (aCurrentTime < iTimestamp*1000 + iAudioMicroSecondsPerDataEvent) { aInterval = iTimestamp * 1000 + iAudioMicroSecondsPerDataEvent - aCurrentTime; } else { aInterval = iAudioMicroSecondsPerDataEvent; } RunIfNotReady(aInterval); } } void LipSyncDummyInputMIO::ProcessVideoFrame(uint32 aCurrentTime, uint32 aInterval) { if (iVideoOnlyOnce == false) { RunIfNotReady(iVideoMicroSecondsPerDataEvent); iVideoOnlyOnce = true; } else { if (aCurrentTime < iTimestamp*1000 + iVideoMicroSecondsPerDataEvent) { aInterval = iTimestamp * 1000 + iVideoMicroSecondsPerDataEvent - aCurrentTime; RunIfNotReady(aInterval); } else { aInterval = iVideoMicroSecondsPerDataEvent; } RunIfNotReady(aInterval); } // Queue the next data event }
#ifndef CUSTOMER_H #define CUSTOMER_H #include <iostream> #include <cstdlib> #include <string> #include <regex> #include "full_menu.h" #include "iterator.h" #include "category.h" #include "item.h" using namespace std; class Customer{ public: Customer(string name = "anon"): _name(name){} void OrderMenu(FullMenu fullMenu) { string itemCode = " "; bool isFound = false; do { isFound == false; cout << "Please input the code of the item to order (input x when finished): "; cin>>itemCode; //cin.ignore(); if (itemCode == "x") break; else { for(int x = 0; isFound == false, x < fullMenu.GetSize(); x++) { for(int y = 0; y < fullMenu.GetCategory(x).GetSize(); y++) { //cout << fullMenu.GetCategory(x).GetItem(y).GetName() << " " << fullMenu.GetCategory(x).GetItem(y).GetProductCode() <<endl; if(fullMenu.GetCategory(x).GetItem(y).GetProductCode() == itemCode) { _orderItems.push_back(fullMenu.GetCategory(x).GetItem(y)); isFound = true; break; } } } } if (isFound == false) cout << "That item doesn't exist." << endl; }while (1); PrintReceipt(); } void PrintReceipt() { system("clear"); double totalToPay = 0; cout << "++++++++ Your Order ++++++++" << endl; for(int n = 0; n < _orderItems.size(); n++) { cout << _orderItems[n].GetName() << " " << _orderItems[n].GetPrice() << "\n"; totalToPay+=_orderItems[n].GetPrice(); } cout << "\n\n" << "Total amount to pay: " << totalToPay << endl << endl; cout << "++++++++ Thank You ++++++++" << "\n\n\n"; _orderItems.clear(); } private: string _name; double _amountToPay; vector <Item> _orderItems; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef ELEMENTREF_H #define ELEMENTREF_H #include "modules/util/simset.h" #include "modules/logdoc/src/html5/html5base.h" class FramesDocument; /** * A reference to a HTML_Element to simplify usage when the element is in risk * of being deleted or removed from the tree while the reference is in existence. * * See elementref.html in the documentation directory for detailed information * about usage and implementation of the ElementRef class. */ class ElementRef { OP_ALLOC_ACCOUNTED_POOLING OP_ALLOC_ACCOUNTED_POOLING_SMO_DOCUMENT public: #include "modules/logdoc/elementreftype.h" protected: // Don't create ElementRefs directly, use one of the sub classes ElementRef() : m_elm(NULL), m_suc(NULL), m_pred(NULL) {} ElementRef(HTML_Element *elm) : m_elm(NULL), m_suc(NULL), m_pred(NULL) { SetElm(elm); } virtual ~ElementRef() { UnlinkFromList(); } public: /** * Resets the ElementRef to not not reference anything anymore (sets the ref to NULL) */ void Reset() { Unreference(); } /** * Sets the element which is to be referenced */ virtual void SetElm(HTML5ELEMENT *elm); /** * Gets a pointer to the element which is referenced. May be NULL. */ HTML5ELEMENT* GetElm() const { return m_elm; } const HTML5ELEMENT* operator->() const { return m_elm; } HTML5ELEMENT* operator->() { return m_elm; } /** * Called when the element is about to be deleted. It may actually * be kept alive for some time longer, but you can't count on it, unless * you later get an OnInserted call. If the reference is kept (something * only KeepAliveElementRef should ever do) you may get several calls * to OnDelete. */ virtual void OnDelete(FramesDocument *document) {} /** * Called when the element has been removed from the tree it was part of. * It is however not being deleted (yet), and may be inserted into a tree again * later (in which there will be a call to OnInserted). * If the element isn't removed from the tree until that happens as part of * the final deletion process you won't get a call to this function. */ virtual void OnRemove(FramesDocument *document) {} /** * Called when the element has been inserted into a tree (but not an element * inserted into the tree for the first time as a part of parsing). * The element has been inserted by the time this function is called, so * you can check Parent() etc. to check where it was inserted. * @param old_document If the element is just moved from one tree to another this * will be the document it's moved from. May be the same as new_document or NULL. * @param new_document The document which owns the tree where the element is inserted. * May be NULL if the tree the element is inserted into is not connected to any FramesDocument. */ virtual void OnInsert(FramesDocument *old_document, FramesDocument *new_document) {} /** * Used to check if a reference is of a certain type * @returns TRUE if the ref is of type type. */ virtual BOOL IsA(ElementRefType type) { return type == ElementRef::NORMAL; } /** * @return Next reference in element's list of references. */ ElementRef* NextRef() { return m_suc; } protected: virtual void Unreference() { UnlinkFromList(); } void UnlinkFromList() { if (m_suc) // If we've a successor, unchain us { OP_ASSERT(m_suc->m_pred == this); m_suc->m_pred = m_pred; } if (m_pred) // If we've a predecessor, unchain us { OP_ASSERT(m_pred->m_suc == this); m_pred->m_suc = m_suc; } else if (m_elm) // If we don't, we're the first in the list AdvanceFirstRef(); m_pred = NULL; m_suc = NULL; m_elm = NULL; } void InsertAfter(ElementRef *pred, HTML5ELEMENT *elm) { OP_ASSERT(!m_elm && pred && !m_pred && !m_suc); m_elm = elm; m_pred = pred; if (pred->m_suc) { m_suc = pred->m_suc; m_suc->m_pred = this; } pred->m_suc = this; } private: friend class HTML_Element; /** * Used by HTML_Element::Clean() to move the reference temporarily to a * separate list while signaling removal or deletion. */ void DetachAndMoveAfter(ElementRef *pred) { if (m_suc) { OP_ASSERT(m_suc->m_pred == this); m_suc->m_pred = m_pred; } if (m_pred) { OP_ASSERT(m_pred->m_suc == this); m_pred->m_suc = m_suc; } m_pred = pred; if (pred->m_suc) { m_suc = pred->m_suc; m_suc->m_pred = this; } else m_suc = NULL; pred->m_suc = this; } void AdvanceFirstRef(); HTML5ELEMENT* m_elm; ElementRef* m_suc; ElementRef* m_pred; }; /** * Class which just NULLs the ref when it's deleted or removed from the tree */ class AutoNullElementRef : public ElementRef { public: AutoNullElementRef(HTML5ELEMENT *elm) : ElementRef(elm) {} AutoNullElementRef() {} virtual void OnDelete(FramesDocument *document) { Reset(); } virtual void OnRemove(FramesDocument *document) { Reset(); } }; /** * Class which just NULLs the ref when it's deleted */ class AutoNullOnDeleteElementRef : public ElementRef { public: AutoNullOnDeleteElementRef(HTML5ELEMENT *elm) : ElementRef(elm) {} AutoNullOnDeleteElementRef() {} virtual void OnDelete(FramesDocument *document) { Reset(); } }; /** * Class which keeps the element alive as long as the reference exists */ class KeepAliveElementRef : public ElementRef { public: KeepAliveElementRef(HTML5ELEMENT *elm) : ElementRef(elm), m_free_element_on_delete(FALSE) {} KeepAliveElementRef() : m_free_element_on_delete(FALSE) {} virtual ~KeepAliveElementRef() { HTML_Element* elm = GetElm(); UnlinkFromList(); DeleteElementIfNecessary(elm); } virtual BOOL IsA(ElementRefType type) { return type == ElementRef::KEEP_ALIVE; } virtual void OnDelete(FramesDocument *document); virtual void OnInsert(FramesDocument *old_document, FramesDocument *new_document); /** * Tell the reference that it should delete the element as soon as it is unreferenced. * This means this reference owns the element, and no one else should delete it, or * reference it after this element stops referencing it. */ virtual void FreeElementOnDelete() { m_free_element_on_delete = TRUE; } protected: virtual void Unreference(); private: /** * Deletes the element if m_free_element_on_delete is TRUE. * @param elm Must be the element we referenced when m_free_element_on_delete was set. */ void DeleteElementIfNecessary(HTML_Element* elm); BOOL m_free_element_on_delete; }; #endif // ELEMENTREF_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef IRC_IDENTD_H #define IRC_IDENTD_H #include "adjunct/m2/src/util/socketserver.h" class GlueFactory; //******************************************************************** // // IdentdServer // //******************************************************************** class IdentdServer : public SocketServer::SocketServerListener { public: // Listener. class IdentdListener { public: virtual ~IdentdListener() {} virtual void OnConnectionEstablished(const OpStringC &connection_to) { } virtual void OnIdentConfirmed(const OpStringC8 &request, const OpStringC8 &response) { } protected: // Construction. IdentdListener() { } }; // Construction / destruction. IdentdServer(IdentdListener &listener); virtual ~IdentdServer(); OP_STATUS Init(const OpStringC &ident_as); private: // Methods. void SendResponseIfPossible(); // SocketServer::SocketServerListener. virtual void OnSocketConnected(const OpStringC &connected_to); virtual void OnSocketDataAvailable(); // Members. IdentdListener &m_listener; OpAutoPtr<SocketServer> m_socket_server; OpString8 m_ident_as; OpString8 m_request; }; #endif
class Mascot { public: explicit Mascot(int, int, int); //constructor (ID, X, Y) void mascotController(); //Controls animations for mascot sprites void updateHoleState(); //updates currentState to the value of hole[x] (global variable) private: void setSprite(); //Sets the image for the sprite to spawn next void nextSprite(); //Picks which set of images for the sprite to spawn from void updateState(); //updates hole[x] (global variable) with current value of currentState int currentState; //set explicitly, then updates when picked by nextHole() in spawn.h or within mascotController() int holeNumber; //ID set by constructor int xLoc; //X-axis location of hole int yLoc; //Y-axis location of hole int mascotSpriteID; //Sprite ID of mascot to spawn int mascotImageID; //Image ID of mascot to spawn int randomMascotID; bool homeChecker; char* animationUp; char* animationStill; char* animationDown; char* animationDead; char* animationDeadInterrupted; };
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "CountdownBoard.generated.h" class USceneComponent; class ACountdownTile; UCLASS() class FINALCOUNTDOWN_API ACountdownBoard : public AActor { GENERATED_BODY() UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) USceneComponent* DummyRoot; public: // Sets default values for this actor's properties ACountdownBoard(); /** Number of blocks along each side of grid */ UPROPERTY(Category = Grid, EditAnywhere, BlueprintReadOnly) int32 Size; /** Spacing of blocks */ UPROPERTY(Category = Grid, EditAnywhere, BlueprintReadOnly) float TileSpacing; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; void Countdown(); FTimerHandle TimerHandle_Countdown; UPROPERTY() ACountdownTile* NewTile; //An array of NewTile actors TArray<ACountdownTile*> TileArray; public: // Called every frame virtual void Tick(float DeltaTime) override; int RandNum; };
#include <iostream> #include <memory.h> using namespace std; int dx[4] = { 1,-1,0,0 }; int dy[4] = { 0,0,1,-1 }; int map[6][6]; bool candidate[10000000]; int counter = 0; void DFS(int x, int y, int process, int dest,int current_num); int main() { int test_case = 0; cin >> test_case; for (int t = 1; t <= test_case; t++) { counter = 0; memset(candidate, false, sizeof(candidate)); for (int s = 0; s < 6; s++) { for (int t = 0; t < 6; t++) { map[s][t] = -1; } } for (int s = 1; s <= 4; s++) { for (int t = 1; t <= 4; t++) { cin >> map[s][t]; } } for (int s = 1; s <= 4; s++) { for (int t = 1; t <= 4; t++) { DFS(s,t,0,7,0); } } cout << '#' << t << ' ' << counter << endl; } return 0; } void DFS(int x, int y, int process, int dest, int current_num) { if (candidate[current_num] == false && dest == process) { candidate[current_num] = true; counter += 1; return; } else if (process < dest) { // 현재 중간 수 백업 int temp_num = map[x][y]; for (int u = 1; u <= process; u++) { temp_num *= 10; } // DFS 탐색 for (int idx = 0; idx < 4; idx++) { if(map[x + dx[idx]][y + dy[idx]] != -1) DFS(x + dx[idx], y + dy[idx], process + 1, dest, current_num + temp_num); } } else { return; } return; }
#ifndef JETINFO_HH #define JETINFO_HH class JetInfo { public: int iphi; int ieta; int et; JetInfo() {}; JetInfo(int iphi,int ieta,int et) { this->iphi = iphi; this->ieta = ieta; this->et = et; } }; #endif
#include <iostream> #include <string.h> #include <math.h> #include <cstdlib> #include <ctime> using namespace std; int dice_roll(){ int v; srand(time(NULL)); //ensures true randomness v = rand() % 6 + 1; return v; //returns value between 1 and 6 } class Player{ int position; public: Player(){ position = 0; } friend class Game; void play(int); }; void Player::play( int die){ position += die; if(position == 21){ cout<<"Snake!!!"; position -= 10; } else if(position == 34){ cout<<"Snake!!!"; position -= 15; } else if(position == 67){ cout<<"Snake!!!"; position -= 12; } else if(position == 58){ cout<<"Snake!!!"; position -= 4; } else if(position == 87){ cout<<"Snake!!!"; position -= 56; } else if(position == 94){ cout<<"Snake!!!"; position -= 76; } else if(position == 45){ cout<<"Ladder!!!"; position += 15; } else if(position == 75){ cout<<"Ladder!!!"; position += 12; } else if(position == 88){ cout<<"Ladder!!!"; position += 4; } else if(position == 2){ cout<<"Ladder!!!"; position += 26; } else if(position == 18){ cout<<"Ladder!!!"; position += 76; } } class Game{ int players; Player p1; Player p2; Player p3; Player p4; public: Game(){ players = 0; } void EnterPlayers(); void PrintGameLine(int); void PrintGame(); void play(); friend class Player; }; void Game::play(){ while(p1.position < 100 and p2.position < 100 and p3.position < 100 and p4.position < 100){ int t, die; cout<<"Which player is playing?"<<endl; cin>>t; switch(t){ case 1: die = dice_roll(); cout<<"die roll is "<<die<<endl; p1.play(die); break; case 2: die = dice_roll(); cout<<"die roll is "<<die<<endl; p2.play(die); break; case 3: die = dice_roll(); cout<<"die roll is "<<die<<endl; p3.play(die); break; case 4: die = dice_roll(); cout<<"die roll is "<<die<<endl; p4.play(die); break; } PrintGame(); } } void Game::PrintGameLine(int i){ if(p1.position == i) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i) cout<<"P2"; else cout<<" "; if(p1.position == i-1) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-1) cout<<"P2"; else cout<<" "; if(p1.position == i-2) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-2) cout<<"P2"; else cout<<" "; if(p1.position == i-3) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-3) cout<<"P2"; else cout<<" "; if(p1.position == i-4) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-4) cout<<"P2"; else cout<<" "; if(p1.position == i-5) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-5) cout<<"P2"; else cout<<" "; if(p1.position == i-6) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-6) cout<<"P2"; else cout<<" "; if(p1.position == i-7) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-7) cout<<"P2"; else cout<<" "; if(p1.position == i-8) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-8) cout<<"P2"; else cout<<" "; if(p1.position == i-9) cout<<"P1"; else cout<<" "; cout<<" "; if(p2.position == i-9) cout<<"P2"<<endl; else cout<<" "<<endl; cout<<" "<<i<<" "; cout<<" "<<i-1<<" "; cout<<" "<<i-2<<" "; cout<<" "<<i-3<<" "; cout<<" "<<i-4<<" "; cout<<" "<<i-5<<" "; cout<<" "<<i-6<<" "; cout<<" "<<i-7<<" "; cout<<" "<<i-8<<" "; cout<<" "<<i-9<<" "<<endl; if(p3.position == i) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i) cout<<"P4"; else cout<<" "; if(p3.position == i-1) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-1) cout<<"P4"; else cout<<" "; if(p3.position == i-2) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-2) cout<<"P4"; else cout<<" "; if(p3.position == i-3) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-3) cout<<"P4"; else cout<<" "; if(p3.position == i-4) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-4) cout<<"P4"; else cout<<" "; if(p3.position == i-5) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-5) cout<<"P4"; else cout<<" "; if(p3.position == i-6) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-6) cout<<"P4"; else cout<<" "; if(p3.position == i-7) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-7) cout<<"P4"; else cout<<" "; if(p3.position == i-8) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-8) cout<<"P4"; else cout<<" "; if(p3.position == i-9) cout<<"P3"; else cout<<" "; cout<<" "; if(p4.position == i-9) cout<<"P4"<<endl; else cout<<" "<<endl; } void Game::PrintGame(){ PrintGameLine(100); PrintGameLine(90); PrintGameLine(80); PrintGameLine(70); PrintGameLine(60); PrintGameLine(50); PrintGameLine(40); PrintGameLine(30); PrintGameLine(20); PrintGameLine(10); } int main(){ Game g; g.PrintGame(); g.play(); return 0; }
#include "tests.hpp" #include "SLAM.hpp" #include "random.hpp" #include <opencv/highgui.h> using namespace std; using namespace cv; typedef Mat_<byte> matim; bool Tester::test_project() { for (int itest = 0; itest < 100; ++itest) { startover: Size imsize(rand() % 1000 + 1, rand() % 1000 + 1); matf K(3,3,0.0f); K(0,0) = grand(50) + 500; K(1,1) = grand(50) + 500; K(2,2) = 1.0f; K(0,2) = imsize.width/2 + grand(5); K(1,2) = imsize.height/2 + grand(5); // initial state : camera is at (0,0,0), R = eye SLAM::CameraState state(K, matf::eye(3,3), matf(3,1,0.0f)); // object is at depth dobj, on axis Z float dobj = frand() * 25 + 10; // object is on plane XY, has size dobjx in X, same Y int dobjx = rand() % 100 + 1; int dobjy = rand() % 100 + 1; int deltax = grand(25); int deltay = grand(25); float objincrx = dobj/K(0,0); float objincry = dobj/K(1,1); matf p3d(3,1); p3d(0) = deltax; p3d(1) = deltay; p3d(2) = dobj; // generate object matim object(dobjy, dobjx); for (int i = 0; i < dobjx; ++i) for (int j = 0; j < dobjy; ++j) object(j,i) = rand() % 256; // project object matim im(imsize, 0); for (int i = 0; i < dobjx; ++i) for (int j = 0; j < dobjy; ++j) { matf p(4,1,1.0f); p(0) = (i - floor(dobjx/2)) * objincrx + deltax; p(1) = (j - floor(dobjy/2)) * objincry + deltay; p(2) = dobj; matf p2d = state.project(p); if (!((p2d(0) >= 0) && (p2d(1) >= 0) && (round(p2d(0)) < imsize.width) && (round(p2d(1)) < imsize.height))) goto startover; im(round(p2d(1)), round(p2d(0))) = object(j,i); } // create patch matf p(4,1,1.0f), p1(4,1,1.0f);//, p2(4,1,1.0f); p (0) = deltax; p (1) = deltay; p (2) = dobj; p1(0) = (- floor(dobjx/2)) * objincrx + deltax; p1(1) = (- floor(dobjy/2)) * objincry + deltay; p1(2) = dobj; //p2(0) = (dobjx-1 - floor(dobjx/2) + deltax) * objincrx; //p2(1) = (dobjy-1 - floor(dobjy/2) + deltay) * objincry; //p2(2) = dobj; matf p2d = state.project(p); matf p2d1 = state.project(p1);//, p2d2 = state.project(p2); int dx = round(p2d(0)-p2d1(0)), dy = round(p2d(1)-p2d1(1)); SLAM::Feature feature (im, state, 0, Point2i(round(p2d(0)), round(p2d(1))), cvrange(p,0,3), dx, dy); //now we rotate and we compare for (int irot = 0; irot < 10; ++irot) { im.setTo(0); // generate a random state Quaternion rotQ; do { rotQ = Quaternion(grand(1), grand(1), grand(1), grand(1)); } while (rotQ.norm() < 0.1); rotQ /= rotQ.norm(); matf R = rotQ.toMat(); matf t(3,1,0.0f); do { t(0) = grand(50); t(1) = grand(50); t(2) = grand(50); } while (norm(t-p3d) > grand(1) * dobj); SLAM::CameraState state(K, R, t); // project object bool isSeen = true; matim im(imsize, 0); for (int i = 0; i < dobjx; ++i) for (int j = 0; j < dobjy; ++j) { matf p(4,1,1.0f); p(0) = (i - floor(dobjx/2)) * objincrx + deltax; p(1) = (j - floor(dobjy/2)) * objincry + deltay; p(2) = dobj; matf p2d = state.project(p); if (!((p2d(0) >= 0) && (p2d(1) >= 0) && (round(p2d(0)) < imsize.width) && (round(p2d(1)) < imsize.height))) { isSeen = false; break; } im(round(p2d(1)), round(p2d(0))) = object(j,i); } if(!isSeen) { --irot; continue; } Rect proj_location; matim mask; matim proj = feature.project(state, p3d, mask, proj_location); if (proj.size().height > 0) { matb todisp[3]; todisp[0] = matb(imsize,0); todisp[1] = im; todisp[2] = matb(imsize,0); cvCopyToCrop(proj, todisp[2], proj_location); mat3b imdisp; merge(todisp, 3, imdisp); namedWindow("imdisp"); imshow("imdisp", imdisp); cvWaitKey(0); } } /* // generate a random state Quaternion rotQ; do { rotQ = Quaternion(grand(1), grand(1), grand(1), grand(1)); } while (rotQ.norm() < 0.1); rotQ /= rotQ.norm(); matf R = rotQ.toMat(); matf t(3,1); t(0) = grand(25); t(1) = grand(25); t(2) = grand(25); SLAM::CameraState state(K, R, t); // We assume that we see an object that is composed of points // x0 + a * u + b * v, where a\in[amin,amax] and b\in[bmin,bmax] // at first time we see it, u,v are parallel to the camera plane, // so the point is at p(x0) + a * k1*i + b * k2*j int w2dobj = rand() % 100 + 1; int h2dobj = rand() % 100 + 1; int l2dobj = floor(w2dobj/2), t2dobj = floor(h2dobj/2); matf p2d(3,1,1.0f); p2d(0) = rand() % (imsize.width - w2dobj + 1) + l2dobj; p2d(1) = rand() % (imsize.height - h2dobj + 1) + t2dobj; matf ray = state.KRinv * p2d; matf centerObj = t + (frand() * 25 + 10) * ray; float objDepth = ((matf)(P*centerObj))(2); int wobj = w2dobj; int hobj = h2dobj; // the object plane is p31*x + p32*y + p33*z + p34-objDepth = 0 for (int i = p2d(0) - l2dobj; i < p2d(0)-l2dobj+w2dobj; ++i) for (int j = p2d(1) - t2dobj; j < p2d(1)-t2dobj+h2dobj; ++j) { matf p2d2(3,1,1.0f); p2d(0) = i; p2d(1) = j; matf ray2 = state.KRinv * p2d2; float lambda = (state.P(2,3)-objDepth - state.P.row(2).dot(t)) / (state.P.row(2).dot(ray2)); matf p3d2 = t + lambda * ray2; } */ // } return true; }
#ifndef _MSG_0X1F_ENTITYRELATIVEMOVE_STC_H_ #define _MSG_0X1F_ENTITYRELATIVEMOVE_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class EntityRelativeMove : public BaseMessage { public: EntityRelativeMove(); EntityRelativeMove(int32_t _entityId, int8_t _dx, int8_t _dy, int8_t _dz); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getEntityId() const; int8_t getDx() const; int8_t getDy() const; int8_t getDz() const; void setEntityId(int32_t _val); void setDx(int8_t _val); void setDy(int8_t _val); void setDz(int8_t _val); private: int32_t _pf_entityId; int8_t _pf_dx; int8_t _pf_dy; int8_t _pf_dz; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X1F_ENTITYRELATIVEMOVE_STC_H_
#include <colib/co_routine_specific.h> #include "PaxosKVServiceImpl.hpp" struct __PaxosKVServiceImplWrapper{ PaxosKVServiceImpl * pImpl; }; CO_ROUTINE_SPECIFIC(__PaxosKVServiceImplWrapper, g_coPaxosKVServiceImplWrapper) PaxosKVServiceImpl *PaxosKVServiceImpl::GetInstance() { return g_coPaxosKVServiceImplWrapper->pImpl; } void PaxosKVServiceImpl::SetInstance(PaxosKVServiceImpl *pImpl) { g_coPaxosKVServiceImplWrapper->pImpl = pImpl; }
#pragma once using namespace std; #include <vector> #include <sstream> namespace OCScript { // 文字列操作を便利にする機能をまとめたクラスです。 class StringUtility { public: // 区切り文字により文字列をスプリットします。 // 引数: ソース文字列, 区切り文字 static vector<wstring> Split(const wstring &src, wchar_t delimiter) { wstringstream ss(src); vector<wstring> items; wstring item; while (getline(ss, item, delimiter)) items.push_back(item); return items; } // 区切り文字により文字列を連結します。 // 引数: ソース文字列, 区切り文字 static wstring Join(const vector<wstring> &src, wstring delimiter) { wstring dest; for (auto it = src.begin(); it != src.end(); it++) { dest += *it; if (it != src.end() - 1) dest += delimiter; } return dest; } // 文字列を置換して新しい文字列として返します。 // 引数: ソース文字列, 対象の文字列, 置換後の文字列 static wstring Replace(const wstring src, const wstring oldVal, const wstring newVal) { auto temp = src; wstring::size_type pos(temp.find(oldVal)); while (pos != wstring::npos) { temp.replace(pos, oldVal.length(), newVal); pos = temp.find(oldVal, pos + newVal.length()); } return temp; } }; }
#pragma once #include "plbase/PluginBase.h" #pragma pack(push, 4) class PLUGIN_API LimbOrienation { public: float m_fYaw; float m_fPitch; }; #pragma pack(pop) VALIDATE_SIZE(LimbOrienation, 8);
/*! * \file TriggerEventGroup.h * * \author Shiyang Ao * \date November 2016 * * */ #pragma once #include "IComponent.h" #include "BaseEventGroup.h" namespace Hourglass { class TriggerEventGroup : public BaseEventGroup { DECLARE_COMPONENT_TYPEID public: // Override IComponent functions IComponent* MakeCopyDerived() const; void OnTriggerEnter(Entity* other); // TriggerEventGroup functions protected: }; }
/* ID: stevenh6 TASK: kimbits LANG: C++ */ #include <fstream> #include <string> #include <algorithm> using namespace std; ofstream fout("kimbits.out"); ifstream fin("kimbits.in"); double graph[33][33]; void nextbit(int N, int L, double I) { if (N != 0) { if (graph[N - 1][L] > I) { fout << 0; nextbit(N - 1, L, I); } else { fout << 1; nextbit(N - 1, L - 1, I - graph[N - 1][L]); } } } int main() { int N, L; double I; for (int i = 0; i < 33; i++) { graph[0][i] = 1; } for (int i = 1; i < 33; i++) { for (int j = 0; j < 33; j++) { if (j != 0) { graph[i][j] = graph[i - 1][j - 1] + graph[i - 1][j]; } else { graph[i][j] = 1; } } } fin >> N >> L >> I; nextbit(N, L, I - 1); fout << endl; }
#include "BTreeNode.h" #include <iostream> #include <cstring> #include <stdio.h> #include <cstdlib> using namespace std; BTLeafNode::BTLeafNode() { memset(buffer, 0, 1024); } /* * Read the content of the node from the page pid in the PageFile pf. * @param pid[IN] the PageId to read * @param pf[IN] PageFile to read from * @return 0 if successful. Return an error code if there is an error. */ RC BTLeafNode::read(PageId pid, const PageFile& pf) { return pf.read(pid, buffer); } /* * Write the content of the node to the page pid in the PageFile pf. * @param pid[IN] the PageId to write to * @param pf[IN] PageFile to write to * @return 0 if successful. Return an error code if there is an error. */ RC BTLeafNode::write(PageId pid, PageFile& pf) { return pf.write(pid, buffer); } /* * Return the number of keys stored in the node. * @return the number of keys in the node */ int BTLeafNode::getKeyCount() { int entrySize = sizeof(int) + sizeof(RecordId); int count = 0; char *temp = buffer; int theKey; for (int i = 0; i < (1024 - sizeof(PageId))/entrySize; ++i) { // 4 is sizeof(int) memcpy(&theKey, temp, 4); if (!theKey) break; ++count; temp += entrySize; } return count; } /* * Insert a (key, rid) pair to the node. * @param key[IN] the key to insert * @param rid[IN] the RecordId to insert * @return 0 if successful. Return an error code if the node is full. */ RC BTLeafNode::insert(int key, const RecordId& rid) { // this is 4 + (4 + 4) = 12 int entrySize = sizeof(int) + sizeof(RecordId); int maxNumberOfEntries = (1024 - sizeof(PageId)) / entrySize; // this is (1024 - 4)/12 = 85 int keyCount = getKeyCount(); if (keyCount == maxNumberOfEntries) return RC_NODE_FULL; char *temp = buffer; int i = 0, theKey; for (; i < (1024 - sizeof(PageId))/entrySize; ++i) { memcpy(&theKey, temp, sizeof(int)); if ((!theKey) || (theKey > key) ) break; temp += entrySize; } // i is the number of items "key" is > than char *newBuffer = (char *)malloc(1024); memset(newBuffer, 0, 1024); // copy i items memcpy(newBuffer, buffer, i*entrySize); // copy "key" and "rid" memcpy(newBuffer + (i*entrySize), &key, sizeof(int)); memcpy(newBuffer + (i*entrySize) + sizeof(int), &rid, sizeof(RecordId)); // copy the rest (items that "key" is < than) memcpy(newBuffer + (i+1)*entrySize, buffer + (i*entrySize), (keyCount - i) * entrySize); // copy the pageID of next page PageId myPageID = getNextNodePtr(); memcpy(newBuffer + 1024 - sizeof(PageId), &myPageID, sizeof(PageId)); // copy the newBuffer back into buffer memcpy(buffer, newBuffer, 1024); free(newBuffer); return 0; } /* * Insert the (key, rid) pair to the node * and split the node half and half with sibling. * The first key of the sibling node is returned in siblingKey. * @param key[IN] the key to insert. * @param rid[IN] the RecordId to insert. * @param sibling[IN] the sibling node to split with. This node MUST be EMPTY when this function is called. * @param siblingKey[OUT] the first key in the sibling node after split. * @return 0 if successful. Return an error code if there is an error. */ RC BTLeafNode::insertAndSplit(int key, const RecordId& rid, BTLeafNode& sibling, int& siblingKey) { int entrySize = sizeof(int) + sizeof(RecordId); int maxNumberOfEntries = (1024 - sizeof(PageId)) / entrySize; // this is (1024-4)/12 = 85 int keyCount = getKeyCount(); if (keyCount < maxNumberOfEntries) return RC_INVALID_FILE_FORMAT; if (sibling.getKeyCount()) return RC_INVALID_ATTRIBUTE; memset(sibling.buffer, 0, 1024); // This is the number of keys that remain in this node int firstHalf = (keyCount + 1) / 2; // Copy the secondHalf to the sibling node memcpy(sibling.buffer, buffer + (firstHalf*entrySize), 1024 - sizeof(PageId) - (firstHalf*entrySize)); // Set the pageid of the sibling node sibling.setNextNodePtr(getNextNodePtr()); // Erase the secondHalf from this node std::fill(buffer + (firstHalf*entrySize), buffer + 1024 - sizeof(PageId), 0); // Now we insert the new (key, rid) pair int theKey; memcpy(&theKey, sibling.buffer, sizeof(int)); if (key >= theKey) sibling.insert(key, rid); else insert(key, rid); // Now we return the first key of the sibling node memcpy(&siblingKey, sibling.buffer, sizeof(int)); // Should we set the "next node pointer" of this node to the sibling node ??? // ... return 0; } /** * If searchKey exists in the node, set eid to the index entry * with searchKey and return 0. If not, set eid to the index entry * immediately after the largest index key that is smaller than searchKey, * and return the error code RC_NO_SUCH_RECORD. * Remember that keys inside a B+tree node are always kept sorted. * @param searchKey[IN] the key to search for. * @param eid[OUT] the index entry number with searchKey or immediately behind the largest key smaller than searchKey. * @return 0 if searchKey is found. Otherwise return an error code. */ RC BTLeafNode::locate(int searchKey, int& eid) { int entrySize = sizeof(int) + sizeof(RecordId); char *temp = buffer; int i = 0; // i = index entry int theKey; for (; i < getKeyCount(); ++i) { memcpy(&theKey, temp, sizeof(int)); if (theKey == searchKey) { eid = i; return 0; } else if (theKey > searchKey) { eid = i; return RC_NO_SUCH_RECORD; } temp += entrySize; } // At this point, searchKey is > all keys in the node eid = i; return RC_NO_SUCH_RECORD; } /* * Read the (key, rid) pair from the eid entry. * @param eid[IN] the entry number to read the (key, rid) pair from * @param key[OUT] the key from the entry * @param rid[OUT] the RecordId from the entry * @return 0 if successful. Return an error code if there is an error. */ RC BTLeafNode::readEntry(int eid, int& key, RecordId& rid) { // first check if eid is valid if (eid < 0 || eid >= getKeyCount()) return RC_NO_SUCH_RECORD; int entrySize = sizeof(int) + sizeof(RecordId); memcpy(&key, buffer + (eid*entrySize), sizeof(int)); memcpy(&rid, buffer + (eid*entrySize) + sizeof(int), sizeof(RecordId)); return 0; } /* * Return the pid of the next slibling node. * @return the PageId of the next sibling node */ PageId BTLeafNode::getNextNodePtr() { PageId myPageID; memcpy(&myPageID, buffer + 1024 - sizeof(PageId), sizeof(PageId)); return myPageID; } /* * Set the pid of the next slibling node. * @param pid[IN] the PageId of the next sibling node * @return 0 if successful. Return an error code if there is an error. */ RC BTLeafNode::setNextNodePtr(PageId pid) { // first check if pid is valid if (pid < 0) return RC_INVALID_PID; memcpy(buffer + 1024 - sizeof(PageId), &pid, sizeof(PageId)); return 0; } void BTLeafNode::print() { int entrySize = sizeof(int) + sizeof(RecordId); char *temp = buffer; int theKey; for (int i = 0; i < getKeyCount(); ++i) { memcpy(&theKey, temp, sizeof(int)); cout << theKey << " | "; temp += entrySize; } cout << "[pid]" << endl; } BTNonLeafNode::BTNonLeafNode() { memset(buffer, 0, 1024); } /* * Read the content of the node from the page pid in the PageFile pf. * @param pid[IN] the PageId to read * @param pf[IN] PageFile to read from * @return 0 if successful. Return an error code if there is an error. */ RC BTNonLeafNode::read(PageId pid, const PageFile& pf) { return pf.read(pid, buffer); } /* * Write the content of the node to the page pid in the PageFile pf. * @param pid[IN] the PageId to write to * @param pf[IN] PageFile to write to * @return 0 if successful. Return an error code if there is an error. */ RC BTNonLeafNode::write(PageId pid, PageFile& pf) { return pf.write(pid, buffer); } // For leaf: Structure is: (key,rid) | (key, rid) | ... | pid // For non-leaf: Structure is: pid (4 empty bytes) | (key, pid) | (key, pid) | ... | (key, pid) /* * Return the number of keys stored in the node. * @return the number of keys in the node */ int BTNonLeafNode::getKeyCount() { int count = 0; int entrySize = sizeof(PageId) + sizeof(int); // this is 4 + 4 = 8 char *temp = buffer + 4 + sizeof(PageId); // according to the structure above int theKey; for (int i = 0; i < (1024 - sizeof(PageId))/entrySize; ++i) { // this is (1024 - 4)/8 = 127 // 4 is sizeof(int) and also sizeof(PageID) memcpy(&theKey, temp, sizeof(int)); if (!theKey) break; ++count; temp += entrySize; } return count; } /* * Insert a (key, pid) pair to the node. * @param key[IN] the key to insert * @param pid[IN] the PageId to insert * @return 0 if successful. Return an error code if the node is full. */ RC BTNonLeafNode::insert(int key, PageId pid) { // this is 4 + 4 = 8 int entrySize = sizeof(int) + sizeof(PageId); int maxNumberOfEntries = (1024 - sizeof(PageId)) / entrySize; // this is (1024 - 4)/8 = 127 int keyCount = getKeyCount(); if (keyCount == maxNumberOfEntries) return RC_NODE_FULL; char *temp = buffer + 4 + sizeof(PageId); int i = 0, theKey; for (; i < (1024 - sizeof(PageId))/entrySize; ++i) { memcpy(&theKey, temp, sizeof(int)); if ((!theKey) || (theKey > key) ) break; temp += entrySize; } // i is the number of items "key" is > than char *newBuffer = (char *)malloc(1024); memset(newBuffer, 0, 1024); // copy i items (and the initial 8 bytes) memcpy(newBuffer, buffer, 8 + i*entrySize); // copy "key" and "pid" memcpy(newBuffer + 8 + (i*entrySize), &key, sizeof(int)); memcpy(newBuffer + 8 + (i*entrySize) + sizeof(int), &pid, sizeof(PageId)); // copy the rest (items that "key" is < than) memcpy(newBuffer + 8 + (i+1)*entrySize, buffer + 8 + (i*entrySize), (keyCount - i) * entrySize); // copy the newBuffer back into buffer memcpy(buffer, newBuffer, 1024); free(newBuffer); return 0; } /* * Insert the (key, pid) pair to the node * and split the node half and half with sibling. * The middle key after the split is returned in midKey. * @param key[IN] the key to insert * @param pid[IN] the PageId to insert * @param sibling[IN] the sibling node to split with. This node MUST be empty when this function is called. * @param midKey[OUT] the key in the middle after the split. This key should be inserted to the parent node. * @return 0 if successful. Return an error code if there is an error. */ RC BTNonLeafNode::insertAndSplit(int key, PageId pid, BTNonLeafNode& sibling, int& midKey) { int entrySize = sizeof(int) + sizeof(PageId); int maxNumberOfEntries = (1024 - sizeof(PageId)) / entrySize; // this is (1024-4)/8 = 127 int keyCount = getKeyCount(); if (keyCount < maxNumberOfEntries) return RC_INVALID_FILE_FORMAT; if (sibling.getKeyCount()) return RC_INVALID_ATTRIBUTE; memset(sibling.buffer, 0, 1024); // This is the number of keys that remain in this node int firstHalf = (keyCount + 1) / 2; // Now we have to find the middle key // Since the keys are sorted, 3 candidates for middle key are: // Last key of the first node, first key of the sibling node, and the one // we are about to insert in this function int lastKeyOfFirst, firstKeyOfSibling; memcpy(&lastKeyOfFirst, buffer + 8 + (firstHalf*entrySize) - 8, sizeof(int)); memcpy(&firstKeyOfSibling, buffer + 8 + (firstHalf*entrySize), sizeof(int)); if (key < lastKeyOfFirst) { // lastKeyOfFirst = middle key // set the midKey midKey = lastKeyOfFirst; // copy the secondHalf to the sibling node memcpy(sibling.buffer + 8, buffer + 8 + (firstHalf * entrySize), 1024 - 8 - (firstHalf * entrySize) ); // set the head pid of the sibling node to the pid of the (lastKeyOfFirst, pid) pair of the first node memcpy(sibling.buffer, buffer + (firstHalf*entrySize) + sizeof(int), sizeof(PageId)); // erase the secondHalf from this node, including the lastKeyOfFirst std::fill(buffer + (firstHalf*entrySize), buffer + 1024, 0); insert(key, pid); } else if (key > firstKeyOfSibling) { // firstKeyOfSibling = middle key // set the midKey midKey = firstKeyOfSibling; // copy the secondHalf to the sibling node, except the (firstKeyOfSibling, pid) pair memcpy(sibling.buffer + 8, buffer + 8 + (firstHalf*entrySize) + entrySize, 1024 - 8 - (firstHalf*entrySize) - entrySize); // set the head pid of the sibling node to the pid of the (firstKeyOfSibling, pid) pair memcpy(sibling.buffer, buffer + 8 + (firstHalf*entrySize) + sizeof(int), sizeof(PageId)); // erase the secondHalf from this node std::fill(buffer + 8 + (firstHalf*entrySize), buffer + 1024, 0); sibling.insert(key, pid); } else { // key = middle key // set the midKey midKey = key; // copy the secondHalf to the sibling node memcpy(sibling.buffer + 8, buffer + 8 + (firstHalf*entrySize), 1024 - 8 - (firstHalf*entrySize)); // set the head pid of the sibling node to the pid of the (key, pid) pair we are to insert in this function memcpy(sibling.buffer, &pid, sizeof(PageId)); // erase the secondHalf from this node std::fill(buffer + 8 + (firstHalf*entrySize), buffer + 1024, 0); } return 0; } /* * Given the searchKey, find the child-node pointer to follow and * output it in pid. * @param searchKey[IN] the searchKey that is being looked up. * @param pid[OUT] the pointer to the child node to follow. * @return 0 if successful. Return an error code if there is an error. */ RC BTNonLeafNode::locateChildPtr(int searchKey, PageId& pid) { int entrySize = sizeof(int) + sizeof(PageId); char *temp = buffer + 8; int theKey; memcpy(&pid, buffer, sizeof(PageId)); for (int i = 0; i < getKeyCount(); ++i) { memcpy(&theKey, temp, sizeof(int)); if (searchKey >= theKey) memcpy(&pid, temp + sizeof(int), sizeof(PageId)); else break; temp += entrySize; } return 0; } /* * Initialize the root node with (pid1, key, pid2). * @param pid1[IN] the first PageId to insert * @param key[IN] the key that should be inserted between the two PageIds * @param pid2[IN] the PageId to insert behind the key * @return 0 if successful. Return an error code if there is an error. */ RC BTNonLeafNode::initializeRoot(PageId pid1, int key, PageId pid2) { memset(buffer, 0, 1024); memcpy(buffer, &pid1, sizeof(PageId)); return insert(key, pid2); } void BTNonLeafNode::print() { int entrySize = sizeof(int) + sizeof(PageId); char *temp = buffer + 8; int theKey; for (int i = 0; i < getKeyCount(); ++i) { memcpy(&theKey, temp, sizeof(int)); cout << theKey << " | "; temp += entrySize; } cout << endl; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (1e15); const int INF = (1<<30); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class IncredibleMachine { public: double calculateTime(double distance, double velocity, double acceleration) { double low=0,high=1e10; for (int i=0; i<100; ++i) { double t = (low+high) / 2.0; double d = velocity*t + 0.5*acceleration*t*t; if (distance > d) low = t; else high = t; } return low; } double simulate(double g, vector <int> &x, vector <int> &y) { int N = (int)x.size(); double time = 0; double v = 0; for (int i=1; i<N; ++i) { int dx = x[i] - x[i-1]; int dy = y[i-1] - y[i]; double r = sqrt(dx*dx + dy*dy); double a = g * dy / r; double t = calculateTime(r, v, a); time += t; v = v + a*t; } return time; } double gravitationalAcceleration(vector <int> x, vector <int> y, int T) { double low=0,high=1e10; for (int i=0; i<100; ++i) { double g = (low + high) / 2.0; double time = simulate(g, x, y); if (T > time) high = g; else low = g; } return low; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {0,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100,22}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; double Arg3 = 9.807692307692307; verify_case(0, Arg3, gravitationalAcceleration(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {0,26,100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {50,26,24}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; double Arg3 = 26.743031720603582; verify_case(1, Arg3, gravitationalAcceleration(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {0,7,8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10,6,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 7; double Arg3 = 1.1076837407708007; verify_case(2, Arg3, gravitationalAcceleration(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { IncredibleMachine ___test; ___test.run_test(-1); } // END CUT HERE
#pragma once #include "residlerParameterFormat.h" #include "sid.h" namespace Steinberg { namespace Vst { namespace residler { struct sidinfo { double clockRate; double sampleRate; }; class sid_wrapper { public: void reset(struct sidinfo *sidinfo_in); #if 0 void start_gen(int frames, float *buf); int run_gen(int frames); #endif int gen(int maxcycles, int maxframes, float *buf); void note_on(int16 note, float velocity); void note_off(int16 note); void set_param(residlerParameterFormat::paramIds, double); private: reSIDfp::SID resid; struct sidinfo sidinfo; int estimate_cycles(int frames_left); static const int res_buf_size = 65536; short residual_buf[res_buf_size]; int residual_buf_fill; struct voiceState { voiceState () : noise (true) , pulse (false) , saw (false) , triangle (false) , ringMod (false) , sync (false) , gate (false) , voiceOn (false) , currentNote(0) , pitchMult (0.5f) , attack (8) , decay (8) , sustain (8) , release (8) {} bool noise; bool pulse; bool saw; bool triangle; bool ringMod; bool sync; bool gate; bool voiceOn; int16 currentNote; double pitchMult; unsigned char attack; unsigned char decay; unsigned char sustain; unsigned char release; } voiceState[3]; struct filterState { filterState () : resonance (8) , voice0FilterOn (false) , voice1FilterOn (false) , voice2FilterOn (false) , HP (false) , BP (false) , LP (true) {} unsigned char resonance; bool voice0FilterOn; bool voice1FilterOn; bool voice2FilterOn; bool HP; bool BP; bool LP; } filterState; void waveformSelector(int, double); unsigned char prepareSIDControlReg(int); unsigned char setSIDRESFilt(); unsigned char setSIDModeVol(); }; }}} // namespaces
// // Created by dylan on 25-5-2020. // #ifndef CPSE2_BOARD_BUILDER_HPP #define CPSE2_BOARD_BUILDER_HPP #include <SFML/Graphics.hpp> class board_builder { private: sf::Vector2f colum1 = {0.0, 205.0}; sf::Vector2f colum2 = {650.0, 20.0}; sf::Vector2f colum3 = {0.0, 430.0}; sf::Vector2f colum4 = {205.0, 0.0}; sf::Vector2f colum5 = {20.0, 650.0}; sf::Vector2f colum6 = {430.0, 0.0}; sf::Color color = sf::Color::White; sf::RenderWindow &window; protected: void draw_rectangle(sf::Vector2f &rect_position, sf::Vector2f &rect_size, sf::Color &board_color); void draw_board(); public: board_builder(sf::RenderWindow &window); }; #endif //CPSE2_BOARD_BUILDER_HPP
#ifndef COMMANDQUEUE_H #define COMMANDQUEUE_H #include "command.h" #include <queue> class CommandQueue { public: CommandQueue(); void push (const Command& command); Command pop (); bool isEmpty (); private: std::queue<Command> mQueue; }; #endif // COMMANDQUEUE_H
// chunk_rendering.cpp #include "chunk_rendering.h" #include "oglhelper.h" namespace leap { namespace rendering { uint16_t ChunkMesh::add_vertex(v3i8 position, BlockNormal normal, v2i8 texture) { static_assert(sizeof(BlockVertex) == sizeof(std::byte) * 6, "BlockVertex is expected to be 6 bytes!"); vertices.emplace_back(position, normal, texture); return static_cast<uint16_t>(vertices.size() - 1); } uint16_t ChunkMesh::add_triangle(uint16_t a, uint16_t b, uint16_t c) { static_assert(sizeof(Triangle) == sizeof(uint16_t) * 3, "Triangle is expected to be 6 bytes!"); triangles.emplace_back(a, b, c); return static_cast<uint16_t>(triangles.size() - 1); } ChunkVertexArray ChunkVertexArray::from_mesh(const ChunkMesh& mesh) { ChunkVertexArray va; glGenVertexArrays(1, &va.vao); glGenBuffers(1, &va.vbo); glGenBuffers(1, &va.ebo); glBindVertexArray(va.vao); glBindBuffer(GL_ARRAY_BUFFER, va.vbo); glBufferData(GL_ARRAY_BUFFER, mesh.vertices.size() * sizeof(BlockVertex), mesh.vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_BYTE, GL_FALSE, sizeof(BlockVertex), reinterpret_cast<GLvoid*>(offsetof(BlockVertex, position))); glEnableVertexAttribArray(1); glVertexAttribIPointer(1, 1, GL_BYTE, sizeof(BlockVertex), reinterpret_cast<GLvoid*>(offsetof(BlockVertex, normal))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_BYTE, GL_FALSE, sizeof(BlockVertex), reinterpret_cast<GLvoid*>(offsetof(BlockVertex, texture))); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, va.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh.triangles.size() * sizeof(ChunkMesh::Triangle), mesh.triangles.data(), GL_STATIC_DRAW); glBindVertexArray(0); va.count = mesh.triangles.size() * 3; return va; } ChunkVertexArray::~ChunkVertexArray() { if (ebo > 0) { glDeleteBuffers(1, &ebo); ebo = 0; } if (vbo > 0) { glDeleteBuffers(1, &vbo); vbo = 0; } if (vao > 0) { glDeleteVertexArrays(1, &vao); vao = 0; } count = 0; } ChunkVertexArray::ChunkVertexArray(ChunkVertexArray&& c) noexcept { vao = c.vao; vbo = c.vbo; ebo = c.ebo; count = c.count; c.vao = 0; c.vbo = 0; c.ebo = 0; c.count = 0; } ChunkVertexArray& ChunkVertexArray::operator=(ChunkVertexArray&& c) noexcept { vao = c.vao; vbo = c.vbo; ebo = c.ebo; count = c.count; c.vao = 0; c.vbo = 0; c.ebo = 0; c.count = 0; return *this; } }// namespace }// namespace
/********************************************************************** *Project : EngineTask * *Author : Jorge Cásedas * *Starting date : 24/06/2020 * *Ending date : 03/07/2020 * *Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library * **********************************************************************/ #pragma once #include <MessageListener.hpp> #include <Component.hpp> #include <string> using namespace std; namespace engine { // I have to use the include above instead the forward declaration for inheritance //class MessageListener; class Entity; /// /// Component made as a simple in game object control by keyboard inputs, it is attached to Entity classes /// class PlayerMovementComponent : public MessageListener, public Component { float speed; /// /// Forward limit /// float fLimit; /// /// Backwards limit /// float bLimit; /// /// Right limit /// float rLimit; /// /// Left limit /// float lLimit; /// /// Path to the audio clip that will be played /// string soundFile; enum class Direction { Right, Left, Backwards, Forward }; public: PlayerMovementComponent(MessageBus& bus, float _speed, string _soundFile); void UseMessage(Message* message) override; /// /// Set the limits coordinates for the entity movement /// void SetMovementLimits(float forward, float backwards, float right, float left); private: /// /// Move forward /// void Forward(); /// /// Move backwards /// void BackWards(); /// /// Move right /// void Right(); /// /// Move left /// void Left(); /// /// Check if the entity is trying to move out of the given limits /// bool OutOfLimits(Direction dir, float movement); /// /// Play an audio clip, this part is commented because i havent been able to use SFML audio lib when building for the demo project, a lot of LNK2019 errors popped up, and I havent been able to solve them /// void PlayAudio(); }; }
#include "NumberObject.h" NumberObject::NumberObject() : SDLGameObject() { } void NumberObject::load( const LoaderParams* pParams ) { SDLGameObject::load( pParams ); } void NumberObject::draw() { SDLGameObject::draw(); } void NumberObject::update() { } void NumberObject::clean() { SDLGameObject::clean(); }
//this file do unittesting of function before integrate it into the project #include <iostream> #include <fstream> #include "date.h" #include "time.h" #include"Vector.h" #include "unit.h" using namespace std; //void menuOption2(Vector<WindlogType>& windlog) { // bool found = false; // int year_input, month_count = 1;//count the month of a year // cout << "enter year: "; cin >> year_input; cout << endl; // // float involved_row = 0, sum_speed = 0, sum_air_temp = 0;/*for ave calculation*/ // for (int i = 0; i < windlog.Size(); i++)//search whole dataset // { // if (windlog.at(i).d.getYear() == year_input)//found year // { // found = true; // if (month_count == windlog.at(i).d.getMonth()) {//calc month data // sum_speed = sum_speed + windlog.at(i).speed; // sum_air_temp = sum_air_temp + windlog.at(i).air_temperature; // involved_row++; // } // else if (month_count < windlog.at(i).d.getMonth()) { // if (sum_speed != 0) {//output // cout << month_to_int(month_count) << " " << year_input << ":"; // printf(" %.1fkm/h, %.2f degrees C \n", (sum_speed / involved_row), (sum_air_temp / involved_row)); // sum_speed = 0; involved_row = 0; sum_air_temp = 0;//reset value // } // else {//no data calculating // cout << month_to_int(month_count) << " " << year_input << ": No Data" << endl; // } // month_count++; // } // /*cout << month_to_int(month_count) << " " << year_input << ":"; // printf(" %.1fkm/h, %.2f degrees C \n", (sum_speed / involved_row), (sum_air_temp / involved_row)); // month_count++;*/ // } // } // if (found == false) {//year no found // cout << "Year: " << year_input << ": No Data" << endl; // } // else { // cout << (sum_speed / involved_row) << ":" << month_count << endl; // while (month_count <= 12) { // //cout << month_to_int(month_count) << " " << year_input << ":"; // printf(" %.1fkm/h, %.2f degrees C \n", (sum_speed / involved_row), (sum_air_temp / involved_row)); // month_count++; // } // } //} //void menuOption3(Vector<WindlogType>& windlog) { // Process_data(windlog, 0, 1, 0, 1, 0, false);//use windlog data, take no month input ,take year input, no speed, has solar radiation, no tempertature, no file output //} //void menuOption4(Vector<WindlogType>& windlog) { // Process_data(windlog, 0, 1, 1, 1, 1, true);//use windlog data, take no month input ,take year input, has speed, has solar radiation, has tempertature, has file output //} //int Unit_test() { // //set value into objects // //passed // // time timeobj; // date dateobj; // // cout << "test the cimpliler of buggy vccomm " << endl << endl; // timeobj.setHour(12); timeobj.setMin(04); timeobj.getHour(); // dateobj.setDay(42); dateobj.setMonth(23); dateobj.setYear(3285); // cout << "show timeobj value: " << timeobj.getHour(); cout << " " << timeobj.getMin(); // cout << "\nshow dateobj value: " << dateobj.getDay(); cout << " " << dateobj.getMonth(); cout << " " << dateobj.getYear(); // cout << endl; // timeobj.print(); // cout << endl; // dateobj.print(); // cout << "\nend..." << endl; // return 0; //} //int Unit_test2() { // //this is very useful snippet to avoid GIGO // //passed // string filename; // ifstream input; ofstream output_file; // //system("dir"); // //test small file // input.open("data/MetData_Mar01-2014-Mar01-2015-ALL.csv");// data/MetData_Mar01-2014-Mar01-2015-ALL.csv for full test. MetData-31-3.csv // input.ignore(500, '\n'); //skip 1st line, till end of line // //cout << input.peek(); // while (!input.eof()) { // string temp; // getline(input, temp, '\n'); // cout << temp << endl;// output till end of line // } // return 0; // //just ~ cat data/MetData-31-3.csv (-.-) //} //int Unit_test3() { // //this test vector function // //passed // Vector<int> intArray; // intArray.push_back(1758); // cout << intArray.getMaxLen() << endl;//expected 3 - default value // intArray.push_back(12); // cout << intArray.getMaxLen() << endl;//expected 6 - double max length // cout << " " << intArray.Size() << endl;//expect 2 // intArray.push_back(98); // intArray.push_back(1758); // cout << intArray.getMaxLen() << endl;//expected 12 - double max length // intArray.push_back(15); // cout << " " << intArray.Size() << endl;//expect 5 // intArray.push_back(98); // cout << intArray.at(4) << endl;//expect 15 or 1758 // // Vector<date> dateArr; // date dateTemp; // dateTemp.setDate(12, 7, 5673); // dateArr.push_back(dateTemp); // cout << dateArr.getMaxLen() << endl;//expected 3 - default value // dateTemp.setDate(01, 12, 1925); // dateArr.push_back(dateTemp); // cout << dateArr.getMaxLen() << endl;//expected 6 - doubled // dateTemp.setDate(27, 1, 1999); // dateArr.push_back(dateTemp); // cout << " " << dateArr.Size() << endl;//expect 3 // dateArr.at(1).print();//expect day: 1 month: 12 year: 1925 // return 0; //} // //int Unit_test4() { // //passed // Vector<WindlogType> windStructArr; // WindlogType struct1; // struct1.d.setDate(1, 2, 9021); // struct1.t.setTime(23, 54); // struct1.speed = 15; // windStructArr.push_back(struct1); // windStructArr.push_back(struct1); // struct1.d.setDate(12, 9, 431); // struct1.t.setTime(2, 35); // struct1.speed = 02; // windStructArr.push_back(struct1); // struct1.d.setDate(7, 5, 575); // struct1.t.setTime(6, 4); // struct1.speed = 0; // windStructArr.push_back(struct1); // windStructArr.push_back(struct1); // cout << " " << windStructArr.Size() << endl;//expect 5 // cout << windStructArr.getMaxLen() << endl;//expected 12 - doubled // windStructArr.push_back(struct1); // windStructArr.push_back(struct1); // cout << windStructArr.at(3).d.getYear() << endl;//expect 575 // windStructArr.at(3).t.print();//expect hour: 6 min: 4 // return 0; // // Vector <<- struct <<- date, timeObj, speed <<- primitive_input //} //int Unit_test5() { // //process, split raw string // //passed // string raw_data = "12/23/5754 16:23, 35,7,34,9.2,45,1,,\n13/3/1256 4:2,"; // string un_process_string = "12/23/5754 16:23, 35,7,34,9.2,45,1,,"; // cout << un_process_string.find("3") << endl;//get 1st orcurrence of " " -expect 4 // cout << un_process_string.substr(0, un_process_string.find("/")) << endl;//expect 12 // un_process_string = un_process_string.substr(un_process_string.find("/"), un_process_string.size());//this remove the readed part // cout << un_process_string.substr(0, un_process_string.find(",")) << endl;//expect /23/7554 16:23 // un_process_string = un_process_string.substr(un_process_string.find(","), un_process_string.size()); // // // //singleLine.substr(0, singleLine.find(","); // cout << un_process_string; // return 0; //} //previous unit testing fucntion will not work since it was originally placed in main -> moved here to clear main.cpp clutter //any fucntion after this should work since this will be for assignment 2 unit test int unit_testing_Unit_class() { unit unit_Obj_1; unit_Obj_1.print(); unit *unitptr = new unit(); unitptr->setUnit(354, 4456, 35); unitptr->print(); unitptr->setSpeed(45.36); cout<<unitptr->getSpeed(); return 0; } int test_string_find() { //test string find string str("There are two needles in this haystack with needles."); string str2("too"); size_t found = str.find(str2); if (found != std::string::npos) { std::cout << "first " + str2 + " is found at: " << found << '\n'; } else { cout << "searched " + str2 + " not found" << endl; } system("pause"); return 0; }
int sonicPin = 3; int incomingByte; long int sensor; long mm, cm, inches; void setup() { Serial.begin(9600); pinMode(sonicPin, INPUT); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } } void readSensor () { sensor = pulseIn(sonicPin, HIGH); cm = sensor/58; } void loop() { incomingByte = Serial.read(); readSensor(); if (incomingByte == 'a' && cm > 100) { Serial.write(cm); } } //int getDistance(int trigPin, int echoPin) {// returns the distance (cm) // // long duration, distance; // // digitalWrite(trigPin, HIGH); // We send a 10us pulse // delayMicroseconds(10); // digitalWrite(trigPin, LOW); // // duration = pulseIn(echoPin, HIGH, 20000); // We wait for the echo to come back, with a timeout of 20ms, which corresponds approximately to 3m // // // pulseIn will only return 0 if it timed out. (or if echoPin was already to 1, but it should not happen) // if (duration == 0) { // If we timed out // pinMode(echoPin, OUTPUT); // Then we set echo pin to output mode // digitalWrite(echoPin, LOW); // We send a LOW pulse to the echo pin // delayMicroseconds(200); // pinMode(echoPin, INPUT); // And finaly we come back to input mode // } // // distance = (duration / 2) / 29.1; // We calculate the distance (sound speed in air is aprox. 291m/s), /2 because of the pulse going and coming // // return distance; //We return the result. Here you can find a 0 if we timed out //}
#include<bits/stdc++.h> #define ll long long #define ld long double #define ull unsigned long long #define rep(x,t,n) for(ll x = t; x < n; ++x) #define repe(x,t,n) for(ll x = t; x <= n; ++x) #define dec(x,t,n) for(ll x = t; x >= n; --x) #define iter(it,x) for(auto it : x) #define nl cout<<'\n'; #define pii pair<int,int> #define pll pair<ll,ll> #define mp(x,y) make_pair(x,y) #define imax INT_MAX #define imin INT_MIN #define f first #define s second #define vvi vector<vector<int> > #define vvl vector<vector<ll> > #define so(x) sizeof(x) #define mod 1000000007 #define N 100000 using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); ll n, t, ans; cin>>t; while(t--){ ans = 0; cin>>n; ll a[n]; rep(i,0,n)cin>>a[i]; sort(a,a+n); auto it = unique(a,a+n); ans = it-a; if(a[0] == 0)ans--; cout<<ans; nl; } return 0; } //author: saket_tna
#include "treeface/misc/UniversalValue.h" #include "treeface/misc/StringCast.h" #include <treecore/MPL.h> using namespace treecore; static_assert( mpl_same_type<GLboolean, GLubyte>::value, "GLboolean is GLubyte" ); namespace treeface { bool UniversalValue::operator ==( const UniversalValue& peer ) const { if (m_type != peer.m_type) return false; switch (m_type) { case TFGL_TYPE_BOOL: return m_data.ui8 == peer.m_data.ui8; case TFGL_TYPE_BYTE: return m_data.i8 == peer.m_data.i8; case TFGL_TYPE_SHORT: return m_data.i16 == peer.m_data.i16; case TFGL_TYPE_INT: return m_data.i32 == peer.m_data.i32; case TFGL_TYPE_UNSIGNED_BYTE: return m_data.ui8 == peer.m_data.ui8; case TFGL_TYPE_UNSIGNED_SHORT: return m_data.ui16 == peer.m_data.ui16; case TFGL_TYPE_UNSIGNED_INT: return m_data.ui32 == peer.m_data.ui32; case TFGL_TYPE_FLOAT: return m_data.f32 == peer.m_data.f32; case TFGL_TYPE_DOUBLE: return m_data.f64 == peer.m_data.f64; case TFGL_TYPE_VEC2F: return m_data.vec2 == peer.m_data.vec2; case TFGL_TYPE_VEC3F: return m_data.vec3 == peer.m_data.vec3; case TFGL_TYPE_VEC4F: return m_data.vec4 == peer.m_data.vec4; //case TFGL_TYPE_MAT2F: return m_data.mat2 == peer.m_data.mat2; //case TFGL_TYPE_MAT3F: return m_data.mat3 == peer.m_data.mat3; //case TFGL_TYPE_MAT4F: return m_data.mat4 == peer.m_data.mat4; default: die("unsupported data type in UniversalValue: %x", int(m_type)); } } } // namespace treeface
#ifndef TREE_H_ #define TREE_H_ #include <cstdlib> #include <string> #include <vector> #include <iostream> #include <queue> #include <stack> #include "TreeNode.h" #define SAFE_DELETE(p) {if(p){delete p; p = 0;}} using namespace std; template <class T> class Tree { public: Tree(); ~Tree(); void displayTree(TreeNode<T> *_currentNode, size_t depth); void displayLevels(); void displayFullTree(); void setRoot(TreeNode<T> *_node); TreeNode<T> *root; private: stack<TreeNode<T>*> s; }; template <class T> Tree<T>::Tree() { } template <class T> Tree<T>::~Tree() { } template <class T> void Tree<T>::setRoot(TreeNode<T> *_node) { root = _node; } template <class T> void Tree<T>::displayTree(TreeNode<T> *_currentNode,size_t depth) { for (size_t i = 0; i < depth; i++) std::cout << " "; std::cout << "-"; std::cout << _currentNode->getData() << std::endl; for (size_t i = 0; i < _currentNode->numOfChildren(); i++) displayTree(_currentNode->getChildAt(i), depth + 1); } template <class T> void Tree<T>::displayFullTree() { } template <class T> void Tree<T>::displayLevels() { cout << endl << "Levels Display:" << endl; if (root == NULL) return; queue<TreeNode<T>*> curLevel; queue<int> level; curLevel.push(root); size_t plev = 0; level.push(plev); while (!curLevel.empty()) { //check the level first,if moved to next level, print a enter size_t clev = level.front(); level.pop(); if (plev<=clev) { plev = clev; } //pop the node TreeNode<T> *p = curLevel.front(); cout << p->getData() << " " << endl; curLevel.pop(); //push its children size_t i = 0; while (i < p->numOfChildren()) { curLevel.push(p->getChildAt(i)); level.push(clev + 1); //update children's level i++; } } } #endif
#include <benchmark/benchmark.h> #include "matrix.hpp" #include "task_3_lib.cpp" static void Rowwise_decomposition(benchmark::State &state) { int size = 5000; for (auto _: state) { state.PauseTiming(); Matrix<int>* M = new Matrix<int>(size); randomizeMatrix(*M); vector<int> V(size); randomizeVector(V); state.ResumeTiming(); MatVecMultRow(*M, V, state.range(0)); state.PauseTiming(); delete M; state.ResumeTiming(); } } static void Columnwise_decomposition(benchmark::State &state) { int size = 5000; for (auto _: state) { state.PauseTiming(); Matrix<int> M(size); randomizeMatrix(M); vector<int> V(size); randomizeVector(V); state.ResumeTiming(); MatVecMultCol(M, V, state.range(0)); } } static void Checkerboard_decomposition(benchmark::State &state) { int size = 5000; for (auto _: state) { state.PauseTiming(); Matrix<int> M(size); randomizeMatrix(M); vector<int> V(size); randomizeVector(V); state.ResumeTiming(); MatVecMultCB(M, V, state.range(0)); } } BENCHMARK(Rowwise_decomposition) ->DenseRange(1, 8) ->Iterations(10); BENCHMARK(Columnwise_decomposition) ->DenseRange(1, 8) ->Iterations(10); BENCHMARK(Checkerboard_decomposition) ->DenseRange(1, 8) ->Iterations(10); BENCHMARK_MAIN();
//阔别好久,又开始在纸上写了 //想好思路,在纸上写好后,搬到电脑上,改了几个小语法错误,然后通过了152组数据(共300多组) //然后瞬间发现了自己把题考虑简单了 //但是很快又根据忘记考虑的数据,想出了更加严谨的算法. 但是只通过了168组数据 //第二天(清明节第二天)把整个代码抄了一遍,发现还是没有逻辑上的错误,于是开始查看错误的那组数据 //还是没发现有啥错误 最后没办法,只能调试一下了 很快发现了问题所在 修改后就通过了 //通过之后发现,自己的方法其实就能解决知道,但是没考虑的特殊情况. //这又算是浪费了时间吧 严谨性还需加强 最终还是调试了. //不过大思路是没问题的 // 9 ms 64.84% class Solution { public: int findTheLow(vector<int>& height,int from,int size){ for(;(from+1)!=size&&height[from+1]<=height[from];++from); return from; } int findTheHigh(vector<int>& height,int from,int size){ for(;(from+1)!=size&&height[from+1]>=height[from];++from); return from; } int trap(vector<int>& height) { int sum = 0; int now = 0; int size = height.size(); if(size<3){ return 0; } int* high_array = new int[10000]; high_array[0]=now; int high_count=1; for(;now!=size-1;++high_count){ int low = findTheLow(height, now, size); /* if(low==size-1){ //解决了这里168变accepted return 0; } */ high_array[high_count] = findTheHigh(height, low, size); now=high_array[high_count]; } cout<<high_count; for(int low=0,high=high_count-1;low!=high;){ int standard; if(height[high_array[low]]<=height[high_array[high]]){ standard = height[high_array[low]]; for(int j=high_array[low]+1;j!=high_array[high];++j){ if(standard>height[j]){ sum+=standard-height[j]; height[j]=standard; } } int m=low+1; for(;m!=high&&height[high_array[m]]<=height[high_array[low]];++m); low=m; }else{ standard = height[high_array[high]]; for(int j=high_array[low]+1;j!=high_array[high];++j){ if(standard>height[j]){ sum+=standard-height[j]; height[j]=standard; } } int m=high-1; for(;m!=low&&height[high_array[m]]<=height[high_array[high]];--m); high=m; } } return sum; } }; //这是原来少考虑了一种情况的 /* //对 回忆一下自己的做题思路(最近每做一题就把这个粘过去) //1.先理解题 //2.确定解题思路(选择数据结构算法什么的) 确定能解决正常情况,也不用考虑太多复杂度 //3.2达到之后, 开始考虑各种解决可能遇到的奇怪情况 然后看看有没有复杂度更低的思路 class Solution { public: int findTheLow(vector<int>& height,int from,int size){ for(;(from+1)!=size&&height[from+1]<=height[from];++from); return from; } int findTheHigh(vector<int>& height,int from,int size){ for(;(from+1)!=size&&height[from+1]>=height[from];++from); return from; } int trap(vector<int>& height) { int sum = 0; int now = 0; int size = height.size(); if(size<3){ return 0; } //解决M形状 int low = findTheLow(height, now, size); int high = findTheHigh(height, low, size); if(low==now){ now=high; } while(now!=size-1){ int low = findTheLow(height, now, size); int high = findTheHigh(height, low, size); if(low==size-1){ return sum; } int lower; if(height[now]<=height[high]){ lower = height[now]; }else{ lower = height[high]; } for(int i = now+1;i!=high;++i){ if(lower>height[i]){ sum+=lower-height[i]; } } now=high; } return sum; } }; */
/* 数组 值域 rk[0~n-1] 1~n sa[1~n] 0~n-1 h[2~n] 排名i和排名i-1的后缀的最长公共前缀 h[0~1] 无意义 */ #define rep(i,a,n) for (i=a;i<n;i++) int wa[MAXN],wb[MAXN],wv[MAXN],ws[MAXN]; void da(int *r,int *sa,int n,int m=128){ int i,j,p,*x=wa,*y=wb; rep(i,0,m) ws[i]=0; rep(i,0,n) ws[x[i]=r[i]]++; rep(i,1,m) ws[i]+=ws[i-1]; for(i=n-1;i>=0;i--)sa[--ws[x[i]]]=i; for(j=1,p=1;p<n;j*=2,m=p){ for(p=0,i=n-j;i<n;i++)y[p++]=i; rep(i,0,n) if(sa[i]>=j)y[p++]=sa[i]-j; rep(i,0,n)wv[i]=x[y[i]]; rep(i,0,m)ws[i]=0; rep(i,0,n)ws[wv[i]]++; rep(i,1,m)ws[i]+=ws[i-1]; for(i=n-1;i>=0;i--)sa[--ws[wv[i]]]=y[i]; for(swap(x,y),p=1,x[sa[0]]=0,i=1;i<n;i++) x[sa[i]]= (y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+j]==y[sa[i]+j])?p-1:p++; } } int rk[MAXN],h[MAXN]; void geth(int *r,int *sa,int n){ int i,j,k=0; for(i=1;i<=n;i++) rk[sa[i]]=i; for(i=0;i<n;h[rk[i++]]=k) for(k?k--:0,j=sa[rk[i]-1];r[i+k]==r[j+k];k++); }
// Example 1_1 : Hello world (sort of) // Created by Oleksiy Grechnyev 2020 // This is a comment /* This is also a comment */ // Include the header file iostream (needed for file Input/Output) // This is NOT called 'import' or 'add library' !!! #include <iostream> /* The main() function is the program entry point it can also be declared as main(int argc, char **argv) returns int value, 0 for correct exit, 1 for error */ int main(){ // cout (standard output stream) and // endl (End of line) are members of namespace std // They are defined in the header iostream std::cout << "Carthago delenda est." << std::endl; // Return 0 = OK return 0; }
#include <iostream> #include <string> const int ArSize = 10; using namespace std; void strcount(const string input); int main() { string input; cout << "Please enter a line:\n"; getline(cin, input); while (input != "") { strcount(input); cout << "Please enter line (empty line to quit): " << endl; getline(cin, input); } cout << "Bye!" << endl; return 0; } void strcount(const string input) { using namespace std; static int total = 0; int count = input.length(); cout << "\"" << input << "\" contains "; total += count; cout << count << " characters" << endl; cout << total << " characters" << endl; }
//知识点:拓扑排序,拓扑序DP /* 题目要求: 求 1~n 之间的最长路 由于题目给出的图有向且无环 并且对于1~i的最短路, 有多条路径可以选择 所以可以进行 拓扑序DP 先将 拓扑序在1之前的点去除 并将他们出边上的点的入度-- 再从1开始进行拓扑排序DP */ #include<cstdio> #include<queue> #include<algorithm> #include<ctype.h> #include<cstring> const int MARX = 1510; //============================================================= struct edge { int u,v,w,ne; }e[50010]; int n,m,num , head[MARX],in[MARX]; long long f[MARX];//f[i]表示 1到i点的最长距离 //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } inline void add(int u,int v,int w)//加边 { e[++num].u=u,e[num].v=v,e[num].w=w; e[num].ne=head[u],head[u]=num; } void prepare()//输入并初始化 { memset(f,-1,sizeof(f)); n=read(),m=read(); for(int i=1;i<=m;i++) { int u=read(),v=read(),w=read(); add(u,v,w); in[v]++;//入度++ } } void topsort()//拓扑排序 { std::queue <int> q; for(int i=1;i<=n;i++)//找到入度为0的点 if(!in[i] && i!=1) q.push(i); //去除拓扑序在1之前的点 for(int u=q.front();!q.empty();q.pop(),u=q.front()) for(int i=head[u],v=e[i].v;i;i=e[i].ne,v=e[i].v) { in[v]--; if(!in[v]) q.push(v); } q.push(1);f[1]=0;//初始化 ,从1开始DP for(int u=q.front();!q.empty();q.pop(),u=q.front()) for(int i=head[u],v=e[i].v;i;i=e[i].ne,v=e[i].v) { f[v]=std::max(f[v],f[u]+e[i].w);//更新1到v点的最长距离 in[v]--; if(!in[v]) q.push(v); } } //============================================================= signed main() { prepare(); topsort(); printf("%lld",f[n]); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- ** ** Copyright (C) 2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef ESUTILS_SYNCIF_SUPPORT #include "modules/ecmascript_utils/essyncif.h" #include "modules/ecmascript_utils/esasyncif.h" #include "modules/ecmascript_utils/esthread.h" #include "modules/ecmascript_utils/essched.h" #ifndef MESSAGELOOP_RUNSLICE_SUPPORT # error "MESSAGELOOP_RUNSLICE_SUPPORT is required for ES_SyncInterface support." #endif // MESSAGELOOP_RUNSLICE_SUPPORT class ES_SyncAsyncCallback : public ES_AsyncCallback { protected: BOOL finished, terminated; ES_SyncInterface::Callback *callback; OP_STATUS status; public: ES_SyncAsyncCallback(ES_SyncInterface::Callback *callback) : finished(FALSE), terminated(FALSE), callback(callback), status(OpStatus::OK) { OpStatus::Ignore(status); } virtual OP_STATUS HandleCallback(ES_AsyncOperation operation, ES_AsyncStatus async_status, const ES_Value &result) { finished = TRUE; if (terminated) { ES_SyncAsyncCallback *cb = this; OP_DELETE(cb); } else if (callback) { ES_SyncInterface::Callback::Status sync_status = ES_SyncInterface::Callback::ESSYNC_STATUS_SUCCESS; switch (async_status) { case ES_ASYNC_FAILURE: sync_status = ES_SyncInterface::Callback::ESSYNC_STATUS_FAILURE; break; case ES_ASYNC_EXCEPTION: sync_status = ES_SyncInterface::Callback::ESSYNC_STATUS_EXCEPTION; break; case ES_ASYNC_NO_MEMORY: sync_status = ES_SyncInterface::Callback::ESSYNC_STATUS_NO_MEMORY; break; case ES_ASYNC_CANCELLED: sync_status = ES_SyncInterface::Callback::ESSYNC_STATUS_CANCELLED; break; } status = callback->HandleCallback(sync_status, result); } else switch (async_status) { case ES_ASYNC_FAILURE: case ES_ASYNC_EXCEPTION: case ES_ASYNC_CANCELLED: status = OpStatus::ERR; break; case ES_ASYNC_NO_MEMORY: status = OpStatus::ERR_NO_MEMORY; break; } return OpStatus::OK; } BOOL IsFinished() { return finished; } void Terminate() { terminated = TRUE; if (finished) { ES_SyncAsyncCallback *cb = this; OP_DELETE(cb); } } OP_STATUS GetStatus() { return status; } }; #ifdef ESUTILS_ES_ENVIRONMENT_SUPPORT # include "modules/ecmascript_utils/esenvironment.h" ES_SyncInterface::ES_SyncInterface(ES_Environment *environment) : runtime(environment->GetRuntime()), asyncif(environment->GetAsyncInterface()) { } #endif // ESUTILS_ES_ENVIRONMENT_SUPPORT ES_SyncInterface::ES_SyncInterface(ES_Runtime *runtime, ES_AsyncInterface *asyncif) : runtime(runtime), asyncif(asyncif) { } class ES_SyncRunInProgress : public ES_ThreadListener { public: ES_SyncRunInProgress(ES_Thread *thread) : previous(g_opera->ecmascript_utils_module.sync_run_in_progress), thread(thread) { g_opera->ecmascript_utils_module.sync_run_in_progress = this; thread->AddListener(this); } ~ES_SyncRunInProgress() { g_opera->ecmascript_utils_module.sync_run_in_progress = previous; } virtual OP_STATUS Signal(ES_Thread *, ES_ThreadSignal signal) { switch (signal) { case ES_SIGNAL_FINISHED: case ES_SIGNAL_FAILED: case ES_SIGNAL_CANCELLED: ES_ThreadListener::Remove(); thread = NULL; } return OpStatus::OK; } static ES_Thread *GetInterruptThread() { ES_SyncRunInProgress *in_progress = g_opera->ecmascript_utils_module.sync_run_in_progress; while (in_progress && !in_progress->thread) in_progress = in_progress->previous; return in_progress ? in_progress->thread : NULL; } private: ES_SyncRunInProgress *previous; ES_Thread *thread; }; static OP_STATUS ES_SyncRun(ES_SyncAsyncCallback &callback, BOOL allow_nested_message_loop, unsigned timeslice, ES_Thread *thread) { OP_NEW_DBG("ES_SyncRun", "es_utils"); ES_SyncRunInProgress in_progress(thread); if (timeslice == 0) timeslice = ESUTILS_SYNC_TIMESLICE_LENGTH; ES_ThreadScheduler* scheduler = thread->GetScheduler(); BOOL leave_thread_alive = allow_nested_message_loop; OP_STATUS status = scheduler->ExecuteThread(thread, timeslice, leave_thread_alive); if (OpStatus::IsError(status)) { OP_DBG(("ExecuteThread failed so syncrun terminated")); callback.Terminate(); return status; } if (!callback.IsFinished()) { OP_ASSERT(allow_nested_message_loop); OP_DBG(("Thread couldn't complete so entering nested message loop")); OP_STATUS status; thread->SetIsSyncThread(); // Make the scheduler (should really be all schedulers) think it's // not active in case it's active BOOL was_active = scheduler->IsActive(); if (was_active) scheduler->PushNestedActivation(); do if (OpStatus::IsError(status = g_opera->RequestRunSlice())) { callback.Terminate(); break; } while (!callback.IsFinished()); thread = NULL; // Is probably deleted if (was_active) scheduler->PopNestedActivation(); return status; } else { if (allow_nested_message_loop) OP_DBG(("Able to complete thread without entering nested message loop")); else OP_DBG(("Thread could complete directly")); } return OpStatus::OK; } ES_SyncInterface::EvalData::EvalData() : program(NULL), program_array(NULL), program_array_length(0), scope_chain(NULL), scope_chain_length(0), this_object(NULL), interrupt_thread(NULL), want_exceptions(FALSE), want_string_result(FALSE), allow_nested_message_loop(TRUE), max_timeslice(0) { } OP_STATUS ES_SyncInterface::Eval(const EvalData &data, Callback *callback) { OP_ASSERT(data.program || data.program_array); ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; ES_ProgramText *program_array, program_array_single; int program_array_length; if (data.program) { program_array_single.program_text = data.program; program_array_single.program_text_length = uni_strlen(data.program); program_array = &program_array_single; program_array_length = 1; } else { program_array = data.program_array; program_array_length = data.program_array_length; } if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status = asyncif->Eval(program_array, program_array_length, data.scope_chain, data.scope_chain_length, async_callback, interrupt_thread, data.this_object); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } asyncif->GetLastStartedThread()->SetIsSoftInterrupt(); RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } ES_SyncInterface::CallData::CallData() : this_object(NULL), function(NULL), method(NULL), arguments(NULL), arguments_count(0), interrupt_thread(NULL), want_exceptions(FALSE), want_string_result(FALSE), allow_nested_message_loop(TRUE), max_timeslice(0) { } OP_STATUS ES_SyncInterface::Call(const CallData &data, Callback *callback) { OP_ASSERT(data.this_object && data.method || data.function); ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status; if (data.function) status = asyncif->CallFunction(data.function, data.this_object, data.arguments_count, data.arguments, async_callback, interrupt_thread); else status = asyncif->CallMethod(data.this_object, data.method, data.arguments_count, data.arguments, async_callback, interrupt_thread); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } #ifdef ESUTILS_SYNCIF_PROPERTIES_SUPPORT ES_SyncInterface::SlotData::SlotData() : object(NULL), name(NULL), index(0), interrupt_thread(NULL), want_exceptions(FALSE), want_string_result(FALSE), allow_nested_message_loop(TRUE), max_timeslice(0) { } OP_STATUS ES_SyncInterface::GetSlot(const SlotData &data, Callback *callback) { ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; ES_Object *object = data.object; if (!object) object = (ES_Object *) runtime->GetGlobalObject(); if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status; if (data.name) status = asyncif->GetSlot(object, data.name, async_callback, interrupt_thread); else status = asyncif->GetSlot(object, data.index, async_callback, interrupt_thread); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } OP_STATUS ES_SyncInterface::SetSlot(const SlotData &data, const ES_Value &value, Callback *callback) { ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; ES_Object *object = data.object; if (!object) object = (ES_Object *) runtime->GetGlobalObject(); if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status; if (data.name) status = asyncif->SetSlot(object, data.name, value, async_callback, interrupt_thread); else status = asyncif->SetSlot(object, data.index, value, async_callback, interrupt_thread); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } OP_STATUS ES_SyncInterface::RemoveSlot(const SlotData &data, Callback *callback) { ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; ES_Object *object = data.object; if (!object) object = (ES_Object *) runtime->GetGlobalObject(); if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status; if (data.name) status = asyncif->RemoveSlot(object, data.name, async_callback, interrupt_thread); else status = asyncif->RemoveSlot(object, data.index, async_callback, interrupt_thread); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } OP_STATUS ES_SyncInterface::HasSlot(const SlotData &data, Callback *callback) { ES_SyncAsyncCallback *async_callback = OP_NEW(ES_SyncAsyncCallback, (callback)); if (!async_callback) return OpStatus::ERR_NO_MEMORY; ES_Object *object = data.object; if (!object) object = (ES_Object *) runtime->GetGlobalObject(); if (data.want_exceptions) asyncif->SetWantExceptions(); if (data.want_string_result) asyncif->SetWantStringResult(); ES_Thread *interrupt_thread = data.interrupt_thread; if (!interrupt_thread) interrupt_thread = ES_SyncRunInProgress::GetInterruptThread(); OP_STATUS status; if (data.name) status = asyncif->HasSlot(object, data.name, async_callback, interrupt_thread); else status = asyncif->HasSlot(object, data.index, async_callback, interrupt_thread); if (OpStatus::IsError(status)) { OP_DELETE(async_callback); return status; } RETURN_IF_ERROR(ES_SyncRun(*async_callback, data.allow_nested_message_loop, data.max_timeslice, asyncif->GetLastStartedThread())); status = async_callback->GetStatus(); OP_ASSERT(async_callback->IsFinished()); OP_DELETE(async_callback); return status; } #endif // ESUTILS_SYNCIF_PROPERTIES_SUPPORT #endif // ESUTILS_SYNCIF_SUPPORT
/***************************************************************************************************************** * File Name : segregateEvenOddNumbers.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page06\segregateEvenOddNumbers.h * Created on : Jan 6, 2014 :: 8:27:14 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef SEGREGATEEVENODDNUMBERS_H_ #define SEGREGATEEVENODDNUMBERS_H_ void segregateEvenOddNumbersON2(vector<int> userInput){ if(userInput.size() == 0 || userInput.size() == 1){ return; } unsigned int outerCounter,innerCounter; int temp; bool isEvenFound = false; for(outerCounter = 0;outerCounter < userInput.size();outerCounter++){ if(userInput[outerCounter]%2 != 0){ isEvenFound = false; for(innerCounter = 0;innerCounter < userInput.size();innerCounter++){ if(userInput[innerCounter] % 2 == 0){ isEvenFound = true; break; } } temp = userInput[outerCounter]; userInput[outerCounter] = userInput[innerCounter]; userInput[innerCounter] = temp; } } } void segregateEvenOddNumbersONAuxSpace(vector<int> userInput){ if(userInput.size() == 0 || userInput.size() == 1){ return; } queue<int> oddBucket,evenBucket; for(unsigned int counter = 0;counter < userInput.size();counter++){ if(userInput[counter]%2 == 0){ oddBucket.push(userInput[counter]); }else{ evenBucket.push(userInput[counter]); } } unsigned int counter = 0; while(!oddBucket.empty()){ userInput[counter++] = oddBucket.front(); oddBucket.pop(); } while(!evenBucket.empty()){ userInput[counter++] = evenBucket.front(); evenBucket.pop(); } } void segregateEvenOddNumbersON(vector<int> userInput){ if(userInput.size() == 0){ return; } unsigned int frontCrawler = 0,backCrawler = userInput.size()-1; int temp; while(frontCrawler < backCrawler){ while(userInput[frontCrawler]%2 == 1){ frontCrawler++; } while(userInput[backCrawler]%2 == 0 && frontCrawler < backCrawler){ backCrawler--; } if(frontCrawler < backCrawler){ temp = userInput[frontCrawler]; userInput[frontCrawler] = userInput[backCrawler]; userInput[backCrawler] = temp; } } } #endif /* SEGREGATEEVENODDNUMBERS_H_ */ /************************************************* End code *******************************************************/
template<typename T> class MyVector { T *v = nullptr ; int sz = 0; public: MyVector() {} MyVector(int i) : sz{i}, v{new T[i]} {} T &operator[](int i) { return v[i]; } };
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <cstdint> namespace common { namespace console { enum class Color : uint8_t { Default, Blue, Green, Red, Yellow, White, Cyan, Magenta, BrightBlue, BrightGreen, BrightRed, BrightYellow, BrightWhite, BrightCyan, BrightMagenta }; void setTextColor(Color color); bool isConsoleTty(); }}
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define REP(i,n) for(int i=0; i<n; i++) #define REP_R(i,n,m) for(int i=m; i<n; i++) #define SMAX 50 string miss_match = "UNRESTORABLE"; int main() { string S, T; cin >> S; cin >> T; if (T.size() > S.size()) { cout << miss_match << endl; return 0; } int pos = 100; // 高々, ( |S| - |T| + 1 ) 通り // 候補を全て考える. 候補が複数ある場合, できるだけ後ろのものを採用. REP(cand, S.size() - T.size() + 1) { int count = 0; for (int index = cand; index < cand + T.size(); index++) { if (S[index] != '?' && S[index] != T[count]) { break; } count++; if (count == T.size()) { pos = cand; } } } if (pos == 100) { cout << miss_match << endl; } else { int j = 0; // pos以降を文字列Tで埋める for (int i = pos; i < pos + T.size(); i++) { S[i] = T[j]; ++j; } // '?'を'a'で埋める REP(i,S.size()) { if (S[i] == '?') S[i] = 'a'; } cout << S << endl; } return 0; }
// Datastructures.hh #ifndef DATASTRUCTURES_HH #define DATASTRUCTURES_HH #include <string> #include <vector> #include <utility> #include <limits> #include <set> #include <map> #include <unordered_map> // Type for town IDs using TownID = std::string; struct TownData { TownData() {} TownData(const TownID& nID, const std::string& nName, const int& nX, const int& nY, const int& nTax) { id = nID; name = nName; x = nX; y = nY; tax = nTax; } TownID id; std::string name; int x; int y; int tax; TownID master; std::vector<TownID> vassal; std::set<TownID> connections; }; class revPriority { public: bool operator() (const TownID& town1, const TownID& town2) const { return town1 > town2; } }; //struct weightedSort //{ // bool operator () (const std::pair<std::pair<TownID, TownID>, int>& road1, // const std::pair<std::pair<TownID, TownID>, int>& road2) { // return road1.second < road2.second; // } //} weightedObject; inline bool roadSort(const std::pair<std::pair<TownID, TownID>, int>& road1, const std::pair<std::pair<TownID, TownID>, int>& road2) { return road1.second < road2.second; } // Return value for cases where required town was not found TownID const NO_ID = "----------"; // Return value for cases where integer values were not found int const NO_VALUE = std::numeric_limits<int>::min(); // Return value for cases where name values were not found std::string const NO_NAME = "-- unknown --"; // Type for a coordinate (x, y) using Coord = std::pair<int, int>; // Return value for cases where coordinates were not found Coord const NO_COORD{NO_VALUE, NO_VALUE}; // Type for distance using Dist = int; // Return value for cases where distance is unknown Dist const NO_DIST = NO_VALUE; class Datastructures { public: Datastructures(); ~Datastructures(); // Estimate of performance: O(1) // Short rationale for estimate: size of a vector is a constant time operation. unsigned int size(); // Estimate of performance: O(n) // Short rationale for estimate: clear operation in maps and vectors are linear void clear(); // Estimate of performance: O(1) on average and O(n) in worst case // Short rationale for estimate: unordered maps have an average find and access // of constant time while their worst case would be linear in size. std::string get_name(TownID id); // Estimate of performance: O(1) on average and O(n) in worst case // Short rationale for estimate: unordered maps have an average find and access // of constant time while their worst case would be linear in size. Coord get_coordinates(TownID id); // Estimate of performance: O(1) on average and O(n) in worst case // Short rationale for estimate: unordered maps have an average find and access // of constant time while their worst case would be linear in size. int get_tax(TownID id); // Estimate of performance: O(n) // Short rationale for estimate: unordered maps have an average find and access // of constant time while their worst case would be linear in size. The vassals // are always maintained in a sorted fashion so no sorting required. std::vector<TownID> get_vassals(TownID id); // Estimate of performance: O(n) // Short rationale for estimate: Just returns a vector. std::vector<TownID> all_towns(); // Estimate of performance: O(logn) on average, O(n) in worst case // Short rationale for estimate: Adding to maps are logarthmic and adding to // unordered maps are linear in worst case. bool add_town(TownID id, std::string const& name, int x, int y, int tax); // Estimate of performance: O(n) // Short rationale for estimate: Iterating through the alphamap is a linear // operation. bool change_town_name(TownID id, std::string const& newname); // Estimate of performance: O(n) // Short rationale for estimate: Returns vector if present, else makes one by // iterating through the map which is already sorted. std::vector<TownID> towns_alphabetically(); // Estimate of performance: O(n) // Short rationale for estimate: Returns vector if present, else makes one by // iterating through the map which is already sorted. std::vector<TownID> towns_distance_increasing(); // Estimate of performance: O(nlogn), O(n) if low number of towns with such name // Short rationale for estimate: If the number of towns with the said name is high, // the towns get added in a vector and are sorted. Which results in a O(nlogn) // situation where n is the number of towns of such name. It is logarthmic otherwise. // but returning a vector is linear, so linear in the end. std::vector<TownID> find_towns(std::string const& name); // Estimate of performance: O(n), O(1) if sorted order available // Short rationale for estimate: If a sorted list is not available, costs O(n), // but O(1) if there is a sorted list that is maintained. A sorted list is formed // once a sort function is called atleast once and no addition is made. TownID min_distance(); // Estimate of performance: O(n), O(1) if sorted order available // Short rationale for estimate: If a sorted list is not available, costs O(n), // but O(1) if there is a sorted list that is maintained. A sorted list is formed // once a sort function is called atleast once and no addition is made. TownID max_distance(); // Estimate of performance: O(n), O(1) if sorted order available // Short rationale for estimate: If a sorted list is not available, costs O(n), // but O(1) if there is a sorted list that is maintained. A sorted list is formed // once a sort function is called atleast once and no addition is made. TownID nth_distance(unsigned int n); // Estimate of performance: O(n), O(logn) if low number of vassals // Short rationale for estimate: Linear as it inserts the vassals in the // vector without compromising the order. If number of vassals is low, it // goes down to a logarthmic complexity. bool add_vassalship(TownID vassalid, TownID masterid); // Estimate of performance: O(logn), O(nlogn) in the worst case // Short rationale for estimate: if all the town masters are in a single chain, // the whole towns list have to be returned, resulting in an O(nlogn) situation. std::vector<TownID> taxer_path(TownID id); // Estimate of performance: O(n) // Short rationale for estimate: Iterating through the roadmap is a linear // operation. std::vector<std::pair<TownID, TownID>> all_roads(); // Estimate of performance: O(n) // Short rationale for estimate: Returns by iterating though a vector in the main map. std::vector<TownID> get_roads_from(TownID id); // Estimate of performance: O(logn) // Short rationale for estimate: Adding to maps are logarthmic bool add_road(TownID town1, TownID town2); // Estimate of performance: O(n) // Short rationale for estimate: erasing from vector is linear, map is logarithmic bool remove_road(TownID town1, TownID town2); // Estimate of performance: O(n) // Short rationale for estimate: Clearing vectors and maps are linear void clear_roads(); // Estimate of performance: O(V + E) // Short rationale for estimate: BFS is used to find a route, and it has a complexity of // V + E where V is the number of vertices and E is the number of edges. std::vector<TownID> any_route(TownID fromid, TownID toid); // Non-compulsory operations // Estimate of performance: O(n), O(nlogn) in the worst case // Short rationale for estimate: If in the odd case that the town has a master // and also a large amount of vassals, they are pushed to a vector and sorted bool remove_town(TownID id); // Estimate of performance: O(nlogn) // Short rationale for estimate: A list is made from scratch by inserting n // elements in a map. std::vector<TownID> towns_distance_increasing_from(int x, int y); // Estimate of performance: O(nlogn) // Short rationale for estimate: Depends on the amount of vassals and their vassals // But the functionality should be O(nlogn) on average. std::vector<TownID> longest_vassal_path(TownID id); // Estimate of performance: O(nlogn) // Short rationale for estimate: Depends on the amount of vassals and their vassals // But the functionality should be O(nlogn) on average. int total_net_tax(TownID id); // Estimate of performance: O(V + E) // Short rationale for estimate: BFS is used to find a route, and it has a complexity of // V + E where V is the number of vertices and E is the number of edges. std::vector<TownID> least_towns_route(TownID fromid, TownID toid); // Estimate of performance: O(E logV) // Short rationale for estimate: Dijkstra's algorithm was used to find the shortest path. But, // since we did not use a Matrix and used adjacent list to traverse the graph through BFS, the // complexity of the algorithm was reduced to O(E log V) instead of O(n^2) std::vector<TownID> shortest_route(TownID fromid, TownID toid); // Estimate of performance: O(V + E) // Short rationale for estimate: DFS is used to find the cycle, and it has a complexity of // V + E where V is the number of vertices and E is the number of edges. std::vector<TownID> road_cycle_route(TownID startid); // Estimate of performance: O(E logV) // Short rationale for estimate: Kruskal's algorithm was implemented to create a minimum spanning // tree, and since this operation has a higher complexity than the other operations (which are // linear), the final complexity is O(E logV) Dist trim_road_network(); private: // Add stuff needed for your class implementation here bool alphalistUpdated = false; bool distlistUpdated = false; unsigned int dist; int tempo = 0; int tempo2 = 0; TownID tempID; TownID start; std::map<TownID, std::set<TownID>> roadmap; std::unordered_map<TownID, TownData> townmap; std::multimap<std::string, TownID> alphamap; std::multimap<int, TownID> distmap; std::vector<std::vector<TownID>> idception; std::vector<TownID> alphalist; std::vector<TownID> distlist; std::vector<TownID> vlist; std::unordered_map<TownID, TownData>::iterator mapIter; std::multimap<std::string, TownID>::iterator iter; std::multimap<int, TownID>::iterator iter2; std::map<TownID, TownID> parentT; int counter; void add_vassal_vectors(const TownID &id); int vassal_taxes(const TownID &id); TownID findSet(const TownID& town); void UnionSet(const TownID& town1, const TownID& town2); bool isCyclic(TownID id, std::map<TownID, bool>& visited, TownID parent, TownID *routeUtil); }; #endif // DATASTRUCTURES_HH
#include "CGuestBinding.h" #include "json/json.h" #include "Logger.h" #include "StrFunc.h" #include "../threadres.h" #include "RedisAccess.h" #include "Helper.h" #include <algorithm> #include "md5.h" #include "threadres.h" #include "RedisLogic.h" #include "SqlLogic.h" namespace { static std::vector<int> errorCode = {-1,-2,-3,-4,-5}; static std::vector<std::string> error_string = { "参数错误", "手机号,用户名或密码为空", "用户名不合法", "用户名已存在或该手机已经绑定过", "验证码错误" }; std::string getErrorMsg(int ec) { auto it = std::find(errorCode.begin(), errorCode.end(), ec); size_t index = std::distance(errorCode.begin(), it); if (index >= error_string.size()) { return ""; } return error_string[index]; } int errorMsg(int code, Json::Value& info, Json::FastWriter& writer, HttpResult& out) { out["msg"] = getErrorMsg(code); out["result"] = code; // out = writer.write(info); return code; } } int CGuestBinding::do_request(const Json::Value& root, char *client_ip, HttpResult& out) { Json::FastWriter jWriter; //Json::Value ret; out["result"] = 0; int nMid, sid, type, idcode; //nSitemId, // std::string strSiteMid; std::string username, phoneno, password; try { nMid = root["mid"].asInt(); sid = root["sid"].asInt(); // nSitemId = Json::SafeConverToInt32(root["param"]["sitemid"]); // strSiteMid = root["param"]["sitemid"].asString(); out["type"] = type = root["param"]["type"].asInt(); idcode = root["param"]["idcode"].asInt(); out["phoneno"] = phoneno = root["param"]["phoneno"].asString(); out["username"] = username = Helper::filterInput(Helper::strtolower(root["param"]["username"].asString().c_str())); out["password"] = password = Helper::trim(root["param"]["password"].asString().c_str()); } catch (...) { out["msg"] = "参数不正确"; //out = jWriter.write(ret); return status_ok; } if (!isMobile(phoneno)) phoneno = ""; out["rewardMoney"] = 0; out["money"] = 0; if (nMid < 1 || (sid != 100 && sid != 102)) //nSitemId < 1 || { errorMsg(-1, out, jWriter, out); return status_ok; } CAutoUserDoing userDoing(nMid); if (userDoing.IsDoing()) { errorMsg(-1, out, jWriter, out); return status_ok; } int rewardMoney = 0; bool flag; if (type == 1) //游客绑定账号 { //先判断是否手机号 if (isMobile(username)) { errorMsg(-3, out, jWriter, out); return status_ok; } if (username.empty() || password.empty()) { errorMsg(-2, out, jWriter, out); return status_ok; } if (!Helper::isUsername(username.c_str())) { errorMsg(-3, out, jWriter, out); return status_ok; } if (!ThreadResource::getInstance().getRedisConnMgr()->account()->SADD("USN", username.c_str())) { errorMsg(-4, out, jWriter, out); return status_ok; } flag = SqlLogic::guestBindAccount(username, password, nMid); } else if (type == 2) //游客绑定手机号 { if (phoneno.empty() || password.empty()) { errorMsg(-2, out, jWriter, out); return status_ok; } int svr_idcode = RedisLogic::getServerIdCode(phoneno); if (svr_idcode != idcode) { errorMsg(-5, out, jWriter, out); return status_ok; } if (!ThreadResource::getInstance().getRedisConnMgr()->account()->SADD("PHN", phoneno.c_str())) { errorMsg(-4, out, jWriter, out); return status_ok; } Json::Value data; data["mid"] = nMid; data["phoneno"] = phoneno; data["password"] = password; flag = SqlLogic::registerByPhoneNumber(data, 2); } else { LOGGER(E_LOG_ERROR) << "unknown type = " << type; errorMsg(-1, out, jWriter, out); return status_ok; } if (flag) { Json::Value gameinfo; if (!SqlLogic::getOneById(gameinfo, nMid)) { errorMsg(-1, out, jWriter, out); return status_ok; } out["rewardMoney"] = rewardMoney; out["money"] = gameinfo["money"]; out["sitemid"] = gameinfo["sitemid"]; out["result"] = 1; } out["msg"] = "绑定成功"; return status_ok; }
class Category_675 { class bulk_17Rnd_9x19_glock17 { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class bulk_15Rnd_9x19_M9SD { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; class bulk_30Rnd_9x19_MP5SD { type = "trade_items"; buy[] = {3,"ItemGoldBar"}; sell[] = {3,"ItemGoldBar"}; }; class bulk_30Rnd_556x45_StanagSD { type = "trade_items"; buy[] = {4,"ItemGoldBar"}; sell[] = {4,"ItemGoldBar"}; }; class bulk_ItemSandbag { type = "trade_items"; buy[] = {3,"ItemGoldBar10oz"}; sell[] = {3,"ItemGoldBar10oz"}; }; class bulk_ItemTankTrap { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {2,"ItemGoldBar"}; }; class bulk_ItemWire { type = "trade_items"; buy[] = {5,"ItemSilverBar10oz"}; sell[] = {5,"ItemSilverBar10oz"}; }; class bulk_PartGeneric { type = "trade_items"; buy[] = {8,"ItemGoldBar"}; sell[] = {8,"ItemGoldBar"}; }; class PartPlywoodPack { type = "trade_items"; buy[] = {2,"ItemSilverBar10oz"}; sell[] = {1,"ItemSilverBar10oz"}; }; class PartPlankPack { type = "trade_items"; buy[] = {1,"ItemSilverBar10oz"}; sell[] = {5,"ItemSilverBar"}; }; class CinderBlocks { type = "trade_items"; buy[] = {1,"ItemGoldBar10oz"}; sell[] = {5,"ItemGoldBar"}; }; class MortarBucket { type = "trade_items"; buy[] = {1,"ItemGoldBar10oz"}; sell[] = {5,"ItemGoldBar"}; }; class ItemFuelBarrelEmpty { type = "trade_items"; buy[] = {1,"ItemGoldBar"}; sell[] = {5,"ItemSilverBar10oz"}; }; class ItemFuelBarrel { type = "trade_items"; buy[] = {2,"ItemGoldBar"}; sell[] = {1,"ItemGoldBar"}; }; }; class Category_636 { duplicate = 675; }; class Category_555 { duplicate = 675; };
#include <string> #include "gwmessage/GWSensorDataConfirm.h" using namespace std; using namespace Poco; using namespace BeeeOn; GWSensorDataConfirm::GWSensorDataConfirm(): GWMessage(GWMessageType::SENSOR_DATA_CONFIRM) { } GWSensorDataConfirm::GWSensorDataConfirm(const JSON::Object::Ptr object): GWMessage(object) { }
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> #include <memory> #include <valarray> #include <numeric> #include <functional> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int k; cin >> k; string s, origin, stuck; unordered_set<char> unstucked, stucked; cin >> s; for (int i = 0; i < s.length();) { int cnt = 1; while (i + cnt < s.length() && s[i + cnt] == s[i]) cnt++; if (cnt % k != 0) unstucked.insert(s[i]); i += cnt; } for (int i = 0; i < s.length();) { if (unstucked.find(s[i]) != unstucked.end()) { origin += s[i++]; } else { int cnt = 1; while (i + cnt < s.length() && s[i + cnt] == s[i]) cnt++; origin += string(cnt / k, s[i]); if (stucked.find(s[i]) == stucked.end()) { stuck += s[i]; stucked.insert(s[i]); } i += cnt; } } cout << stuck << endl; cout << origin << endl; return 0; }
#ifndef ADRESATMENEGER_H #define ADRESATMENEGER_H #include <iostream> #include <vector> #include <windows.h> #include <sstream> #include <fstream> #include <string> #include <algorithm> #include "Adresat.h" #include "UzytkownikMenager.h" #include "PlikiZAdresatami.h" #include "MetodyPomocnicze.h" using namespace std; class AdresatMenager { const int ID_ZALOGOWANEGO_UZYTKOWNIKA; vector <Adresat> adresaci; PlikiZAdresatami plikiZAdresatami; Adresat podajDaneNowegoAdresata(); void wyswietlDaneAdresata(Adresat adresat); public: AdresatMenager(string nazwaPlikuZAdresatami, int idZalogowanegoUzytkownika): plikiZAdresatami(nazwaPlikuZAdresatami), ID_ZALOGOWANEGO_UZYTKOWNIKA(idZalogowanegoUzytkownika) { adresaci = plikiZAdresatami.wczytajAdresatowZalogowanegoUzytkownikaZPliku(ID_ZALOGOWANEGO_UZYTKOWNIKA); }; void wyswietlWszystkichAdresatow(); void wyswietlIloscWyszukanychAdresatow(int iloscAdresatow); void dodajAdresata(); void usunAdresata(); void edytujAdresata(); void zaktualizujDaneWybranegoAdresata(Adresat adresat); void wyszukajAdresatowPoImieniu(); void wyszukajAdresatowPoNazwisku(); char wybierzOpcjeZMenuEdycja(); Adresat pobierzDaneAdresata(string daneAdresataOddzielonePionowymiKreskami); string zamienDaneAdresataNaLinieZDanymiOddzielonymiPionowymiKreskami(Adresat adresat); }; #endif
#include "rdtsc_benchmark.h" #include "ut.hpp" #include <random> #include <algorithm> #include <math.h> #include <functional> #include <vector> #include "compute_steering.h" using namespace boost::ut; // provides `expect`, `""_test`, etc using namespace boost::ut::bdd; // provides `given`, `when`, `then` auto data_loader(cVector3d x, double* wp, const size_t N_wp, const double minD, const double rateG, const double maxG, const double dt, int* iwp, double* G) { *iwp=1; *G = 0.0; } int main() { double x[3] = {0,0,0}; const int N_wp = 3; double wp[2*N_wp] = {0,0,1,1,2,2}; double minD = 12.0; double rateG = 0.1; double maxG = 1.5; double dt = 1.0; int iwp = 1; double G = 0.0; int iwp_exact = 1; double G_exact = 0.0; data_loader(x, wp, N_wp, minD, rateG, maxG, dt, &iwp_exact, &G_exact); compute_steering_base(x, wp, N_wp, minD, rateG, maxG, dt, &iwp_exact, &G_exact); data_loader(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); compute_steering(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); expect(that % fabs(G - G_exact) < 1.0e-10) << "G"; expect(that % (iwp - iwp_exact) == 0 ) << "iwp"; // Initialize the benchmark struct by declaring the type of the function you want to benchmark // Benchmark<decltype(&compute_steering_base)> bench("compute_steering Benchmark"); // // data_loader(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); // bench.data_loader = data_loader; // // Add your functions to the struct, give it a name (Should describe improvements there) and yield the flops this function has to do (=work) // // First function should always be the base case you want to benchmark against! // bench.add_function(&compute_steering_base, "base", 0.0); // bench.funcFlops[0] = compute_steering_base_flops(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); // bench.funcBytes[0] = 8*compute_steering_base_memory(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); // bench.add_function(&compute_steering, "active", 0.0); // bench.funcFlops[1] = compute_steering_active_flops(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); // bench.funcBytes[1] = 8*compute_steering_active_memory(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); // // //Run the benchmark: give the inputs of your function in the same order as they are defined. // bench.run_benchmark(x, wp, N_wp, minD, rateG, maxG, dt, &iwp, &G); return 0; }
#include<iostream> #include"Node.h" #include<math.h> using namespace std; /* * Count nodes in complete binary tree */ int count(Node* root){ int lh=0,rh=0; Node* curr=root; while(curr!=NULL){ lh++; curr=curr->left; } curr=root; while(curr!=NULL){ rh++; curr=curr->right; } if(lh==rh){ return pow(2,lh)-1; } return 1+count(root->left)+count(root->right); }
#include <iostream> #include <string> #include <juce_core/juce_core.h> #include <juce_events/juce_events.h> class AsynchronousCommandlineReader : public juce::ActionBroadcaster, private juce::Timer { public: AsynchronousCommandlineReader() { } ~AsynchronousCommandlineReader() override { removeAllActionListeners(); } void start() { asynchronous_input.startThread(); startTimer(100); } void stop() { stopTimer(); asynchronous_input.stopThread(100); } void acknowledge() { asynchronous_input.acknowledge(); } void timerCallback() override { std::string line = asynchronous_input.get_line(); if (line != "") { if (line == "quit") { juce::JUCEApplicationBase::quit(); } else { sendActionMessage(juce::String(line)); } } } private: class AsynchronousInput : public juce::Thread { public: AsynchronousInput() : juce::Thread("Asynchronous Commandline Reader") {} void run() override { do { synchronousInput = ""; while (!threadShouldExit() && !acknowledged) { yield(); } acknowledged = false; while (!threadShouldExit()) { while (std::cin.peek() == std::char_traits<char>::eof()) { yield(); } std::cin.get(nextCharacter); if (nextCharacter == '\n') { acknowledged = true; break; } synchronousInput += nextCharacter; } if (threadShouldExit()) { break; } while (!threadShouldExit() && !sendOverNextLine) { yield(); } if (threadShouldExit()) { break; } inputLock.lock(); input = synchronousInput; inputLock.unlock(); sendOverNextLine = false; } while (!threadShouldExit() && synchronousInput != "quit"); std::cout << "thread quit" << std::endl; } std::string get_line() { if (sendOverNextLine) { return ""; } else { inputLock.lock(); std::string returnInput = input; inputLock.unlock(); sendOverNextLine = true; return returnInput; } } void acknowledge() { acknowledged = true; } private: std::atomic<bool> sendOverNextLine{false}; std::atomic<bool> acknowledged{true}; char nextCharacter; std::mutex inputLock; std::string synchronousInput; std::string input; }; AsynchronousInput asynchronous_input; };
#include <stdio.h> #include <iostream> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include <opencv2/calib3d/calib3d.hpp> #include "opencv2/nonfree/features2d.hpp" #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdlib.h> #include <GL/glew.h> #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #include <math.h> #include "XForm.h" #include "GLCamera.h" #include "ReadInDataSet.h" #include "dfsFolder.h" #include "Lumigraph.h" using namespace std; using namespace cv; //Globals GLCamera camera; xform xf; vector<Lumigraph> lg; static unsigned buttonstate = 0; Vec3f center(0,0,0); double size = 5.0; #define WIDTH 640 #define HEIGHT 480 #define DEBUG 0 //Display Function void redraw() { camera.setupGL(xf * center, size); glClearColor(1, 1, 1, 1); glClearDepth(1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_CULL_FACE); float* pixels = (float*) malloc(sizeof(float) * lg[0].t_width * lg[0].s_height * 3); int index = 0; glMatrixMode(GL_PROJECTION); glMultMatrixd(xf); Mat Img_ori = lg[0].DrawImage(xf); Mat Img; Size size(WIDTH,HEIGHT); resize(Img_ori,Img,size); for(int s = 0;s<HEIGHT;s++) { for(int t=0;t<WIDTH;t++) { pixels[index] = *(Img.data + Img.step[0]*s + Img.step[1]*t); pixels[index+1] = *(Img.data + Img.step[0]*s + Img.step[1]*t + 1); pixels[index+2] = *(Img.data + Img.step[0]*s + Img.step[1]*t + 2); index += 3; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawPixels(WIDTH,HEIGHT,GL_RGB,GL_UNSIGNED_BYTE,pixels); glutSwapBuffers(); glPopMatrix(); } //Mouse Function void mousemotionfunc(int x, int y) { static const Mouse::button physical_to_logical_map[] = { Mouse::NONE, Mouse::ROTATE, Mouse::MOVEXY, Mouse::MOVEZ, Mouse::MOVEZ, Mouse::MOVEXY, Mouse::MOVEXY, Mouse::MOVEXY, }; Mouse::button b = Mouse::NONE; if (buttonstate & (1 << 4)) b = Mouse::WHEELUP; else { if (buttonstate & (1 << 3)) b = Mouse::WHEELDOWN; else b = physical_to_logical_map[buttonstate & 7]; } //b = Mouse::MOVEXY; camera.mouse(x, y, b, xf * center, size, xf); if (b != Mouse::NONE) glutPostRedisplay(); } void mousebuttonfunc(int button, int state, int x, int y) { if (state == GLUT_DOWN) buttonstate |= (1 << button); else buttonstate = 0;//buttonstate &= ~(1 << button); mousemotionfunc(x, y); } void init(string in) { lg.push_back(Lumigraph(in)); } void resetview() { xf = xform::trans(0, 0, -5.0f * size) * xform::trans(-center); //camera.stopspin(); buttonstate = 0; } int main( int argc, char** argv ) { //string filepath = "C:\\HomeWork&Project\\CS684\\DataBase\\preview\\"; try { string filepath = "C:\\OpenCV_Project\\SFM_Exp\\Test\\"; string data = "Building"; int WriteTXT = 0; if(WriteTXT == 1) { string dataTXT = filepath + data + ".txt"; ofstream fout( dataTXT, ios::app); dfsFolder(filepath, fout); } ReadInImages(filepath,data); glutInitWindowPosition(100, 0); glutInitWindowSize(WIDTH,HEIGHT); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInit(&argc, argv); glutCreateWindow("Unstructured Lumigraph Viewer"); glEnable(GL_TEXTURE_2D); glutDisplayFunc(redraw); glutMouseFunc(mousebuttonfunc); glutMotionFunc(mousemotionfunc); resetview(); string filename = filepath + data; init(filename.c_str()); glutMainLoop(); } catch(cv::Exception & e) { cout<<e.msg<<endl; } }
namespace iberbar { inline CColor4F::CColor4F() : b( 0.0f ), g( 0.0f ), r( 0.0f ), a( 0.0f ) { } inline CColor4F::CColor4F( const CColor4B& color ) : b( (float)( color.b ) / 255.0f ) , g( (float)( color.g ) / 255.0f ) , r( (float)( color.r ) / 255.0f ) , a( (float)( color.a ) / 255.0f ) { } inline CColor4F::CColor4F( const uint32& val ) : b( (float)( GetColorB( val ) ) / 255.0f ) , g( (float)( GetColorG( val ) ) / 255.0f ) , r( (float)( GetColorR( val ) ) / 255.0f ) , a( (float)( GetColorA( val ) ) / 255.0f ) { } inline CColor4F::CColor4F( float _a, float _r, float _g, float _b ) : b( _b ) , g( _g ) , r( _r ) , a( _a ) { } inline CColor4F::CColor4F( float _r, float _g, float _b ) : b( _b ) , g( _g ) , r( _r ) , a( 1.0f ) { } inline CColor4F::CColor4F( const float* pValues ) throw( ) : b( pValues[ 0 ] ) , g( pValues[ 1 ] ) , r( pValues[ 2 ] ) , a( pValues[ 3 ] ) { } inline CColor4F::operator float* ( ) { return value; } inline CColor4F::operator const float* () const { return value; } inline CColor4F::operator uint32 () const { return MakeColorARGB( (uint32)( a*255.0f ), (uint32)( r*255.0f ), (uint32)( g*255.0f ), (uint32)( b*255.0f ) ); } inline CColor4B::CColor4B() : b(0) , g(0) , r(0) , a(0) { } inline CColor4B::CColor4B( const CColor4F& color ) : b( (uint8)( color.b * 255.0f ) ) , g( (uint8)( color.g * 255.0f ) ) , r( (uint8)( color.r * 255.0f ) ) , a( (uint8)( color.a * 255.0f ) ) { } inline CColor4B::CColor4B( const uint32& val ) : value32( val ) { } inline CColor4B::CColor4B( uint8 _r, uint8 _g, uint8 _b ) : b( _b ), g( _g ), r( _r ), a( 255 ) { } inline CColor4B::CColor4B( uint8 _a, uint8 _r, uint8 _g, uint8 _b ) : b( _b ), g( _g ), r( _r ), a( _a ) { } inline CColor4B::CColor4B( const uint8* p ) : b( p[0] ), g( p[1] ), r( p[2] ), a( p[3] ) { } inline CColor4B::operator uint32 () const { return value32; //return (uint32)((((r) & 0xff) << 16) | (((g) & 0xff) << 8) | (((b) & 0xff)) | (((a) & 0xff) << 24 ) ); } inline CColor4B::operator uint8* () { return value8; } inline CColor4B::operator const uint8* () const { return value8; } inline uint32 CColor4B::toRGBA() const { return (uint32)( ( ( (r)&0xff )<<24 )|( ( (g)&0xff )<<16 )|( ( (b)&0xff )<<8 )|( (a)&0xff ) ); } }
/*! * @copyright © 2017 Universidade Federal do Amazonas. * * @brief Interface da API em C++ da classe mãe I2C. * * @file mkl_I2CPort.h * @version 1.0 * @date 07 Dezembro 2017 * * @section HARDWARES & SOFTWARES * +board FRDM-KL25Z da NXP. * +processor MKL25Z128VLK4 - ARM Cortex-M0+ * +compiler Kinetis® Design Studio IDE * +manual L25P80M48SF0RM, Rev.3, September 2012 * +revisions Versão (data): Descrição breve. * ++ 1.0 (07 Dezembro 2017): Versão inicial. * * @section AUTHORS & DEVELOPERS * +institution Universidade Federal do Amazonas * +courses Engenharia da Computação / Engenharia Elétrica * +teacher Miguel Grimm <miguelgrimm@gmail.com> * +student Versão inicial: * ++ Leticia Flores <leticia.flors@gmail.com> * ++ Matheus de Sousa Castro <matheus.sousa110@gmail.com> * ++ Stephanie Lopes <stephanielopees@gmail.com> * ++ Victoria da Silva Leite <victoria_leite@hotmail.com> * @section LICENSE * * GNU General Public License (GNU GPL) * * Este programa é um software livre; Você pode redistribuí-lo * e/ou modificá-lo de acordo com os termos do "GNU General Public * License" como publicado pela Free Software Foundation; Seja a * versão 3 da licença, ou qualquer versão posterior. * * Este programa é distribuído na esperança de que seja útil, * mas SEM QUALQUER GARANTIA; Sem a garantia implícita de * COMERCIALIZAÇÃO OU USO PARA UM DETERMINADO PROPÓSITO. * Veja o site da "GNU General Public License" para mais detalhes. * * @htmlonly http://www.gnu.org/copyleft/gpl.html */ #ifndef C__USERS_MSCAS_DESKTOP_CPPLINT_MASTER_MKL_I2CPORT_H_ #define C__USERS_MSCAS_DESKTOP_CPPLINT_MASTER_MKL_I2CPORT_H_ #include "mkl_I2C.h" /*! * @class mkl_I2CPort_H * * @brief Classe de implementação do periférico I2C para a placa KL25Z128. * * @details Esta classe é usada para leitura ou escrita de dados de 8 bits * e usa o periférico I2C. * */ class mkl_I2CPort : public mkl_I2C { public: explicit mkl_I2CPort(i2c_Pin_t pinSCL = i2c_PTE1, i2c_Pin_t pinSDA = i2c_PTE0); /*! * Método de ajuste da velocidade de transmissão. */ void baudRate(i2c_baudRate_t speed); /*! * Métodos de configuração do I2C. */ void setSlave(uint8_t address); uint8_t getSlave(); void enableAck(); void disableAck(); /*! * Métodos comuns de Escrita e Leitura. */ i2c_Exception_t startTransmission(); i2c_Exception_t startTransmissionTo(uint8_t address); /*! * Métodos de Escrita. */ void waitTransfer(); void send8Bits(uint8_t data); void stopTransmission(); /*! * Métodos de Leitura. */ i2c_Exception_t selectReceptionMode(); i2c_Exception_t selectReceptionModeFrom(uint8_t slave); /*! * Espera a chegada do dado. */ i2c_Exception_t waitArrived(); /*! * Retorna o dado recebido. */ uint8_t receive8Bits(); /*! * Método de excessão. */ i2c_Exception_t ExceptionOcurred(); uint8_t slaveAddress; i2c_Exception_t exception; }; #endif // C__USERS_MSCAS_DESKTOP_CPPLINT_MASTER_MKL_I2CPORT_H_
#ifndef BASEPAWN_HH #define BASEPAWN_HH #include <QGraphicsPolygonItem> //#include <QGraphicsSceneMouseEvent> class basepawn : public QGraphicsPolygonItem { public: basepawn(int id); void colorPawn(); int playerId; int pawnNumber; }; #endif // BASEPAWN_HH