text
stringlengths
8
6.88M
/*The tree node has data, left child and right child class Node { int data; Node* left; Node* right; }; */ Node *lca(Node *root, int v1,int v2) { int small = v1; int large = v2; if (v1 > v2) { small = v2 ; large = v1 ; } // Write your code here. Node* res = NULL; bool LCAFound = false; Node* currentNode = root; while (!LCAFound) { if (small <= currentNode->data && large >= currentNode->data) { res= currentNode; LCAFound = true; } else if (small < currentNode->data && large < currentNode->data) { currentNode = currentNode->left; } else { currentNode = currentNode->right; } } return res; }
#include "rna_transcription.h" char transcription::to_rna(char RNA) { return RNA == 'G' ? 'C' : RNA == 'C' ? 'G' : RNA == 'T' ? 'A' : RNA == 'A' ? 'U' : '?'; } string transcription::to_rna(string RNA) { string newRNA; for (auto kv : RNA) newRNA += to_rna(kv); return newRNA; }
#include "ConnectFile.h" void ConnectFile::importDauSach(string line, ConTroDauSach &data) { data = new DauSach; string temp = ""; int n = 0; for (;line[n] != ','; n++) { temp += line[n]; } data->ISBN = temp; temp = ""; n++; for (;line[n] != ','; n++) { temp += line[n]; } data->tenSach = temp; temp = ""; n++; for (;line[n] != ','; n++) { temp += line[n]; } data->soTrang = BackEnd::convertToString(temp); temp = ""; n++; for (;line[n] != ','; n++) { temp += line[n]; } data->tacGia = temp; temp = ""; n++; for (;line[n] != ','; n++) { temp += line[n]; } data->namXuatBan = BackEnd::convertToString(temp); temp = ""; n++; for (;line[n] != ','; n++) { temp += line[n]; } data->theLoai = temp; temp = ""; n++; if (n < line.size()) { Sach sach; DanhSachLienKetDon danhSachSach; while (n < line.size()) { for (;line[n] != ','; n++) { temp += line[n]; } sach.maSach = temp; temp = ""; n++; sach.trangThai = line[n] - '0'; n++;n++; for (;line[n] != ','; n++) { temp += line[n]; } sach.viTri = temp; temp = ""; n++; danhSachSach.insert(sach); } data->dms = danhSachSach.get(); } } void ConnectFile::importDocGia(string line, TheDocGia & data) { } void ConnectFile::readFile() { if (inputFile.is_open()) { if (inputFile.peek() != EOF) { string a = ""; getline(inputFile, a); int n = BackEnd::convertToString(a); if (n != 0) { ConTroDauSach dauSach; string dsds; for (int i = 0;i < n;i++) { dsds = ""; getline(inputFile, dsds); importDauSach(dsds, dauSach); danhSachDauSach.insert(dauSach); } } if (inputFile.eof()) { string dsdg; TheDocGia theDocGia; while (!inputFile.eof()) { dsdg = ""; getline(inputFile, dsdg); importDocGia(dsdg, theDocGia); danhSachTheDocGia.insert(theDocGia); } } } } } void ConnectFile::wirteFile() { DanhSachDauSach p = danhSachDauSach.get(); outputFile << p.soLuongSach << endl; for (int i = 0;i < p.soLuongSach;i++) { outputFile << p.data[i]->ISBN << ',' << p.data[i]->tenSach << ',' << p.data[i]->soTrang << ',' << p.data[i]->tacGia << ',' << p.data[i]->namXuatBan << ',' << p.data[i]->theLoai << ','; if (p.data[i]->dms != NULL) { DSLKDSach run; for (run = p.data[i]->dms;run != NULL;run = run->next) { outputFile << run->data.maSach << ',' << run->data.trangThai << ',' << run->data.viTri << ','; } } } } MangConTroDauSach ConnectFile::getMangConTroDauSach() { return danhSachDauSach.get(); } void ConnectFile::setMangConTroDauSach(MangConTroDauSach value) { danhSachDauSach.set(value); } CayTheDocGia ConnectFile::getCayTheDocGia() { return danhSachTheDocGia.get(); } void ConnectFile::setCayTheDocGia(CayTheDocGia value) { danhSachTheDocGia.set(value); } ConnectFile::ConnectFile() { inputFile.open("data.txt", ios::in); outputFile.open("data.txt", ios::out); this->readFile(); } ConnectFile::~ConnectFile() { inputFile.close(); outputFile.close(); this->wirteFile(); }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) scanf("%lld", &n) #define scf(n) scanf("%lf", &n) #define pfl(x) printf("%lld\n",x) #define pb push_back #define fr(i,n) for (ll i=0;i<n;i++) ll mod=10000007; ll bigpow(ll x, ll e) { ll res; if (e == 0) res = 1; else if (e == 1) res = x; else { res = bigpow(x, e / 2); res = res * res; if (e % 2) res = res * x; } return res; } int main() { ll m,n,t,b,c,d,i,j,x,y,z,l,p,r; ll cnt=0,ans=0; scl(m); scl(n); ll a[n]; for(i=0; i<n; i++) { cin>>a[i]; } x=n-1; fr(i,n) { ans+=a[i]*bigpow( m, x); // cout<<a[i]<<" "<<pow( m, x)<<endl; if(x==0)x=0; else x--; } //pfl(ans); if(ans&1) cout<<"odd"<<endl; else cout<<"even"<<endl; return 0; }
#include <iostream> int main() { const int v2 = 0; int v1 = v2; int & r1 = v1; r1 = v2; r1 = 30; std::cout << "v2 = " << v2 << std::endl; //int & r3 = v2; //int null = 0, *p = (int *)null; int null = 0, *p = NULL; return 0; }
#include "gameengine.h" #include <chrono> #include <thread> #include <QCoreApplication> #include <QRandomGenerator> #include <QThread> static MyEnums::PlayerType mapUnsignedToSignType(const unsigned player) { switch (player) { case 1: return MyEnums::PlayerType::Nought; case 2: return MyEnums::PlayerType::Cross; default: return MyEnums::PlayerType::Empty; } } static unsigned mapSignTypeToUnsigned(const MyEnums::PlayerType player) { switch (player) { case MyEnums::PlayerType::Nought: return 1; case MyEnums::PlayerType::Cross: return 2; default: return 0; } } MyEnums::PlayerType GameEngine::getOpositPlayer(const MyEnums::PlayerType player) const noexcept { return player == MyEnums::PlayerType::Cross ? MyEnums::PlayerType::Nought : MyEnums::PlayerType::Cross; } bool GameEngine::isBoardFull() const noexcept { return moves.size() == 9; } void GameEngine::swapActivePlayer() noexcept { activePlayer = getOpositPlayer(activePlayer); emit playerChanged(mapSignTypeToUnsigned(activePlayer)); } void GameEngine::checkGameStatus() noexcept { for(auto const& element : columnsRowsOrDiagonals) if(board[element[0]].sign == activePlayer && board[element[1]].sign == activePlayer && board[element[2]].sign == activePlayer){ std::vector<int> squares; for(auto const& square : element) squares.push_back(square); emit gameEnded(mapSignTypeToUnsigned(activePlayer), squares); gameInProgress = false; return; } //draw if(isBoardFull()){ emit gameEnded(mapSignTypeToUnsigned(MyEnums::PlayerType::Empty), {}); gameInProgress = false; } } GameEngine::GameEngine(QObject *parent) : QObject(parent), activePlayer(MyEnums::PlayerType::Cross) {} void GameEngine::newGame() { gameInProgress = true; reset(); swapActivePlayer(); if(aiStatus[activePlayer]) moveAI(); } void GameEngine::move(const unsigned index, const unsigned sign) { if(gameInProgress) { auto signType = mapUnsignedToSignType(sign); if(signType == activePlayer && board[index].sign == MyEnums::PlayerType::Empty){ board[index].sign = signType; moves.push(index); emit updateSquare(index, mapSignTypeToUnsigned(signType)); checkGameStatus(); swapActivePlayer(); if(aiStatus[activePlayer] && gameInProgress){ std::this_thread::sleep_for(std::chrono::milliseconds(500)); moveAI(); } } else emit badMove(); } } void GameEngine::reset() { while(!moves.empty() && gameInProgress) undo(); } void GameEngine::undo() { if(!moves.empty() && gameInProgress){ const auto index = moves.top(); board[index].sign = MyEnums::PlayerType::Empty; moves.pop(); swapActivePlayer(); emit updateSquare(index, mapSignTypeToUnsigned(MyEnums::PlayerType::Empty)); } } void GameEngine::toggleAi(const unsigned sign) { aiStatus[mapUnsignedToSignType(sign)] = !aiStatus[mapUnsignedToSignType(sign)]; emit toggleAiSig(aiStatus[mapUnsignedToSignType(sign)], sign); if(aiStatus[activePlayer]) moveAI(); } std::optional<unsigned> GameEngine::findWinningMove(const MyEnums::PlayerType player) const noexcept { std::vector<unsigned> candidates; for(auto const& element : columnsRowsOrDiagonals){ unsigned playerSignsCounter = 0; unsigned emptyCounter = 0; unsigned candidate; for(auto const& position : element){ if(board[position].sign == player) ++playerSignsCounter; else if(board[position].sign == MyEnums::PlayerType::Empty){ candidate = position; ++emptyCounter; } } if(playerSignsCounter == 2 && emptyCounter == 1) candidates.push_back(candidate); } if(candidates.empty()) return {}; return candidates[QRandomGenerator::global()->generate()%candidates.size()]; } unsigned GameEngine::findBestMove() const noexcept { unsigned maxSignCounter = 0; std::vector<unsigned> bestMoves; for(auto i = 0u; i < board.size(); ++i){ if(board[i].sign == MyEnums::PlayerType::Empty) { auto boardCopy = board; boardCopy[i].sign = activePlayer; unsigned signCounter = 0; for(auto const& element : columnsRowsOrDiagonals) { for(auto const& position : element) { if(boardCopy[position].sign == activePlayer){ ++signCounter; break; } } } if(signCounter > maxSignCounter){ bestMoves.clear(); maxSignCounter = signCounter; bestMoves.push_back(i); } else if(signCounter == maxSignCounter) bestMoves.push_back(i); } } if(!bestMoves.empty()) return bestMoves[QRandomGenerator::global()->generate()%bestMoves.size()]; else return 0; } void GameEngine::moveAI() noexcept { QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents, 100); if(auto position = findWinningMove(activePlayer)) move(*position, mapSignTypeToUnsigned(activePlayer)); else if(auto position = findWinningMove(getOpositPlayer(activePlayer))) move(*position, mapSignTypeToUnsigned(activePlayer)); else move(findBestMove(), mapSignTypeToUnsigned(activePlayer)); } void GameEngine::process() { if(!QThread::currentThread()->isInterruptionRequested()) QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents, 1000); }
#include <Servo.h> Servo servo1; Servo servo2; int currentPos = 0; void setup() { Serial.begin(9600); servo1.attach(9); servo2.attach(8); } void servoWrite(int pos) { servo1.write(pos); servo2.write(pos); delay(50); } void serialReset(){ Serial.end(); Serial.begin(9600); } void loop() { while (Serial.available() < 1) {}; Serial.print("inside"); int temp = Serial.parseInt(); while (temp > 180 || temp < -180 || temp == 0){ temp = Serial.parseInt(); } if (currentPos < temp) { for (int i = currentPos; i < temp + 1; i+=5) { servoWrite(i); Serial.println(i); } servoWrite(temp); } if (currentPos > temp) { for (int i = currentPos; i > temp - 1; i-=5) { servoWrite(i); Serial.println(i); } servoWrite(temp); } serialReset(); currentPos = temp; }
N = input().strip() print(N[::-1])
/************************************************************* * > File Name : P2264.cpp * > Author : Tony * > Created Time : 2019/10/14 20:49:10 * > Algorithm : set **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 110; set<string> key, s; int ans; int main() { int n = read(); for (int i = 1; i <= n; ++i) { string str; cin >> str; for (int j = 0; j < str.length(); ++j) { if (str[j] >= 'A' && str[j] <= 'Z') { str[j] += 32; } } key.insert(str); } string word; char ch = getchar(); while (scanf("%c", &ch) == 1) { if (ch == '\n') break; if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { if (ch >= 'A' && ch <= 'Z') { ch += 32; } word.push_back(ch); } else { if (!word.empty()) { if (key.count(word)) s.insert(word); word.clear(); } if (ch == '.') { ans += s.size(); s.clear(); } } } printf("%d\n", ans); return 0; }
#ifndef _CONFIG_H_INCLUDED #define _CONFIG_H_INCLUDED #include <string> #include "common.h" #include "pixmap.h" #include "fuzzy.h" #ifdef _WINDOWS #include <windows.h> #include <stdio.h> #include <fcntl.h> #include <io.h> #include <iostream> #include <fstream> #include <conio.h> #ifndef _USE_OLD_IOSTREAMS using namespace std; #endif /* _USE_OLD_IOSTREAMS */ #endif /* _WINDOWS */ class Config { public: Config(); ~Config(); #ifdef _WINDOWS FILE *fp; bool V_CONSOLE_ONLY; static const char V_LOGFILE[8]; void redirectIO(); void toConsole(); void closeRedirectIO(); void setPath(); #endif /* _WINDOWS */ unsigned char *PIXBUF; bool *EDGE_MAP; //border map created in Threshold parsed in Border Pixmap *DBGPIXMAP; string TAG_IMAGE_FILE; //image filename Fuzzy *FUZZY; int THRESHOLD_WINDOW_SIZE; //Adapative thresholdng window size(lower the faster) int THRESHOLD_OFFSET; //threshold offset adjustment int THRESHOLD_RGB_FACTOR; //RGB range multiplication factor int WIN_DSHOW_MAXRGB; int WIN_DSHOW_COLORS; int PIXMAP_SCALE_SIZE; //fix pixmap to this bounding box size int PIXMAP_MINIMUM_SCALE_SIZE; //minimum valid value for PIXMAP_SCALE_FACTOR bool PIXMAP_FAST_SCALE; //scale by skipping(FAST) or by averaging(SLOW) bool PIXMAP_NATIVE_SCALE; //scale using platform specific external libraray bool JPG_SCALE; //scale by 2/4/8 on IJG JPEG lib decompress //NATIVE_SCALE requires no further scaling, JPG_SCALE may need further scaling int ANCHOR_BOX_FLEX_PERCENT; //allowed flexibility for box width and height int SHAPE_BOX_FLEX_PERCENT; //allowed flexibility for box width and height int GRID_WIDTH; //image width int GRID_HEIGHT; //image height bool PESSIMISTIC_ROTATION; //resizing the grid for rotated shapes int THREADS; int V_GRID_WIDTH; int V_GRID_HEIGHT; int V_WIN_WIDTH; int V_WIN_HEIGHT; int V_WIN_BORDER; int V_MSG_STRIP_SIZE; int V_FRAME_DELAY; int V_SKIP_FRAMES; bool *V_MAP; //tag map, inited in Decoder and filled up in Border bool V_D_TESTING; bool V_D_SKIP_CAM; bool V_D_PIXDEBUG; static const char V_TESTFILE[9]; bool LOGGING; bool TAG_DEBUG; bool WIN_DEBUG; bool WIN_PERF_LOG; bool VISUAL_DEBUG; bool ANCHOR_DEBUG; bool ARGS_OK; const int TAG_LENGTH; const int MAX_ANCHORS; const int MAX_SHAPES; const bool PLATFORM_CPP; const bool PLATFORM_CPP_MAGICK; const bool PLATFORM_CPP_SYMBIAN; const bool PLATFORM_CPP_SYMBIAN_S60; /* static final boolean PLATFORM_JAVA = true; static final boolean PLATFORM_JAVA_ME = false; static final boolean PLATFORM_JAVA_SE = true; static final boolean PLATFORM_JAVA_ANDROID = false; */ bool CHECK_VISUAL_DEBUG(); void setDebugPixmap(Pixmap* pixmap); bool checkArgs(int argc, char **argv); void freeEdgemap(); void freePixbuf(); }; #endif /* _CONFIG_H_INCLUDED */
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once WINRT_EXPORT namespace winrt { namespace ABI::Windows::Services::TargetedContent { struct ITargetedContentAction; struct ITargetedContentAvailabilityChangedEventArgs; struct ITargetedContentChangedEventArgs; struct ITargetedContentCollection; struct ITargetedContentContainer; struct ITargetedContentContainerStatics; struct ITargetedContentImage; struct ITargetedContentItem; struct ITargetedContentItemState; struct ITargetedContentObject; struct ITargetedContentStateChangedEventArgs; struct ITargetedContentSubscription; struct ITargetedContentSubscriptionOptions; struct ITargetedContentSubscriptionStatics; struct ITargetedContentValue; struct TargetedContentAction; struct TargetedContentAvailabilityChangedEventArgs; struct TargetedContentChangedEventArgs; struct TargetedContentCollection; struct TargetedContentContainer; struct TargetedContentFile; struct TargetedContentImage; struct TargetedContentItem; struct TargetedContentItemState; struct TargetedContentObject; struct TargetedContentStateChangedEventArgs; struct TargetedContentSubscription; struct TargetedContentSubscriptionOptions; struct TargetedContentValue; } namespace Windows::Services::TargetedContent { struct ITargetedContentAction; struct ITargetedContentAvailabilityChangedEventArgs; struct ITargetedContentChangedEventArgs; struct ITargetedContentCollection; struct ITargetedContentContainer; struct ITargetedContentContainerStatics; struct ITargetedContentImage; struct ITargetedContentItem; struct ITargetedContentItemState; struct ITargetedContentObject; struct ITargetedContentStateChangedEventArgs; struct ITargetedContentSubscription; struct ITargetedContentSubscriptionOptions; struct ITargetedContentSubscriptionStatics; struct ITargetedContentValue; struct TargetedContentAction; struct TargetedContentAvailabilityChangedEventArgs; struct TargetedContentChangedEventArgs; struct TargetedContentCollection; struct TargetedContentContainer; struct TargetedContentFile; struct TargetedContentImage; struct TargetedContentItem; struct TargetedContentItemState; struct TargetedContentObject; struct TargetedContentStateChangedEventArgs; struct TargetedContentSubscription; struct TargetedContentSubscriptionOptions; struct TargetedContentValue; } namespace Windows::Services::TargetedContent { template <typename T> struct impl_ITargetedContentAction; template <typename T> struct impl_ITargetedContentAvailabilityChangedEventArgs; template <typename T> struct impl_ITargetedContentChangedEventArgs; template <typename T> struct impl_ITargetedContentCollection; template <typename T> struct impl_ITargetedContentContainer; template <typename T> struct impl_ITargetedContentContainerStatics; template <typename T> struct impl_ITargetedContentImage; template <typename T> struct impl_ITargetedContentItem; template <typename T> struct impl_ITargetedContentItemState; template <typename T> struct impl_ITargetedContentObject; template <typename T> struct impl_ITargetedContentStateChangedEventArgs; template <typename T> struct impl_ITargetedContentSubscription; template <typename T> struct impl_ITargetedContentSubscriptionOptions; template <typename T> struct impl_ITargetedContentSubscriptionStatics; template <typename T> struct impl_ITargetedContentValue; } namespace Windows::Services::TargetedContent { enum class TargetedContentAppInstallationState { NotApplicable = 0, NotInstalled = 1, Installed = 2, }; enum class TargetedContentAvailability { None = 0, Partial = 1, All = 2, }; enum class TargetedContentInteraction { Impression = 0, ClickThrough = 1, Hover = 2, Like = 3, Dislike = 4, Dismiss = 5, Ineligible = 6, Accept = 7, Decline = 8, Defer = 9, Canceled = 10, Conversion = 11, Opportunity = 12, }; enum class TargetedContentObjectKind { Collection = 0, Item = 1, Value = 2, }; enum class TargetedContentValueKind { String = 0, Uri = 1, Number = 2, Boolean = 3, File = 4, ImageFile = 5, Action = 6, Strings = 7, Uris = 8, Numbers = 9, Booleans = 10, Files = 11, ImageFiles = 12, Actions = 13, }; } }
/* * SPDX-FileCopyrightText: (C) 2015-2022 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef STATS_H #define STATS_H #include <Cutelyst/cutelyst_global.h> #include <QObject> namespace Cutelyst { class EngineRequest; class StatsPrivate; class Stats { Q_DECLARE_PRIVATE(Stats) public: /** * Constructs a new stats object with the given parent. */ explicit Stats(EngineRequest *request); virtual ~Stats(); /** * Called before an action is executed to start counting it's time */ virtual void profileStart(const QString &action); /** * Called after an action is executed to stop counting it's time */ virtual void profileEnd(const QString &action); /** * Returns a text report of collected timmings */ virtual QByteArray report(); protected: StatsPrivate *d_ptr; }; } // namespace Cutelyst #endif // STATS_H
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) scanf("%lld", &n) #define scc(c) scanf(" %c", &c); #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define l(s) s.size() #define asort(a) sort(a,a+n) #define all(x) (x).begin(), (x).end() #define dsort(a) sort(a,a+n,greater<int>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<int>()); #define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end()) #define pn printf("\n") #define md 10000007 #define inf 1<<28 #define debug printf("I am here\n") #define ps printf(" ") int main() { ll t; cin>>t; while(t--) { ll cnt=0,ans=0, mx=0; ll n,m,r,p,s; cin>>n>>r>>p>>s; string s2, s1(n, '?'); //cout<<s1<<endl; cin>>s2; fr(i, n) { if(s2[i]=='R' and p) p--, s1[i]='P'; else if(s2[i]=='P' and s) s--, s1[i]='S'; else if(s2[i]=='S' and r) r--, s1[i]='R'; } fr(i, n) { if(s1[i]=='?') { if(r)s1[i]='R', r--; else if(p)s1[i]='P', p--; else if(s)s1[i]='S', s--; } else cnt++; } if( cnt>=(n+1)/2 )cout<<"YES"<<endl<<s1<<endl; else cout<<"NO"<<endl; } return 0; }
/** * * @file CM730ControlTable.hpp * @brief CM730 control table * @auther Naoki Takahashi * **/ #pragma once #include "../../Communicator/Protocols/DynamixelVersion1.hpp" namespace IO { namespace Device { namespace ControlBoard { namespace CM730ControlTable { constexpr Communicator::Protocols::DynamixelVersion1::Byte model_number_low = 0x00, // eeprom start model_number_high = 0x01, version_of_firmware = 0x02, id = 0x03, baud_rate = 0x04, return_delay_time = 0x05, status_return_level = 0x10, // eeprom end dynamixel_power = 0x18, // ram start enable_led_pannel = 0x19, led_5_low = 0x1a, led_5_high = 0x1b, led_6_low = 0x1c, led_6_high = 0x1d, button = 0x1e, gyro_z_low = 0x26, gyro_z_high = 0x27, gyro_y_low = 0x28, gyro_y_high = 0x29, gyro_x_low = 0x2a, gyro_x_high = 0x2b, acc_x_low = 0x2c, acc_x_high = 0x2d, acc_y_low = 0x2e, acc_y_high = 0x2f, acc_z_low = 0x30, acc_z_high = 0x31, present_voltage = 0x32, mic_low = 0x33, mic_high = 0x34, adc_2_low = 0x35, adc_2_high = 0x36, adc_3_low = 0x37, adc_3_high = 0x38, adc_4_low = 0x39, adc_4_high = 0x3a, adc_5_low = 0x3b, adc_5_high = 0x3c, adc_6_low = 0x3d, adc_6_high = 0x3e, adc_7_low = 0x3f, adc_7_high = 0x40, adc_8_low = 0x41, adc_8_high = 0x41, adc_9_low = 0x42, adc_9_high = 0x43, adc_10_low = 0x44, adc_10_high = 0x45, adc_11_low = 0x46, adc_11_high = 0x47, adc_12_low = 0x48, adc_12_high = 0x49, adc_13_low = 0x4a, adc_13_high = 0x4b, adc_14_low = 0x4c, adc_14_high = 0x4d, adc_15_low = 0x4e, adc_15_high = 0x4f; // ram end } } } }
#ifndef CELLO_COMPONENT_INFO #define CELLO_COMPONENT_INFO #include <string> #include <map> #include <vector> #include <gameplay.h> using std::string; using std::map; using std::vector; using gameplay::Vector3; #define COMPONENT_INFO(className) static cello::ComponentInfo<className> getInfo() \ { \ cello::ComponentInfo<className> componentInfo; #define PARAM(className, paramName, member) componentInfo.add(paramName, &className::member); #define END_COMPONENT_INFO return componentInfo; \ } namespace cello { enum class ParamType { BOOL, FLOAT, INT, STRING, VECTOR3 }; template<class ComponentClass> class ComponentInfo { public: void add(string name, bool ComponentClass::* boolMember) { _paramMap[name] = ParamType::BOOL; _boolMap[name] = boolMember; } void add(string name, float ComponentClass::* floatMember) { _paramMap[name] = ParamType::FLOAT; _floatMap[name] = floatMember; } void add(string name, int ComponentClass::* intMember) { _paramMap[name] = ParamType::INT; _intMap[name] = intMember; } void add(string name, string ComponentClass::* stringMember) { _paramMap[name] = ParamType::STRING; _stringMap[name] = stringMember; } void add(string name, Vector3 ComponentClass::* vector3Member) { _paramMap[name] = ParamType::VECTOR3; _vector3Map[name] = vector3Member; } const map<string, ParamType>& getParamMap() const { return _paramMap; } bool ComponentClass::* getBool(string name) { return _boolMap[name]; } float ComponentClass::* getFloat(string name) { return _floatMap[name]; } int ComponentClass::* getInt(string name) { return _intMap[name]; } string ComponentClass::* getString(string name) { return _stringMap[name]; } Vector3 ComponentClass::* getVector3(string name) { return _vector3Map[name]; } private: map<string, ParamType> _paramMap; map<string, bool ComponentClass::*> _boolMap; map<string, float ComponentClass::*> _floatMap; map<string, int ComponentClass::*> _intMap; map<string, string ComponentClass::*> _stringMap; map<string, Vector3 ComponentClass::*> _vector3Map; }; } #endif
class Solution { public: int maxProfit(vector<int>& inventory, int orders) { int result = 0; inventory.push_back(0); sort(inventory.begin(), inventory.end()); int count = 1; long temp = 0; long n; for(int i = inventory.size()-1; i > 0; i--) { if(orders >= count*(inventory[i] - inventory[i-1])) { n = inventory[i] - inventory[i-1]; temp = (n*(n-1)/2)%1000000007; result = (result + count*((((inventory[i-1] + 1)*n)%1000000007 + temp)%1000000007))%1000000007; orders -= count*(inventory[i] - inventory[i-1]); } else { long num = orders/count; temp = num*(num-1)/2; result = (result + count*((((inventory[i] -num+1)*num)%1000000007 + temp)%1000000007))%1000000007; orders = orders%count; result = (result + orders*(inventory[i] -num))%1000000007; break; } count++; } return result; } };
#include "display_object.h" namespace loss { DisplayObject::DisplayObject(DisplayObject *parent) : _parent(parent) { } Eigen::Projective3f &DisplayObject::transform() { return _transform; } void DisplayObject::parent(DisplayObject *parent) { _parent = parent; } DisplayObject *DisplayObject::parent() const { return _parent; } }
#ifndef _C_DBTASK_SQLOPER_H #define _C_DBTASK_SQLOPER_H #include <iostream> #include <vector> #include "common.h" #define UNUSED(x) (void)x enum DB_TYPE { DB_ORACLE = 0, DB_MYSQL = 1, }; class _c_dbTaskSqlOper { public: static _c_dbTaskSqlOper& getInstance(); bool executeCreatDb(DB_TYPE databaseType, PDB_PARAM pParam); bool executeSql(DB_TYPE databaseType, PDB_PARAM pParam, const std::string& strSql, bool statrments); std::vector<bool> executeSql(DB_TYPE databaseType, PDB_PARAM pParam, std::vector<std::string> sqlVector, bool statrments); void executeQuery(DB_TYPE databaseType, PDB_PARAM pParam, const std::string& strSql, std::string& result); public: bool executeOracleCreatDb(PDB_PARAM pParam); bool executeMysqlCreatDb(PDB_PARAM pParam); bool executeOracleSql(PDB_PARAM pParam, const std::string& strSql, bool statrments); bool executeMysqlSql(PDB_PARAM pParam, const std::string& strSql, bool statrments); bool executeOracleQuery(PDB_PARAM pParam, const std::string& strSql, std::string& result); bool executeMysqlQuery(PDB_PARAM pParam, const std::string strSql, std::string& result); bool conDB(PDB_PARAM pParam); }; #endif
#include<bits/stdc++.h> using namespace std; #define ff first #define ss second #define int long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define mii map<int,int> #define pqb priority_queue<int> #define pqs priority_queue<int,vi,greater<int> > #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define inf 1e18 #define ps(x,y) fixed<<setprecision(y)<<x mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int MAXN = 1e6+1; vector <int> adj[MAXN]; vector <int> vis(MAXN); int timer; int low[MAXN],in[MAXN]; set <int> AP; // Articulation Points void c_p_c() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void dfs(int s,int par) { vis[s] = 1; int child = 0; low[s] = in[s] = timer++; for(int u:adj[s]) { if(u == par) continue; if(vis[u] == 1) { // Back Edge low[s] = min(low[s],in[u]); } else { // Forward Edge child++; dfs(u,s); low[s] = min(low[s],low[u]); if(low[u] >= in[s] && par != -1) // Not Root and AP { AP.insert(s); } } } if(par == -1 && child > 1) // IF parent and child > 1 { AP.insert(s); } } int32_t main() { c_p_c(); while(1) { timer = 0; int n,m; cin >> n >> m; if(n == 0 && m == 0) { break; } for(int i=1;i<=m;i++) { adj[i].clear(); vis[i] = 0; low[i] = 0,in[i] = 0; } for(int i=0;i<m;i++) { int x,y; cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } for(int i=1;i<=n;i++) { if(vis[i] == 0) { dfs(i,-1); } } cout<<AP.size()<<endl; AP.clear(); } return 0; }
#include "include/world.h" #include "include/intersection.h" #include "include/plane.h" #include "gtest/gtest.h" #include <cmath> class WorldFixture : public ::testing::Test { protected: virtual void SetUp() { world = new raytracer::World(); light = new raytracer::Light(); transform = new raytracer::Transform(); ray = new raytracer::Ray(); xs = new std::vector<raytracer::Intersection>(); intersection = new raytracer::Intersection(); i1 = new raytracer::Intersection(); i2 = new raytracer::Intersection(); i3 = new raytracer::Intersection(); i4 = new raytracer::Intersection(); intersectionData = new raytracer::IntersectionData(); color = new raytracer::Color(); position = new raytracer::Tuple(); point = new raytracer::Tuple(); } virtual void TearDown() { delete world; delete light; delete transform; delete ray; delete xs; delete intersection; delete i1; delete i2; delete i3; delete i4; delete intersectionData; delete color; delete position; delete point; } raytracer::World * world; raytracer::Light * light; raytracer::Ray * ray; std::shared_ptr<raytracer::Shape> s1 = std::make_shared<raytracer::Sphere>(); std::shared_ptr<raytracer::Shape> s2 = std::make_shared<raytracer::Sphere>(); std::shared_ptr<raytracer::Shape> floor = std::make_shared<raytracer::Plane>(); std::shared_ptr<raytracer::Shape> upper = std::make_shared<raytracer::Plane>(); std::shared_ptr<raytracer::Shape> lower = std::make_shared<raytracer::Plane>(); raytracer::Transform * transform; std::vector<raytracer::Intersection> * xs; raytracer::Intersection * intersection; raytracer::Intersection * i1; raytracer::Intersection * i2; raytracer::Intersection * i3; raytracer::Intersection * i4; raytracer::IntersectionData * intersectionData; raytracer::Color * color; raytracer::Tuple * position; raytracer::Tuple * point; }; //// Test empty data structure? //TEST_F(WorldFixture, TestDataStructure) { // ASSERT_EQ(nullptr, world); //} TEST_F(WorldFixture, DefaultWorld) { world->defaultWorld(); s1->material.color = raytracer::Color(0.8, 1.0, 0.6); s1->material.diffuse = 0.7; s1->material.specular = 0.2; s2->setTransform(transform->scale(0.5, 0.5, 0.5)); EXPECT_EQ(raytracer::Light(raytracer::createPoint(-10, 10, -10), raytracer::Color(1, 1, 1)), world->light_); EXPECT_EQ(s1->material.diffuse, world->shapes_[0]->material.diffuse); EXPECT_EQ(s1->material.color, world->shapes_[0]->material.color); EXPECT_EQ(s1->material.specular, world->shapes_[0]->material.specular); ASSERT_EQ(s2->getTransform(), world->shapes_[1]->getTransform()); } TEST_F(WorldFixture, WorldRayIntersection) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -5), raytracer::createVector(0, 0, 1)); world->intersectWorld(* ray, xs); EXPECT_EQ(xs->size(), 4); EXPECT_EQ(xs[0][0].getDistance(), 4); EXPECT_EQ(xs[0][1].getDistance(), 4.5); EXPECT_EQ(xs[0][2].getDistance(), 5.5); ASSERT_EQ(xs[0][3].getDistance(), 6); } //TEST_F(WorldFixture, IntersectionShading) { // world->defaultWorld(); // * ray = raytracer::Ray(raytracer::Point(0, 0, -5), raytracer::Vector(0, 0, 1)); // s1 = world->shapes_[0]; // * intersection = raytracer::Intersection(4, s1); // * intersectionData = intersection->prepareComputations(* ray); // * color = world->shadeHit(* intersectionData); // ASSERT_EQ(raytracer::Color(0.38066, 0.47583, 0.2855), * color); //} // //TEST_F(WorldFixture, InsideIntersectionShading) { // world->defaultWorld(); // light_->setPointLight(raytracer::Point(0, 0.25, 0), raytracer::Color(1, 1, 1)); // world->light_ = * light_; // * ray = raytracer::Ray(raytracer::Point(0, 0, 0), raytracer::Vector(0, 0, 1)); // s2 = world->shapes_[1]; // * intersection = raytracer::Intersection(0.5, s2); // * intersectionData = intersection->prepareComputations(* ray); // * color = world->shadeHit(* intersectionData); // ASSERT_EQ(raytracer::Color(0.90498, 0.90498, 0.90498), * color); //} TEST_F(WorldFixture, ColorWhenRayMisses) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -5), raytracer::createVector(0, 1, 0)); * color = world->colorAt(* ray); ASSERT_EQ(raytracer::Color(0, 0, 0), * color); } TEST_F(WorldFixture, ColorWhenRayHits) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -5), raytracer::createVector(0, 0, 1)); * color = world->colorAt(* ray); ASSERT_EQ(raytracer::Color(0.38066, 0.47583, 0.2855), * color); } TEST_F(WorldFixture, ColorWithIntersectionBehindRay) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, 0.75), raytracer::createVector(0, 0, -1)); s1 = world->shapes_[0]; s1->material.ambient = 1; s2 = world->shapes_[1]; s2->material.ambient = 1; * color = world->colorAt(* ray); ASSERT_EQ(s2->material.color, * color); } // change to world isShadowed methods // for soft shadow implementation breaks tests // functionality stays the same with new variable //TEST_F(WorldFixture, NoShadowNothingColinearPointLight) { // world->defaultWorld(); // * point = raytracer::createPoint(0, 10, 0); // ASSERT_FALSE(world->isShadowed(* point)); //} // //TEST_F(WorldFixture, ShadowObjectBetweenPointLight) { // world->defaultWorld(); // * point = raytracer::createPoint(10, -10, 10); // ASSERT_TRUE(world->isShadowed(* point)); //} // //TEST_F(WorldFixture, NoShadowObjectBehindLight) { // world->defaultWorld(); // * point = raytracer::createPoint(-20, 20, -20); // ASSERT_FALSE(world->isShadowed(* point)); //} // //TEST_F(WorldFixture, NoShadowObjectBehindThePoint) { // world->defaultWorld(); // * point = raytracer::createPoint(-2, 2, -2); // ASSERT_FALSE(world->isShadowed(* point)); //} TEST_F(WorldFixture, IntersectionInShadow) { light->setPointLight(raytracer::createPoint(0, 0, -10), raytracer::Color(1, 1, 1)); world->light_ = * light; world->addObject(s1); transform->translate(0, 0, 10); s2->setTransform(* transform); world->addObject(s2); * ray = raytracer::Ray(raytracer::createPoint(0, 0, 5), raytracer::createVector(0, 0, 1)); * i1 = raytracer::Intersection(4, s2); * intersectionData = i1->prepareComputations(* ray, * xs); * color = world->shadeHit(* intersectionData); ASSERT_EQ(* color, raytracer::Color(0.1, 0.1, 0.1)); } //TEST_F(WorldFixture, OcclusionTestBetweenTwoPoints1) { // world->defaultWorld(); // * position = raytracer::createPoint(-10, -10, -10); // * point = raytracer::createPoint(-10, -10, 10); // ASSERT_FALSE(world->isShadowed(* position, * point)); //} // //TEST_F(WorldFixture, OcclusionTestBetweenTwoPoints2) { // world->defaultWorld(); // auto lightPosition = raytracer::Point(-10, -10, -10); // auto point = raytracer::Point(10, 10, 10); // ASSERT_TRUE(world->isShadowed(lightPosition, point)); //} // //TEST_F(WorldFixture, OcclusionTestBetweenTwoPoints3) { // world->defaultWorld(); // auto lightPosition = raytracer::Point(-10, -10, -10); // auto point = raytracer::Point(-20, -20, -20); // ASSERT_FALSE(world->isShadowed(lightPosition, point)); //} // //TEST_F(WorldFixture, OcclusionTestBetweenTwoPoints4) { // world->defaultWorld(); // auto lightPosition = raytracer::Point(-10, -10, -10); // auto point = raytracer::Point(-5, -5, -5); // ASSERT_FALSE(world->isShadowed(lightPosition, point)); //} TEST_F(WorldFixture, ReflectedColorForNonReflectiveMaterial) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, 0), raytracer::createVector(0, 0, 1)); s1 = world->shapes_[1]; s1->material.ambient = 1; * intersection = raytracer::Intersection(1, s1); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->reflectedColor(* intersectionData); ASSERT_EQ(* color, raytracer::Color(0, 0, 0)); } TEST_F(WorldFixture, ReflectedColorForReflectiveMaterial) { world->defaultWorld(); floor->material.reflection = 0.5; transform->translate(0, -1, 0); floor->setTransform(* transform); world->addObject(s1); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -3), raytracer::createVector(0, -sqrt(2)/2, sqrt(2)/2)); * intersection = raytracer::Intersection(sqrt(2), floor); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->reflectedColor(* intersectionData); ASSERT_EQ(* color, raytracer::Color(0.19032, 0.2379, 0.14274)); } TEST_F(WorldFixture, ShadeHitWithReflectiveMaterial) { world->defaultWorld(); floor->material.reflection = 0.5; transform->translate(0, -1, 0); floor->setTransform(* transform); world->addObject(s1); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -3), raytracer::createVector(0, -sqrt(2)/2, sqrt(2)/2)); * intersection = raytracer::Intersection(sqrt(2), floor); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->shadeHit(* intersectionData); ASSERT_EQ(* color, raytracer::Color(0.87677, 0.92436, 0.82918)); } // TODO Fix test to assert death or exit TEST_F(WorldFixture, ColorAtWithMutuallyReflectiveSurfaces) { world->defaultWorld(); world->light_.setPointLight(raytracer::createPoint(0, 0, 0), raytracer::Color(1, 1, 1)); floor->material.reflection = 1; transform->translate(0, -1, 0); floor->setTransform(* transform); world->addObject(floor); upper->material.reflection = 1; transform->translate(0, 1, 0); upper->setTransform(* transform); world->addObject(upper); * ray = raytracer::Ray(raytracer::createPoint(0, 0, 0), raytracer::createVector(0, 1, 0)); ASSERT_DEATH_IF_SUPPORTED(world->colorAt(* ray), ""); } TEST_F(WorldFixture, ReflectedColorAtMaximumRecursiveDepth) { world->defaultWorld(); floor->material.reflection = 0.5; transform->translate(0, -1, 0); floor->setTransform(* transform); world->addObject(floor); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -3), raytracer::createVector(0, -sqrt(2)/2, sqrt(2)/2)); * intersection = raytracer::Intersection(sqrt(2), floor); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->reflectedColor(* intersectionData, 0); ASSERT_EQ(* color, raytracer::Color(0, 0, 0)); } TEST_F(WorldFixture, RefractedColorOpaqueSurface) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -5), raytracer::createVector(0, 0, 1)); * i1 = raytracer::Intersection(4, world->shapes_[0]); * i2 = raytracer::Intersection(6, world->shapes_[0]); * xs = intersections(* i1, * i2); * intersectionData = xs[0][0].prepareComputations(* ray, * xs); * color = world->refractedColor(* intersectionData, 5); ASSERT_EQ(* color, raytracer::Color(0, 0, 0)); } TEST_F(WorldFixture, RefractedColorMaximumRecursiveDepth) { world->defaultWorld(); world->shapes_[0]->material.transparency = 1.0; world->shapes_[0]->material.refractiveIndex = 1.5; * ray = raytracer::Ray(raytracer::createPoint(0, 0, -5), raytracer::createVector(0, 0, 1)); * i1 = raytracer::Intersection(4, world->shapes_[0]); * i2 = raytracer::Intersection(6, world->shapes_[0]); * xs = intersections(* i1, * i2); * intersectionData = xs[0][0].prepareComputations(* ray, * xs); * color = world->refractedColor(* intersectionData, 0); ASSERT_EQ(* color, raytracer::Color(0, 0, 0)); } TEST_F(WorldFixture, RefractedColorUnderTotalInternalReflection) { world->defaultWorld(); world->shapes_[0]->material.transparency = 1.0; world->shapes_[0]->material.refractiveIndex = 1.5; * ray = raytracer::Ray(raytracer::createPoint(0, 0, sqrt(2)/2), raytracer::createVector(0, 1, 0)); * i1 = raytracer::Intersection(-sqrt(2)/2, world->shapes_[0]); * i2 = raytracer::Intersection(sqrt(2)/2, world->shapes_[0]); * xs = intersections(* i1, * i2); * intersectionData = xs[0][1].prepareComputations(* ray, * xs); * color = world->refractedColor(* intersectionData, 5); ASSERT_EQ(* color, raytracer::Color(0, 0, 0)); } TEST_F(WorldFixture, RefractedColorRefractedRay) { world->defaultWorld(); world->shapes_[0]->material.ambient = 1.0; world->shapes_[0]->material.pattern = std::make_shared<raytracer::TestPattern>(); world->shapes_[1]->material.transparency = 1.0; world->shapes_[1]->material.refractiveIndex = 1.5; * ray = raytracer::Ray(raytracer::createPoint(0, 0, 0.1), raytracer::createVector(0, 1, 0)); * i1 = raytracer::Intersection(-0.9899, world->shapes_[0]); * i2 = raytracer::Intersection(-0.4899, world->shapes_[1]); * i3 = raytracer::Intersection(0.4899, world->shapes_[1]); * i4 = raytracer::Intersection(0.9899, world->shapes_[0]); * xs = intersections(* i1, * i2, * i3, * i4); * intersectionData = xs[0][2].prepareComputations(* ray, * xs); * color = world->refractedColor(* intersectionData, 5); ASSERT_EQ(* color, raytracer::Color(0, 0.99888, 0.04725)); } TEST_F(WorldFixture, ShadeHitWithTransparentMaterial) { world->defaultWorld(); floor->material.transparency = 0.5; floor->material.refractiveIndex = 1.5; floor->setTransform(transform->translate(0, -1, 0)); world->addObject(floor); s1->material.color = raytracer::Color(1, 0, 0); s1->material.ambient = 0.5; s1->setTransform(transform->translate(0, -3.5, -0.5)); world->addObject(s1); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -3), raytracer::createVector(0, -sqrt(2)/2, sqrt(2)/2)); * intersection = raytracer::Intersection(sqrt(2), floor); * xs = intersections(* intersection); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->shadeHit(* intersectionData, 5); ASSERT_EQ(* color, raytracer::Color(0.93642, 0.68642, 0.68642)); } TEST_F(WorldFixture, ShadeHitWithReflectiveTransparentMaterial) { world->defaultWorld(); * ray = raytracer::Ray(raytracer::createPoint(0, 0, -3), raytracer::createVector(0, -sqrt(2)/2, sqrt(2)/2)); floor->setTransform(transform->translate(0, -1, 0)); floor->material.reflection = 0.5; floor->material.transparency = 0.5; floor->material.refractiveIndex = 1.5; world->addObject(floor); s1->material.color = raytracer::Color(1, 0, 0); s1->material.ambient = 0.5; s1->setTransform(transform->translate(0, -3.5, -0.5)); world->addObject(s1); * intersection = raytracer::Intersection(sqrt(2), floor); * xs = intersections(* intersection); * intersectionData = intersection->prepareComputations(* ray, * xs); * color = world->shadeHit(* intersectionData, 5); ASSERT_EQ(* color, raytracer::Color(0.93391, 0.69643, 0.69243)); }
#include "DialogueBox.h" #include "Textures.h" #include "GameWindow.h" #include "App_WebBrowser.h" #include "Website.h" DialogueBox::DialogueBox() { } DialogueBox::DialogueBox(GameWindow* gamewindowP, Textures* texturesP, Website* websiteP, int x, int y, dialogueBoxType type) { this->gameWindowP = gamewindowP; this->TextureGroup = texturesP; this->websiteP = websiteP; this->browserP = this->websiteP->getBrowserP(); this->type = type; this->spr.setTexture(this->TextureGroup->tex_dialogueBoxArticleChoice); this->spr.setOrigin(this->spr.getGlobalBounds().width/2, this->spr.getGlobalBounds().height/2); this->spr.setPosition(this->gameWindowP->getViewCenter()); if(this->gameWindowP->Desktop.getDialogueListSize() > 0) { this->spr.setPosition( this->gameWindowP->Desktop.dialogueList.back().getBounds().left + 10 , this->gameWindowP->Desktop.dialogueList.back().getBounds().top + 10); } switch(this->type) { case d_YesNo: { sf::Vector2i yesPos = sf::Vector2i(this->spr.getGlobalBounds().left + (this->spr.getGlobalBounds().width/4) - (this->TextureGroup->TextureRects[TRDialogueYesInactive].width/2), this->spr.getGlobalBounds().top + (this->spr.getGlobalBounds().height*0.75) - (this->TextureGroup->TextureRects[TRDialogueYesInactive].height/2)); sf::Vector2i noPos = sf::Vector2i(this->spr.getGlobalBounds().left + (this->spr.getGlobalBounds().width*0.75) - (this->TextureGroup->TextureRects[TRDialogueNoInactive].width/2), this->spr.getGlobalBounds().top + (this->spr.getGlobalBounds().height*0.75) - (this->TextureGroup->TextureRects[TRDialogueNoInactive].height/2)); std::cout << "YESPOS: " << yesPos.x << ", " << yesPos.y << std::endl; std::cout << "NOPOS: " << noPos.y << ", " << noPos.y << std::endl; this->opt1 = Button(this->gameWindowP, yesPos.x, yesPos.y, ButDialogueYes, APPNone, WPNone, 0); this->opt2 = Button(this->gameWindowP, noPos.x, noPos.y, ButDialogueNo, APPNone, WPNone, 0); } break; case d_CritSup: { std::cout << "CRITSUP CONSTRUCTOR CALLED " << std::endl; this->spr.setTexture(this->TextureGroup->tex_dialogueBoxCritSup, true); sf::Vector2i yesPos = sf::Vector2i(this->spr.getGlobalBounds().left + (this->spr.getGlobalBounds().width/4) - (this->TextureGroup->TextureRects[TRDialogueYesInactive].width/2), this->spr.getGlobalBounds().top + (this->spr.getGlobalBounds().height*0.75) - (this->TextureGroup->TextureRects[TRDialogueYesInactive].height/2)); sf::Vector2i noPos = sf::Vector2i(this->spr.getGlobalBounds().left + (this->spr.getGlobalBounds().width*0.75) - (this->TextureGroup->TextureRects[TRDialogueNoInactive].width/2), this->spr.getGlobalBounds().top + (this->spr.getGlobalBounds().height*0.75) - (this->TextureGroup->TextureRects[TRDialogueNoInactive].height/2)); std::cout << "YESPOS: " << yesPos.x << ", " << yesPos.y << std::endl; std::cout << "NOPOS: " << noPos.y << ", " << noPos.y << std::endl; this->opt1 = Button(this->gameWindowP, yesPos.x, yesPos.y, ButDialogueCriticize, APPNone, WPNone, 0); this->opt2 = Button(this->gameWindowP, noPos.x, noPos.y, ButDialogueSupport, APPNone, WPNone, 0); } break; case d_ThreeOpts: { this->opt1Name = this->gameWindowP->Desktop.articleChosen.back().bc_para2_1_name; this->opt2Name = this->gameWindowP->Desktop.articleChosen.back().bc_para2_2_name; this->opt3Name = this->gameWindowP->Desktop.articleChosen.back().bc_para2_3_name; this->spr.setTexture(this->TextureGroup->tex_dialogueBoxItemChoice, true); this->opt1 = Button(this->gameWindowP, this->spr.getGlobalBounds().left + 2, this->spr.getGlobalBounds().top + 56, ButDialogueChoice, APPNone, WPNone, 0); this->opt2 = Button(this->gameWindowP, this->spr.getGlobalBounds().left + 2, this->spr.getGlobalBounds().top + 87, ButDialogueChoice, APPNone, WPNone, 0); this->opt3 = Button(this->gameWindowP, this->spr.getGlobalBounds().left + 2, this->spr.getGlobalBounds().top + 118, ButDialogueChoice, APPNone, WPNone, 0); this->labels.push_back(sf::Text(this->opt1Name, this->TextureGroup->articleFont, 15)); this->labels.back().setOrigin(floor(this->labels.back().getGlobalBounds().width/2), floor(this->labels.back().getGlobalBounds().height/2)); this->labels.back().setPosition(floor(this->opt1.getBounds().left + (this->opt1.getBounds().width/2)), floor(this->opt1.getBounds().top + (this->opt1.getBounds().height/2))); this->labels.back().setColor(sf::Color::Black); this->labels.push_back(sf::Text(this->opt2Name, this->TextureGroup->articleFont, 15)); this->labels.back().setOrigin(floor(this->labels.back().getGlobalBounds().width/2), floor(this->labels.back().getGlobalBounds().height/2)); this->labels.back().setPosition(floor(this->opt2.getBounds().left + (this->opt2.getBounds().width/2)), floor(this->opt2.getBounds().top + (this->opt2.getBounds().height/2))); this->labels.back().setColor(sf::Color::Black); this->labels.push_back(sf::Text(this->opt3Name, this->TextureGroup->articleFont, 15)); this->labels.back().setOrigin(floor(this->labels.back().getGlobalBounds().width/2), floor(this->labels.back().getGlobalBounds().height/2)); this->labels.back().setPosition(floor(this->opt3.getBounds().left + (this->opt3.getBounds().width/2)), floor(this->opt3.getBounds().top + (this->opt3.getBounds().height/2))); this->labels.back().setColor(sf::Color::Black); } break; } } sf::FloatRect DialogueBox::getBounds() { return this->spr.getGlobalBounds(); } void DialogueBox::update() { this->browserP->websiteP->checkDialogueBoxes(); this->opt1.update(); this->opt2.update(); switch(this->type) { case d_YesNo: { if(this->opt1.getActive()) { this->Return = dr_Yes; } else if(this->opt2.getActive()) { this->Return = dr_No; std::cout << "OPT2 ACTIVE" << std::endl; } } break; case d_CritSup: { if(this->opt1.getActive()) { this->Return = dr_Criticize; } else if(this->opt2.getActive()) { this->Return = dr_Support; } } break; case d_ThreeOpts: { this->opt3.update(); if(this->opt1.getActive()) { this->Return = dr_crit1; } else if(this->opt2.getActive()) { this->Return = dr_crit2; } else if(this->opt3.getActive()) { this->Return = dr_crit3; } } break; default: std::cout << "UNKNOWN DIALOGUEBOX TYPE IN DIALOGUEBOX.CPP" << std::endl; break; } } dialogueBoxReturns DialogueBox::getReturn() { return this->Return; } void DialogueBox::render() { this->gameWindowP->queSprites(this->spr,2); this->opt1.render(2); this->opt2.render(2); if(this->type == d_ThreeOpts) { this->opt3.render(2); for(unsigned i = 0; i < this->labels.size(); i++) { this->gameWindowP->queText(this->labels[i],2); } } } DialogueBox::~DialogueBox() { this->labels.clear(); }
// Section 11 // Function Definitions // Area of a circle nd volume of a cylinder #include <iostream> #include <cmath> using namespace std; //function prototypes double calc_volume_cylinder(double radius, double height); double calc_area_circle(double radius); void area_circle (); void volume_cylinder(); const double pi {3.14159}; int main () { area_circle(); volume_cylinder(); cout << "Hello world" << endl; return 0; } double calc_area_circle(double radius) { return pi * pow(radius, 2.0); } double calc_volume_cylinder(double radius, double height) { //return pi * pow(radius, 2.0) * height; return calc_area_circle(radius) * height; } void area_circle () { double radius {0}; cout <<"\nPlease enter the radius of the circle: "; cin >> radius; cout << "\nThe area of the circle with radius " << radius<< " is " << calc_area_circle(radius)<< endl; } void volume_cylinder() { double radius {0}; double height {0}; cout <<"\nPlease enter the radius of the cylinder: "; cin >> radius; cout <<"\nPlease enter the height of the cylinder: "; cin >> height; cout << "\nThe volume of cylinder with radius " << radius <<" and height "<<height<< " is "<<calc_volume_cylinder(radius, height)<< endl; }
/* problem : Implement a stack that stores integers, then program process the commands condition : 5 commands are given push,pop(if stack is empty, printout -1),size,empty(if stack is empty print 1, otherwise print 0),top(if stack is empty, printout -1) Example -Input 14 push 1 push 2 top size empty pop pop pop size empty pop push 3 empty top -Output 2 2 0 2 1 -1 0 1 -1 0 3 */ #include<iostream> #include<stack> using namespace std; int main(){ stack<int> s; int T; int num; string cmd; cin>>T; for(int i=0;i<T;i++){ cin>>cmd; if(cmd=="push"){ cin>>num; s.push(num); }else if(cmd=="pop"){ if(s.empty()){ cout<<"-1"<<endl; }else{ cout<<s.top()<<endl; s.pop(); } }else if(cmd=="size"){ cout<<s.size()<<endl; }else if(cmd=="empty"){ if(s.empty()){ cout<<"1"<<endl; }else{ cout<<"0"<<endl; } }else if(cmd=="top"){ if(s.empty()){ cout<<"-1"<<endl; }else{ cout<<s.top()<<endl; } } } }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "expat.h" #include <string> #include "cow_xml.h" #include <multimedia/component_factory.h> #include <multimedia/mm_debug.h> MM_LOG_DEFINE_MODULE_NAME("COWXML"); namespace YUNOS_MM { const char * xmlPath = "Path"; const char * xmlCompLibPath = "libpath"; const char * xmlComponents = "Components"; const char * xmlComponent = "Component"; const char * xmlCompLibName = "libComponentName"; const char * xmlCompName = "ComponentName"; const char * xmlMime = "mime"; const char * xmlMimeType = "MimeType"; const char * xmlPriority = "Priority"; const char * xmlPriorityDisable = "disable"; const char * xmlPriorityLow = "low"; const char * xmlPriorityNormal = "normal"; const char * xmlPriorityHigh = "high"; const char * xmlCap = "Cap"; const char * xmlDecoder = "decoder"; const char * xmlEncoder = "encoder"; const char * xmlEnAndDecoder = "codec"; const char * xmlGeneric = "generic"; /*static*/ CowComponentXMLSP CowComponentXML::create(std::string fileName) { //#0 new a XML file CowComponentXML *pXML = new CowComponentXML(); if (!pXML){ ERROR("new CowComponentXML() is error\n"); return CowComponentXMLSP((CowComponentXML*)NULL); } if(pXML->Init(fileName)==false){ ERROR("initiate the xml file is error\n"); delete pXML; return CowComponentXMLSP((CowComponentXML*)NULL); } //#1 set the shared pointer CowComponentXMLSP pCCowCompXMLSP(pXML,&CowComponentXML::Release); return pCCowCompXMLSP; } CowComponentXML::CowComponentXML() :mbInited(false) { INFO("now start to parse cow xml file\n"); return; } CowComponentXML::~CowComponentXML() { unInit(); } bool CowComponentXML::Init(std::string fileName) { FILE *file = NULL; if(true == mbInited){ INFO("CAUTION:cow xml has been initiated\n"); return true; } //#1 open the xml file for parsing INFO("the cow xml file:%s\n",fileName.c_str()); if (fileName.empty()) return false; file = fopen(fileName.c_str(),"r"); if (file == NULL) { ERROR("unable to open cow plugins xml file:%s\n", fileName.c_str()); return false; } if (parseXMLFile(file) == false){ ERROR("unable to parse the xml file\n"); fclose(file); return false; } fclose(file); file = NULL; mbInited = true; return true; } void CowComponentXML::unInit() { if(false == mbInited){ INFO("cow xml hasn't been initiated\n"); return ; } mVComNameLibName.clear(); mVMimeTypeComName.clear(); mNodeStack.clear(); mbInited = false; return; } bool CowComponentXML::parseXMLFile(FILE *file) { int InitCheck = 0; XML_Parser parser = ::XML_ParserCreate(NULL); if (parser == NULL) { ERROR("fail to create XML parser"); return false; } ::XML_SetUserData(parser, this); ::XML_SetElementHandler(parser, StartElementHandlerWrapper, EndElementHandlerWrapper); const int BUFF_SIZE = 512; while (InitCheck == 0) { void *buff = ::XML_GetBuffer(parser, BUFF_SIZE); if (buff == NULL) { ERROR("failed in call to XML_GetBuffer()"); InitCheck = -1; break; } int bytes_read = ::fread(buff, 1, BUFF_SIZE, file); if (bytes_read < 0) { ERROR("failed in call to fread"); InitCheck = -1; break; } int ret = ::XML_ParseBuffer(parser, bytes_read, bytes_read == 0); if (ret == 0) {//OK==1,ERROR==0 InitCheck = -1; break; } if (bytes_read == 0) { break; } } ::XML_ParserFree(parser); return true; } // static void CowComponentXML::StartElementHandlerWrapper(void *me, const char *name, const char **attrs) { static_cast<CowComponentXML *>(me)->startElementHandler(name, attrs); } // static void CowComponentXML::EndElementHandlerWrapper(void *me, const char *name) { static_cast<CowComponentXML *>(me)->endElementHandler(name); } void CowComponentXML::startElementHandler(const char *name, const char **attrs) { //#0 check it with "Components" if (!strcmp(name, xmlComponents)){ if (!mNodeStack.empty()){ ERROR("the cow plugins xml file has error format(Components)\n"); return; } //#0.0 push the components into stack std::string StackName = xmlComponents; mNodeStack.push_back(StackName); return; } //check it with "libpath". // it is the default 'libpath' of this xml, each Component can override it if (!strcmp(name, xmlPath)){ DEBUG("libpath: (%s, %s)", attrs[0], attrs[1]); if (!strcmp(attrs[0], xmlCompLibPath) && attrs[1]) { mLibPath = attrs[1]; } return; } //#1 check it with "Component" if (!strcmp(name, xmlComponent)){ if (mNodeStack.empty()){ ERROR("the cow plugins xml file has error format(Component)\n"); return; } if (mNodeStack[0] != xmlComponents) { ERROR("find the xml file header is error\n"); return; } //#1.0 save the attribute into list addOneComponent(attrs); //#1.1 push the current component into stack std::string str = xmlComponent; mNodeStack.push_back(str); return; } //#2 check it with "MimeType" if (!strcmp(name, xmlMime)){ if (mNodeStack.empty()){ ERROR("the cow plugins xml file has error format(mime)\n"); return; } if (mNodeStack[0] != xmlComponents) { ERROR("find the xml file header is error2\n"); return; } if (mNodeStack[1] != xmlComponent) { ERROR("find the xml file header is error3\n"); return; } addOneMime(attrs); return; } ERROR("find UNKNOWN block in the xml file header: %s", name); return; } void CowComponentXML::endElementHandler(const char *name) { if (!strcmp(name, xmlPath)){ return; } if (!strcmp(name, xmlComponents)){ if ((mNodeStack.size() != 1) || (mNodeStack[0] != xmlComponents)){ ERROR("End Element Components is error\n"); return; } mNodeStack.pop_back(); return; } //#1 check it with "</Component>" if (!strcmp(name, xmlComponent)){ if ((mNodeStack[mNodeStack.size() - 1] != xmlComponent)){ ERROR("End Element Component is error\n"); return; } mNodeStack.pop_back(); return; } if (!strcmp(name, xmlMime)){ return; } ERROR("End Element Component:unknown block:%s", name); return; } bool CowComponentXML::addOneComponent(const char **attrs) { const char *pLibComponentName = NULL; const char *pComponentName = NULL; const char *pLibPath = mLibPath.c_str(); size_t i = 0; //#0 find the LibComponentName && ComponentName while (attrs[i] != NULL) { if (!strcmp(attrs[i], xmlCompLibName)) { if (attrs[i + 1] == NULL) { return false; } pLibComponentName = attrs[i + 1]; ++i; } else if (!strcmp(attrs[i], xmlCompName)) { if (attrs[i + 1] == NULL) { return false; } pComponentName = attrs[i + 1]; ++i; } else if (!strcmp(attrs[i], xmlCompLibPath)) { if (attrs[i + 1] == NULL) { return false; } pLibPath = attrs[i + 1]; ++i; } else return false; ++i; }//while (attrs[i] != NULL) if (!pLibComponentName || !pComponentName || !pLibPath){ return false; } //#1 save the LibComponentName && ComponentName ComNameLibName cnlc; cnlc.mLibName = pLibPath; cnlc.mLibName.append("/lib"); cnlc.mLibName.append(pLibComponentName); cnlc.mLibName.append(".so"); cnlc.mComName = pComponentName; DEBUG("got lib %s support component: %s\n", pLibComponentName, pComponentName); mVComNameLibName.push_back(cnlc); return true; } bool CowComponentXML::addOneMime(const char **attrs) { const char *MimeType = NULL; const char *Priority = NULL; const char *Cap = NULL; size_t i = 0; //#0 find the LibComponentName && ComponentName while (attrs[i] != NULL) { if (!strcmp(attrs[i], xmlMimeType)) { if (attrs[i + 1] == NULL) { return false; } MimeType = attrs[i + 1]; ++i; } else if (!strcmp(attrs[i], xmlPriority)) { if (attrs[i + 1] == NULL) { return false; } Priority = attrs[i + 1]; ++i; } else if (!strcmp(attrs[i], xmlCap)) { if (attrs[i + 1] == NULL) { return false; } Cap = attrs[i + 1]; ++i; } else return false; ++i; }//while (attrs[i] != NULL) if ((!MimeType) || (!Priority) || (Cap == NULL)) return false; //#1 push the MimeType && ComponentName input the number MimeTypeComName mtcn; mtcn.mMimeType = MimeType; if (!strcmp(Priority, xmlPriorityLow)) mtcn.mPriority = LOW_PRIORITY; else if (!strcmp(Priority, xmlPriorityNormal)) mtcn.mPriority = DEFAULT_PRIORITY; else if (!strcmp(Priority, xmlPriorityHigh)) mtcn.mPriority = HIGH_PRIORITY; else if (!strcmp(Priority, xmlPriorityDisable)) mtcn.mPriority = DISABLE_PRIORITY; else { ERROR("xml file priority error:%s",Priority); return false; } if(!strcmp(Cap, xmlEnAndDecoder)) mtcn.mCap = XML_COMP_CODECS; else if(!strcmp(Cap, xmlEncoder)) mtcn.mCap = XML_COMP_ENCODER; else if(!strcmp(Cap, xmlDecoder)) mtcn.mCap = XML_COMP_DECODER; else if(!strcmp(Cap,xmlGeneric)) mtcn.mCap = XML_COMP_GENERIC; else { ERROR("xml file codec info error:%s\n",Cap); return false; } mtcn.mComName = mVComNameLibName.back().mComName; mVMimeTypeComName.push_back(mtcn); return true; } std::vector<ComNameLibName> &CowComponentXML::getComNameLibNameTable() { return mVComNameLibName; } std::vector<MimeTypeComName> &CowComponentXML::getMimeTypeComNameTable() { return mVMimeTypeComName; } /*static*/void CowComponentXML::Release(CowComponentXML * pXML) { if (pXML){ INFO("now begin to unload xml file\n"); pXML->unInit(); } delete pXML; } }
/*************************************************************************** dialogoordenarcasos.cpp - description ------------------- begin : mar sep 16 2003 copyright : (C) 2003 by Oscar G. Duarte email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogoordenarcasos.h" BEGIN_EVENT_TABLE(DialogoOrdenarCasos, wxDialog) EVT_BUTTON(DLG_ORDENCASO_BTN_ORDENAR, DialogoOrdenarCasos::ordenar) EVT_BUTTON(DLG_ORDENCASO_BTN_OK, DialogoOrdenarCasos::cerrarOk) // EVT_BUTTON(DLG_ORDENCASO_BTN_CANCELAR, DialogoOrdenarCasos::cancelar) EVT_BUTTON(DLG_ORDENCASO_BTN_AYUDA, DialogoOrdenarCasos::ayuda) EVT_LISTBOX(DLG_ORDENCASO_LISTBOX_ESTRATEGIAS,DialogoOrdenarCasos::llenarNodos) EVT_CHECKBOX(DLG_ORDENCASO_CHECKBOX_ASCENDENTE, DialogoOrdenarCasos::clickAscendente) EVT_CHECKBOX(DLG_ORDENCASO_CHECKBOX_DESCENDENTE, DialogoOrdenarCasos::clickDescendente) END_EVENT_TABLE() DialogoOrdenarCasos::DialogoOrdenarCasos(Proyecto *proy, wxWindow *parent, wxHtmlHelpController *ayuda): wxDialog(parent,wxID_ANY,wxString(wxT("Prueba"))) { Proy=proy; Ayuda=ayuda; ButtonOrdenar =new wxButton(this,DLG_ORDENCASO_BTN_ORDENAR, wxT("Ordenar")); ButtonOK =new wxButton(this,DLG_ORDENCASO_BTN_OK, wxT("OK")); // ButtonCancelar =new wxButton(this,DLG_ORDENCASO_BTN_CANCEL, wxT("Cancelar")); ButtonAyuda =new wxButton(this,DLG_ORDENCASO_BTN_AYUDA, wxT("Ayuda")); ListBoxEstrategias =new wxListBox(this,DLG_ORDENCASO_LISTBOX_ESTRATEGIAS,wxPoint(0,0),wxSize(150, 80), 0, 0, wxLB_SINGLE|wxLB_ALWAYS_SB); ListBoxNodos =new wxListBox(this,DLG_ORDENCASO_LISTBOX_NODOS,wxPoint(0,0),wxSize(150, 80), 0, 0, wxLB_SINGLE|wxLB_ALWAYS_SB); StaticEstrategias =new wxStaticText(this,DLG_ORDENCASO_STATIC_ESTRATEGIAS, wxT("Metodologías")); StaticNodos =new wxStaticText(this,DLG_ORDENCASO_STATIC_NODOS, wxT("Nodos")); CheckAlfabetico =new wxCheckBox(this,DLG_ORDENCASO_CHECKBOX_ALFABETICO, wxT("Orden Alfabético")); CheckAscendente =new wxCheckBox(this,DLG_ORDENCASO_CHECKBOX_ASCENDENTE, wxT("Ascendente")); CheckDescendente =new wxCheckBox(this,DLG_ORDENCASO_CHECKBOX_DESCENDENTE, wxT("Descendente")); CheckAlfabetico->SetValue(1); CheckAscendente->SetValue(1); CheckDescendente->SetValue(0); wxBoxSizer *sizerEst = new wxBoxSizer(wxVERTICAL); sizerEst->Add(StaticEstrategias, 0, wxALIGN_CENTER | wxALL, 5); sizerEst->Add(ListBoxEstrategias, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerNod = new wxBoxSizer(wxVERTICAL); sizerNod->Add(StaticNodos, 0, wxALIGN_CENTER | wxALL, 5); sizerNod->Add(ListBoxNodos, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerListas = new wxBoxSizer(wxHORIZONTAL); sizerListas->Add(sizerEst, 0, wxALIGN_CENTER | wxALL, 5); sizerListas->Add(sizerNod, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerAlf = new wxBoxSizer(wxVERTICAL); sizerAlf->Add(CheckAlfabetico, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerOrden = new wxBoxSizer(wxVERTICAL); sizerOrden->Add(CheckAscendente, 0, wxALIGN_LEFT | wxALL, 0); sizerOrden->Add(CheckDescendente, 0, wxALIGN_LEFT | wxALL, 0); wxBoxSizer *sizerCheck = new wxBoxSizer(wxHORIZONTAL); sizerCheck->Add(sizerAlf, 0, wxALIGN_TOP | wxALL, 5); sizerCheck->Add(sizerOrden, 0, wxALIGN_TOP | wxALL, 5); wxBoxSizer *sizerButInf = new wxBoxSizer(wxHORIZONTAL); sizerButInf->Add(ButtonOK, 0, wxALIGN_CENTER | wxALL, 5); // sizerButInf->Add(ButtonCancelar, 0, wxALIGN_CENTER | wxALL, 5); sizerButInf->Add(ButtonAyuda, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerTotal = new wxBoxSizer(wxVERTICAL); sizerTotal->Add(sizerListas, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerCheck, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(ButtonOrdenar, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerButInf, 0, wxALIGN_CENTER | wxALL, 5); SetAutoLayout(TRUE); SetSizer(sizerTotal); sizerTotal->SetSizeHints(this); sizerTotal->Fit(this); llenarCuadro(); } DialogoOrdenarCasos::~DialogoOrdenarCasos() { } void DialogoOrdenarCasos::llenarCuadro() { ListBoxEstrategias->Clear(); int i,tam; tam=Proy->Estrategias.GetCount(); for(i=0;i<tam;i++) { wxString cad; cad=Proy->Estrategias.Item(i).Nombre; ListBoxEstrategias->Append(cad); } if(tam>0) { ListBoxEstrategias->SetSelection(0); } wxCommandEvent ev; llenarNodos(ev); } void DialogoOrdenarCasos::llenarNodos(wxCommandEvent&) { ListBoxNodos->Clear(); int i,tam; Estrategia *Est; int numEst; numEst=ListBoxEstrategias->GetSelection(); if(numEst<0){return;} Est=&Proy->Estrategias.Item(numEst); ListaNodos Lista; Est->Grafo.llenarArreglo(&Lista); tam=Lista.GetCount(); for(i=0;i<tam;i++) { wxString cad; cad=Lista.Item(0).VarCalculada.Nombre; ListBoxNodos->Append(cad); Lista.Detach(0); } if(tam>0) { ListBoxNodos->SetSelection(0); } } void DialogoOrdenarCasos::clickAscendente(wxCommandEvent&) { if(CheckAscendente->GetValue()) { CheckDescendente->SetValue(FALSE); }else { CheckDescendente->SetValue(TRUE); } } void DialogoOrdenarCasos::clickDescendente(wxCommandEvent&) { if(CheckDescendente->GetValue()) { CheckAscendente->SetValue(FALSE); }else { CheckAscendente->SetValue(TRUE); } } void DialogoOrdenarCasos::ordenar(wxCommandEvent&) { if(CheckAlfabetico->GetValue()) { Proy->ordenNombre(CheckDescendente->GetValue()); wxString cad=wxT("Se han ordenado los casos alfabéticamente"); wxMessageBox(cad, GENERAL_ADVERTENCIA, wxOK | wxICON_INFORMATION, this); }else { Estrategia *Est; NodoCalculo *Nodo; int numEst,numNodo; numEst=ListBoxEstrategias->GetSelection(); numNodo=ListBoxNodos->GetSelection(); if(numEst*numNodo < 0){return;} Est=&Proy->Estrategias.Item(numEst); Nodo=Est->Grafo.buscarNodo(ListBoxNodos->GetStringSelection()); if(Nodo==NULL){return;} float opt,r; opt=Proy->Optimismo; r=Proy->Representatividad; Proy->ordenValor(Nodo,opt,r,CheckDescendente->GetValue()); wxString cad=wxT("Se han ordenado los casos"); wxMessageBox(cad, GENERAL_ADVERTENCIA, wxOK | wxICON_INFORMATION, this); } } void DialogoOrdenarCasos::cerrarOk(wxCommandEvent&) { Close(); } void DialogoOrdenarCasos::ayuda(wxCommandEvent&) { Ayuda->Display(wxT("Ordenar los Casos")); }
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int lsum=0, rsum=0, n=cardPoints.size()-1; for(int i=0; i<k; i++){ lsum+=cardPoints[i]; } int maxm=lsum; for(int i=0; i<k; i++){ rsum+=cardPoints[n-i]; lsum-=cardPoints[k-i-1]; maxm=max(rsum+lsum, maxm); } return maxm; } };
/* Foward List: * Thuộc tính: + Foward-list là một singly linked list + Cấu trúc tuần từ (Sequence) + Danh sách liên kết (Linked list) + Cấp phát động (Allocator-aware) * Template parameters <T, Alloc>: + T: Kiểu dữ liệu cần chứa (Type of ele contained) + Alloc: Type of allocation object * Function member: - Constructor: + forward-list(): khởi tạo với 0 element + forward-list(n): khởi tạo với n element + forward-list(n, value): khởi tạo với n element với giá trị value + forward-list(first, last): khởi tạo với range(first, last) + forward-list(forward-list): khởi tạo mà copy toàn bộ dữ liệu + forward-list() = {a, b, c,...} khởi tạo và gán phần tử + forward-list(std::move(forward-list)): khởi tạo chuyển dữ liệu - Iterators: + before_begin(): => iterator: before ele[0] (Dùng làm tham số, không tham chiếu) + before_begin(): => const_iterator: before ele[0] (Dùng làm tham số, không tham chiếu) + begin(): => iterator: ele[0] + end(): => iterator: ele[n] + cbegin(): => const_iterator: ele[0] (Không thể thay đổi giá trị *it) + cend(): => const_iterator: ele[n] (Không thể thay đổi giá trị *it) - Capacity: + maxsize(): => maximum size + empty(): => có rỗng? (true or false) - Element access: + front(): => reference ele[0] - Modifiers: + assign(first, last)/(pos, value): gán giá trị + emplace_front(value): chèn trực tiếp phần tử vào đầu + emplace_after(pos, value): chèn trực tiếp phần tử vào pos + push_front(value): chèn sao chép phần tử vào đầu + pop_front(): xóa phần tử đầu + insert(it, value)/(it, n, value)/(it, <>)/(it, it1, it2): chèn phần tử + erase(it)/(first, last): xóa phần tử + swap(foward-list): hoán đổi dữ liệu 2 foward-list + resize(n, value): resize forward-list + clear(): xóa toàn bộ dữ liệu - Operations: + splice_after(argument): nối 2 forward-list + remove(value): xóa tất cả ele có value + remove_if(Predicate pred): pred là một điều kiện(có thể implement bằng function hoặc class) + unique(Predicate pred): xóa các phần tử lặp lại + merge(forward-list, comp): comp là một điều kiện để merge (std::greater<>()) + sort(comp): sort list + reverse(): đảo ngược list - Non-member function overloads: + swap(foward-list): hoán đổi dữ liệu 2 foward-list + relational operators(forward-list): dùng để biểu thị toán tử quan hệ _ ____ __ _ _ __ (_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_ /( .-/ .-/ (_) (_/ (_/ */ #include <iostream> #include <forward_list> using namespace std; int main() { }
#pragma once #include <tudocomp/util.hpp> #include <tudocomp/Compressor.hpp> #include <tudocomp/Range.hpp> #include <tudocomp_stat/StatPhase.hpp> #include <tudocomp/compressors/lz_pointer_jumping/FixedBufferPointerJumping.hpp> #include <tudocomp/compressors/lz_pointer_jumping/DynamicBufferPointerJumping.hpp> #include <tudocomp/compressors/lz_pointer_jumping/PointerJumping.hpp> // For default params #include <tudocomp/compressors/lz_trie/TernaryTrie.hpp> #include <tudocomp/coders/BinaryCoder.hpp> namespace tdc {namespace lz_pointer_jumping { template<typename lz_algo_t, typename coder_t, typename dict_t> class BaseLZPointerJumpingCompressor: public Compressor { using factorid_t = lz_common::factorid_t; using node_t = typename dict_t::node_t; using encoder_t = typename coder_t::Encoder; struct stats_t { IF_STATS(size_t dictionary_resets = 0); IF_STATS(size_t dict_counter_at_last_reset = 0); IF_STATS(size_t total_factor_count = 0); }; using lz_state_t = typename lz_algo_t::template lz_state_t<encoder_t, dict_t, stats_t>; using pointer_jumping_t = PointerJumping<DynamicBufferPointerJumping<lz_state_t>>; /// Max dictionary size before reset, 0 == unlimited const factorid_t m_dict_max_size {0}; /// Pointer Jumping jump width. const size_t m_jump_width {1}; public: inline BaseLZPointerJumpingCompressor(Config&& cfg): Compressor(std::move(cfg)), m_dict_max_size(this->config().param("dict_size").as_uint()), m_jump_width(this->config().param("jump_width").as_uint()) { CHECK_GE(m_jump_width, 1); CHECK_LE(m_jump_width, pointer_jumping_t::MAX_JUMP_WIDTH); CHECK_EQ(m_dict_max_size, 0) << "dictionary resets are currently not supported"; // TODO: need to fix and include this code fragment for dictionary resets /* // check if dictionary's maximum size was reached // (this will never happen if m_dict_max_size == 0) if(tdc_unlikely(dict.size() == m_dict_max_size)) { DCHECK_GT(dict.size(),0U); reset_dict(); factor_count = 0; IF_STATS(stat_dictionary_resets++); IF_STATS(stat_dict_counter_at_last_reset = m_dict_max_size); } */ } inline static Meta meta() { Meta m(Compressor::type_desc(), lz_algo_t::meta_name(), lz_algo_t::meta_desc()); m.param("coder", "The output encoder.") .strategy<coder_t>(TypeDesc("coder"), Meta::Default<BinaryCoder>()); m.param("lz_trie", "The trie data structure implementation.") .strategy<dict_t>(TypeDesc("lz_trie"), Meta::Default<lz_trie::TernaryTrie>()); m.param("dict_size", "the maximum size of the dictionary's backing storage before it " "gets reset (0 = unlimited)" ).primitive(0); m.param("jump_width", "jump width of the pointer jumping optimization" ).primitive(2); return m; } virtual void compress(Input& input, Output& out) override { const size_t n = input.size(); const size_t reserved_size = isqrt(n)*2; auto is = input.as_stream(); // Stats StatPhase phase(lz_algo_t::stat_phase_name()); stats_t stats; size_t factor_count = 0; // set up coder encoder_t coder(config().sub_config("coder"), out, NoLiterals()); // set up dictionary (the lz trie) dict_t dict(config().sub_config("lz_trie"), n, reserved_size + lz_state_t::initial_dict_size()); // set up lz algorithm state lz_state_t lz_state { factor_count, coder, dict, stats }; // set up initial state for trie search lz_state.reset_dict(); bool early_exit = lz_state.initialize_traverse_state(is); if (early_exit) return; // set up pointer jumping pointer_jumping_t pjm { lz_state, m_jump_width }; pjm.reset_buffer(); // main loop char c; continue_while: while(is.get(c)) { auto action = pjm.on_insert_char(static_cast<uliteral_t>(c)); if (action.buffer_full_and_found()) { // we can jump ahead lz_state.set_traverse_state(action.traverse_state()); pjm.reset_buffer(); } else if (action.buffer_full_and_not_found()) { // we need to manually add to the trie, // and create a new jump entry for(size_t i = 0; i < pjm.jump_buffer_size() - 1; i++) { uliteral_t const bc = pjm.jump_buffer(i); bool is_new_node = lz_state.dict_find_or_insert(bc); if (is_new_node) { // we got a new trie node in the middle of the // jump buffer, restart the jump buffer search lz_state.reset_traverse_state(bc); pjm.shift_buffer(i + 1); goto continue_while; } } { // the child node for the last char in the buffer // is also the node the new jump pointer jumps to. size_t i = pjm.jump_buffer_size() - 1; uliteral_t const bc = pjm.jump_buffer(i); bool is_new_node = lz_state.dict_find_or_insert(bc); // the next time we will skip over this through the jump pointer DCHECK(is_new_node); pjm.insert_jump_buffer(lz_state.get_traverse_state()); lz_state.reset_traverse_state(bc); pjm.reset_buffer(); } } else { // read next char... } } // process chars from last incomplete jump buffer for(size_t i = 0; i < pjm.jump_buffer_size(); i++) { uliteral_t const bc = pjm.jump_buffer(i); bool is_new_node = lz_state.dict_find_or_insert(bc); if (is_new_node) { lz_state.reset_traverse_state(bc); } } // take care of left-overs. We do not assume that the stream has a sentinel lz_state.end_of_input(static_cast<uliteral_t>(c)); IF_STATS( phase.log_stat("factor_count", stats.total_factor_count); phase.log_stat("dictionary_reset_counter", stats.dictionary_resets); phase.log_stat("max_factor_counter", stats.dict_counter_at_last_reset); ) } inline std::unique_ptr<Decompressor> decompressor() const override { using Decompressor = typename lz_algo_t::template Decompressor<coder_t>; // FIXME: construct AST and pass it std::stringstream cfg; cfg << "dict_size=" << to_string(m_dict_max_size); return Algorithm::instance<Decompressor>(cfg.str()); } }; }}//ns
#include "CCollectDlg.h" #include <process.h> CCollectDlg::CCollectDlg(int _objectIndex) : m_objectIndex(_objectIndex) { m_curSettingData.msgOptions[WM_CREATE] = true; m_curSettingData.msgOptions[WM_SHOWWINDOW] = true; m_curSettingData.msgOptions[WM_WINDOWPOSCHANGED] = true; m_curSettingData.msgOptions[WM_STYLECHANGED] = true; m_curSettingData.msgOptions[WM_NCACTIVATE] = true; m_curSettingData.msgOptions[WM_SETTEXT] = true; m_curSettingData.msgOptions[WM_SIZE] = true; m_curSettingData.msgOptions[WM_MOVE] = true; m_curSettingData.msgOptions[WM_DESTROY] = true; } CCollectDlg::~CCollectDlg() { } BOOL CCollectDlg::Start(HWND _parentHwnd, std::vector<std::wstring> _inputProcessName) { m_parentHwnd = _parentHwnd; m_queueNotEmpty = CreateEventW(NULL, TRUE, TRUE, NULL); InitializeCriticalSection(&m_readWriteCS); m_threadHandle = (HANDLE)_beginthreadex(NULL, 0, DisplayDataThread, (LPVOID)this, NULL, NULL); if (INVALID_HANDLE_VALUE == m_threadHandle) { return FALSE; } m_ownHwnd = CreateDialogParamW(NULL, MAKEINTRESOURCEW(IDD_COLLECTPAGE), NULL, CCollectDlg::RunProc, (LPARAM)this); // 캡션 추가 std::wstring showCaption = L""; for (auto x : _inputProcessName) { showCaption += x + L"|"; } showCaption.pop_back(); SetWindowTextW(m_ownHwnd, showCaption.data()); // 창띄우기 ShowWindow(m_ownHwnd, SW_SHOW); return TRUE; } BOOL CCollectDlg::End() { if (NULL != m_childOption) { m_childOption->End(0); delete m_childOption; m_childOption = NULL; } m_threadQuit = TRUE; SetEvent(m_queueNotEmpty); CloseHandle(m_queueNotEmpty); LeaveCriticalSection(&m_readWriteCS); DestroyWindow(m_collectListHwnd); DestroyWindow(m_ownHwnd); WaitForSingleObject(m_threadHandle, INFINITE); CloseHandle(m_threadHandle); m_threadHandle = INVALID_HANDLE_VALUE; DeleteCriticalSection(&m_readWriteCS); PostMessage(m_parentHwnd, WM_CHILDEND, (WPARAM)m_objectIndex, NULL); return 0; } INT_PTR CALLBACK CCollectDlg::RunProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CCollectDlg* pointerThis = (CCollectDlg*)GetWindowLongPtr(hwnd, GWLP_USERDATA); switch (uMsg) { case WM_INITDIALOG: SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lParam); pointerThis = (CCollectDlg*)lParam; pointerThis->m_ownHwnd = hwnd; pointerThis->InitDialog(hwnd, (HWND)(wParam), lParam); break; case WM_COMMAND: pointerThis->Command(hwnd, (int)(LOWORD(wParam)), (HWND)(lParam), (UINT)HIWORD(wParam)); break; case WM_CLOSE: pointerThis->End(); break; case WM_SETOPTION: BOOL succFunc = pointerThis->m_childOption->GetOption(&(pointerThis->m_curSettingData)); if (TRUE == succFunc) { if (FALSE == pointerThis->m_showMsgData) { PostMessageW(hwnd, WM_COMMAND, MAKEWPARAM(IDC_STARTSUSPEND, IDC_STARTSUSPEND), NULL); } // wParam, lParam Show/noShow if (TRUE == pointerThis->m_curSettingData.wParamShow) { pointerThis->m_lvCol.cx = 70; pointerThis->m_lvCol.pszText = L"wParam"; ListView_SetColumn(pointerThis->m_collectListHwnd, colIndex::wParam, &(pointerThis->m_lvCol)); } else { pointerThis->m_lvCol.cx = 0; pointerThis->m_lvCol.pszText = L"wParam"; ListView_SetColumn(pointerThis->m_collectListHwnd, colIndex::wParam, &(pointerThis->m_lvCol)); } if (TRUE == pointerThis->m_curSettingData.lParamShow) { pointerThis->m_lvCol.cx = 70; pointerThis->m_lvCol.pszText = L"lParam"; ListView_SetColumn(pointerThis->m_collectListHwnd, colIndex::lParam, &(pointerThis->m_lvCol)); } else { pointerThis->m_lvCol.cx = 0; pointerThis->m_lvCol.pszText = L"lParam"; ListView_SetColumn(pointerThis->m_collectListHwnd, colIndex::lParam, &(pointerThis->m_lvCol)); } } delete pointerThis->m_childOption; pointerThis->m_childOption = NULL; break; } return FALSE; } // 다이얼로그 초기화 BOOL CCollectDlg::InitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { InitCommonControls(); // Force the common controls DLL to be loaded. // window is a handle to my window that is already created. m_collectListHwnd = CreateWindowExW( 0, (LPWSTR)WC_LISTVIEWW, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER | LVS_SHOWSELALWAYS | LVS_REPORT, 11, 38, 776, 255, hwnd, NULL, NULL, NULL); memset(&m_lvCol, 0, sizeof(LVCOLUMNW)); m_lvCol.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; m_lvCol.iSubItem = 0; m_lvCol.fmt = LVCFMT_LEFT; m_lvCol.cx = 70; m_lvCol.pszText = L"Index"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::index, &m_lvCol); m_lvCol.cx = 80; m_lvCol.pszText = L"Process Name"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::pName, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"PID"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::pID, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"TID"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::tID, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"Msg Content"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::msgContent, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"Msg Code"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::msgCode, &m_lvCol); m_lvCol.cx = 20; m_lvCol.pszText = L"Msg Type"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::msgType, &m_lvCol); m_lvCol.cx = 70; m_lvCol.pszText = L"HWND"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::hwnd, &m_lvCol); m_lvCol.cx = 70; m_lvCol.pszText = L"wParam"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::wParam, &m_lvCol); m_lvCol.cx = 70; m_lvCol.pszText = L"lParam"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::lParam, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"Caption"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::caption, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"Class Name"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::className, &m_lvCol); m_lvCol.cx = 60; m_lvCol.pszText = L"Style"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::style, &m_lvCol); m_lvCol.cx = 100; m_lvCol.pszText = L"Detail"; ListView_InsertColumn(m_collectListHwnd, (int)colIndex::detail, &m_lvCol); memset(&m_lvItem, 0, sizeof(LVITEMW)); m_lvItem.mask = LVIF_TEXT; // Text Style m_lvItem.cchTextMax = 256; // Max size of test m_lvItem.iSubItem = 0; // col m_lvItem.iItem = 0; // row //Option 설정 PostMessageW(hwnd, WM_COMMAND, MAKEWPARAM(IDC_OPTION, IDC_OPTION), NULL); return TRUE; } void CCollectDlg::Command(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { BOOL SuccessFuc = FALSE; switch (id) { case IDCANCEL: case IDOK: //End(); break; case IDC_STARTSUSPEND: if (FALSE == m_showMsgData) { SendMessageW(GetDlgItem(hwnd, IDC_STARTSUSPEND), WM_SETTEXT, 0, (LPARAM)L"일시정지"); } else { SendMessageW(GetDlgItem(hwnd, IDC_STARTSUSPEND), WM_SETTEXT, 0, (LPARAM)L"시작"); } m_showMsgData = !m_showMsgData; break; case IDC_FILEOUT: SaveLog(hwnd); break; case IDC_OPTION: if (NULL != m_childOption) { break; } m_childOption = new COptionDlg(); m_childOption->Start(m_ownHwnd, &m_curSettingData); break; } } void CCollectDlg::InsertData(MsgData _inputMsgData) { if (FALSE == m_threadQuit) { EnterCriticalSection(&m_readWriteCS); if (TRUE == m_showMsgData) { m_inputMsg.push(_inputMsgData); } SetEvent(m_queueNotEmpty); LeaveCriticalSection(&m_readWriteCS); } } UINT CCollectDlg::DisplayDataThread(void * arg) { ((CCollectDlg*)arg)->DisplayData(); return 0; } void CCollectDlg::DisplayData() { std::queue<MsgData> inputMsgQeuue; m_saveDataList.reserve(1024); while (true) { HWND listHwnd = GetDlgItem(m_ownHwnd, IDC_COLLECTLIST); if (TRUE == m_threadQuit) { break; } EnterCriticalSection(&m_readWriteCS); std::swap(inputMsgQeuue, m_inputMsg); if (inputMsgQeuue.empty() && m_inputMsg.empty()) { ResetEvent(m_queueNotEmpty); } LeaveCriticalSection(&m_readWriteCS); if (TRUE == m_threadQuit) { break; } WaitForSingleObject(m_queueNotEmpty, INFINITE); while (!inputMsgQeuue.empty()) { SaveData curSaveData; MsgData inputMsgData = inputMsgQeuue.front(); inputMsgQeuue.pop(); if (65536 <= inputMsgData.msgCode) { continue; } if (false == m_curSettingData.msgOptions[inputMsgData.msgCode] && false == m_curSettingData.otherMsgShow) { continue; } if (TRUE == m_threadQuit) { break; } WCHAR buf[32] = { 0, }; // Line number(8자리수) 추가 wsprintf(buf, L"<%08d>", m_listRowIndex); curSaveData.index = std::wstring(buf); // Process Name 추가 curSaveData.pName = std::wstring(inputMsgData.processName); // Process ID 추가 curSaveData.pID = std::to_wstring(inputMsgData.processID); // Thread ID 추가 curSaveData.tID = std::to_wstring(inputMsgData.threadID); // Message Content 추가 if (NULL == wmToString[inputMsgData.msgCode]) { curSaveData.msgContent = L"unknown"; } else { curSaveData.msgContent = std::wstring(wmToString[inputMsgData.msgCode]); } // Message Code 추가 memset(buf, 0, 32); wsprintf(buf, L"%d", inputMsgData.msgCode); curSaveData.msgCode = std::wstring(buf); switch (inputMsgData.hookType) { case MSG_CALLWND: // Msg type 추가 curSaveData.msgType = L"S"; break; case MSG_CALLWNDRET: // Msg type 추가 curSaveData.msgType = L"R"; break; case MSG_GETMSG: // Msg type 추가 curSaveData.msgType = L"P"; break; } // wParam 추가 memset(buf, 0, 32); wsprintf(buf, L"0x%016X", inputMsgData.hwnd); curSaveData.hwnd = std::wstring(buf); // wParam 추가 memset(buf, 0, 32); wsprintf(buf, L"0x%016X", inputMsgData.wParam); curSaveData.wParam = std::wstring(buf); // lParam 추가 memset(buf, 0, 32); wsprintf(buf, L"0x%016X", inputMsgData.lParam); curSaveData.lParam = std::wstring(buf); switch (inputMsgData.msgCode) { case WM_CREATE: case WM_SHOWWINDOW: case WM_WINDOWPOSCHANGED: case WM_STYLECHANGED: case WM_NCACTIVATE: case WM_SETTEXT: case WM_SIZE: case WM_MOVE: case WM_DESTROY: WCHAR longBuf[MAX_PATH] = { 0, }; GetWindowTextW((HWND)inputMsgData.hwnd, longBuf, MAX_PATH); if (longBuf[0] != '\0') { curSaveData.caption += std::wstring(longBuf); } memset(longBuf, 0, MAX_PATH); GetClassNameW((HWND)inputMsgData.hwnd, longBuf, MAX_PATH); if (longBuf[0] != '\0') { curSaveData.className += std::wstring(longBuf); } WNDCLASSW wndClass; GetClassInfoW((HINSTANCE)inputMsgData.hInstance, longBuf, &wndClass); AddStyleString(&curSaveData.style, wndClass.style); break; } std::wstring optionData; size_t front = 0; switch (inputMsgData.msgCode) { case WM_CREATE: case WM_WINDOWPOSCHANGED: curSaveData.detail += std::wstring(inputMsgData.otherData); break; case WM_SETTEXT: curSaveData.detail += L"Text:" + std::wstring(inputMsgData.otherData); break; case WM_STYLECHANGED: optionData = std::wstring(inputMsgData.otherData); front = optionData.find(L':'); curSaveData.detail += L"Old"; AddStyleString(&curSaveData.detail, std::stoi(optionData.substr(front + 1)), 2); curSaveData.detail += L" New"; front = optionData.find_last_of(L':'); AddStyleString(&curSaveData.detail, std::stoi(optionData.substr(front + 1)), 2); break; case WM_SHOWWINDOW: curSaveData.detail += L"WindowShow:"; curSaveData.detail += inputMsgData.wParam ? L"TRUE" : L"FALSE"; switch (inputMsgData.lParam) { case SW_OTHERUNZOOM: curSaveData.detail += L" Status:SW_OTHERUNZOOM"; break; case SW_OTHERZOOM: curSaveData.detail += L" Status:SW_OTHERZOOM"; break; case SW_PARENTCLOSING: curSaveData.detail += L" Status:SW_PARENTCLOSING"; break; case SW_PARENTOPENING: curSaveData.detail += L" Status:SW_PARENTOPENING"; break; } break; case WM_NCACTIVATE: curSaveData.detail += L" IconDraw:"; curSaveData.detail += inputMsgData.wParam ? L"TRUE" : L"FALSE"; break; case WM_SIZE: switch (inputMsgData.wParam) { case SIZE_MAXHIDE: curSaveData.detail += L" ResizingType:SIZE_MAXHIDE"; break; case SIZE_MAXIMIZED: curSaveData.detail += L" ResizingType:SIZE_MAXIMIZED"; break; case SIZE_MAXSHOW: curSaveData.detail += L" ResizingType:SIZE_MAXSHOW"; break; case SIZE_MINIMIZED: curSaveData.detail += L" ResizingType:SIZE_MINIMIZED"; break; case SIZE_RESTORED: curSaveData.detail += L" ResizingType:SIZE_RESTORED"; break; } curSaveData.detail += L" Width:" + std::to_wstring(LOWORD(inputMsgData.lParam)); curSaveData.detail += L" Height:" + std::to_wstring(HIWORD(inputMsgData.lParam)); break; case WM_MOVE: curSaveData.detail += L" CX:" + std::to_wstring(LOWORD(inputMsgData.lParam)); curSaveData.detail += L" CY:" + std::to_wstring(HIWORD(inputMsgData.lParam)); break; } if (TRUE == m_threadQuit) { break; } m_lvItem.iItem = m_listRowIndex++; // choose item m_lvItem.iSubItem = (int)colIndex::index; m_lvItem.pszText = &curSaveData.index[0]; ListView_InsertItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::pName; m_lvItem.pszText = &curSaveData.pName[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::pID; m_lvItem.pszText = &curSaveData.pID[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::tID; m_lvItem.pszText = &curSaveData.tID[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::msgContent; m_lvItem.pszText = &curSaveData.msgContent[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::msgCode; m_lvItem.pszText = &curSaveData.msgCode[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::msgType; m_lvItem.pszText = &curSaveData.msgType[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::hwnd; m_lvItem.pszText = &curSaveData.hwnd[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::wParam; m_lvItem.pszText = &curSaveData.wParam[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::lParam; m_lvItem.pszText = &curSaveData.lParam[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::caption; m_lvItem.pszText = &curSaveData.caption[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::className; m_lvItem.pszText = &curSaveData.className[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::style; m_lvItem.pszText = &curSaveData.style[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); m_lvItem.iSubItem = (int)colIndex::detail; m_lvItem.pszText = &curSaveData.detail[0]; ListView_SetItem(m_collectListHwnd, (LPARAM)&m_lvItem); ListView_Scroll(m_collectListHwnd, 0, m_listRowIndex - 1); m_saveDataList.push_back(curSaveData); } } } void CCollectDlg::AddStyleString(std::wstring *_inputString, UINT _inputStyle, int _type) { std::wstring styleString = L""; if (WS_BORDER & _inputStyle) { styleString += L"WS_BORDER|"; } if (WS_CAPTION & _inputStyle) { styleString += L"WS_CAPTION|"; } if (WS_CHILD & _inputStyle) { styleString += L"WS_CHILD|"; } if (WS_CHILDWINDOW & _inputStyle) { styleString += L"WS_CHILDWINDOW|"; } if (WS_CLIPCHILDREN & _inputStyle) { styleString += L"WS_CLIPCHILDREN|"; } if (WS_CLIPSIBLINGS & _inputStyle) { styleString += L"WS_CLIPSIBLINGS|"; } if (WS_DISABLED & _inputStyle) { styleString += L"WS_DISABLED|"; } if (WS_DLGFRAME & _inputStyle) { styleString += L"WS_DLGFRAME|"; } if (WS_GROUP & _inputStyle) { styleString += L"WS_GROUP|"; } if (WS_HSCROLL & _inputStyle) { styleString += L"WS_HSCROLL|"; } if (WS_ICONIC & _inputStyle) { styleString += L"WS_ICONIC|"; } if (WS_MAXIMIZE & _inputStyle) { styleString += L"WS_MAXIMIZE|"; } if (WS_MAXIMIZEBOX & _inputStyle) { styleString += L"WS_MAXIMIZEBOX|"; } if (WS_MINIMIZE & _inputStyle) { styleString += L"WS_MINIMIZE|"; } if (WS_MINIMIZEBOX & _inputStyle) { styleString += L"WS_MINIMIZEBOX|"; } if (WS_OVERLAPPED & _inputStyle) { styleString += L"WS_OVERLAPPED|"; } if (WS_OVERLAPPEDWINDOW & _inputStyle) { styleString += L"WS_OVERLAPPEDWINDOW|"; } if (WS_POPUP & _inputStyle) { styleString += L"WS_POPUP|"; } if (WS_POPUPWINDOW & _inputStyle) { styleString += L"WS_POPUPWINDOW|"; } if (WS_SIZEBOX & _inputStyle) { styleString += L"WS_SIZEBOX|"; } if (WS_SYSMENU & _inputStyle) { styleString += L"WS_SYSMENU|"; } if (WS_TABSTOP & _inputStyle) { styleString += L"WS_TABSTOP|"; } if (WS_THICKFRAME & _inputStyle) { styleString += L"WS_THICKFRAME|"; } if (WS_TILED & _inputStyle) { styleString += L"WS_TILED|"; } if (WS_TILEDWINDOW & _inputStyle) { styleString += L"WS_TILEDWINDOW|"; } if (WS_VISIBLE & _inputStyle) { styleString += L"WS_VISIBLE|"; } if (WS_VSCROLL & _inputStyle) { styleString += L"WS_VSCROLL"; } if (!styleString.empty()) { if (L'|' == styleString.back()) { styleString.pop_back(); } if (1 == _type) { *_inputString += styleString; } else if (2 == _type) { *_inputString += L"Style: " + styleString; } } } BOOL CCollectDlg::SaveLog(HWND hwnd) { //HWND ListBoxHwnd = GetDlgItem(hwnd, IDC_COLLECTLIST); //LRESULT count = SendMessageW(ListBoxHwnd, LB_GETCOUNT, 0, 0); // 저장 경로 지정 OPENFILENAMEW oFile; WCHAR saveFileName[MAX_PATH] = L"log"; memset(&oFile, 0, sizeof(oFile)); oFile.lStructSize = sizeof(oFile); oFile.hwndOwner = NULL; oFile.lpstrFilter = L"Text Files (*.txt)\0*.txt\0CSV Files (*.csv)\0*.csv\0All Files (*.*)\0*.*\0"; oFile.lpstrFile = saveFileName; oFile.nMaxFile = MAX_PATH; oFile.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; oFile.lpstrDefExt = (LPCWSTR)L"txt"; BOOL succFunc = GetSaveFileNameW(&oFile); if (FALSE == succFunc) { MessageBoxW(NULL, L"저장 취소", NULL, MB_OK); return FALSE; } HANDLE fileHandle = CreateFileW( saveFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == fileHandle) { return FALSE; } DWORD returnLen = 0; LRESULT textLen = 0; LPWSTR curText = NULL; // UNICODE(Little Endian) 설정(WCHAR 출력) //unsigned char mark[2] = { 0xFF, 0xFE }; // UTF-8 //unsigned char mark[3] = { 0xEF, 0xBB, 0xBF }; //WriteFile(fileHandle, &mark, 2, &returnLen, NULL); std::string header = "index,pName,pID,tID,msgContent,msgCode,msgType,wParam,lParam,caption,className,style,detail\n"; WriteFile(fileHandle, header.data(), header.size(), &returnLen, NULL); ULONGLONG count = m_saveDataList.size(); for (UINT i = 0; i < count; i++) { std::string ouputTxtA = ""; std::wstring outputTxtW = L""; outputTxtW += m_saveDataList[i].index + L","; outputTxtW += m_saveDataList[i].pName + L","; outputTxtW += m_saveDataList[i].pID + L","; outputTxtW += m_saveDataList[i].tID + L","; outputTxtW += m_saveDataList[i].msgContent + L","; outputTxtW += m_saveDataList[i].msgCode + L","; outputTxtW += m_saveDataList[i].msgType + L","; outputTxtW += m_saveDataList[i].wParam + L","; outputTxtW += m_saveDataList[i].lParam + L","; outputTxtW += m_saveDataList[i].caption + L","; outputTxtW += m_saveDataList[i].className + L","; outputTxtW += m_saveDataList[i].style + L","; outputTxtW += m_saveDataList[i].detail + L"\n"; ouputTxtA = wcs2mbs(outputTxtW, std::locale("kor")); // 파일 쓰기 WriteFile(fileHandle, ouputTxtA.data(), ouputTxtA.size(), &returnLen, NULL); delete[] curText; returnLen = 0; textLen = 0; curText = NULL; } CloseHandle(fileHandle); MessageBoxW(NULL, L"저장 완료", L"Success", MB_OK); return TRUE; } std::string CCollectDlg::wcs2mbs(std::wstring const & str, std::locale const & loc) { typedef std::codecvt <wchar_t, char, std::mbstate_t> codecvt_t; std::codecvt <wchar_t, char, std::mbstate_t> const& codecvt = std::use_facet<codecvt_t>(loc); std::mbstate_t state = std::mbstate_t(); std::vector<char> buf((str.size() + 1) * codecvt.max_length()); wchar_t const* in_next = str.c_str(); char* out_next = &buf[0]; codecvt_t::result r = codecvt.out(state, str.c_str(), str.c_str() + str.size(), in_next, &buf[0], &buf[0] + buf.size(), out_next); return std::string(&buf[0]); }
// Fill out your copyright notice in the Description page of Project Settings. #include "MenuButton.h" #include "Runtime/UMG/Public/Blueprint/WidgetTree.h" #include "UObject/ConstructorHelpers.h" bool UMenuButton::Initialize() { auto success = Super::Initialize(); WidgetTree->RootWidget = ButtonCustom; ButtonCustom->AddChild(m_text); return success; } void UMenuButton::OnClick(std::function<void()> fn) { on_click_ = fn; ButtonCustom->OnClicked.AddDynamic(this, &UMenuButton::Click); } void UMenuButton::Click() { on_click_(); }
/* * Copyright (c) 2014, Julien Bernard * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <mm/colormap.h> #include <fstream> #include <iostream> namespace mm { void colormap::output_to_ppm(std::ostream& file) const { file << "P3\n"; file << this->width() << ' ' << this->height() << '\n'; file << static_cast<unsigned>(mm::color::max) << '\n'; for (size_type y = 0; y < this->height(); ++y) { for (size_type x = 0; x < this->width(); ++x) { auto c = this->get(x, y); file << static_cast<unsigned>(c.red_channel()) << ' ' << static_cast<unsigned>(c.green_channel()) << ' ' << static_cast<unsigned>(c.blue_channel()) << ' '; } file << '\n'; } } void colormap::output_to_ppm(const std::string& filename) const { std::ofstream file(filename); output_to_ppm(file); } }
//Дан целочисленный массив размера N. Удалить из массива все элементы, встречающиеся ровно два раза, и вывести размер полученного массива и его содержимое. #include <iostream> #include <locale.h> using namespace std; void shift(int i, int N, int* A) { for (int j = i; j < N; j++) { A[j] = A[j + 1]; //записываем, игнорируя(тем самым удаляя) значение элемента, которому был равен текущий элемент } } int main() { int N, i; setlocale(LC_ALL, "Rus"); cout << "введите N>>"; cin >> N; int* A = new int[N]; cout << "введите элементы массива A>>"; for (i = 0; i < N; i++) { cin >> A[i]; } i = 0; while (i != (N - 1)) //пока индекс текущего элемента не будет равен кол-ву всех элементов минус 1, т.е. не станет последним элементом { for (int q = i + 1; q < N; q++) { if (A[i] == A[q]) //если какой-либо последующий элемент равен текущему, то на место него записывается элемент, следующий после него, и так далее { shift(i, N, A); //функция удаления одного элемента с индексом i и сдвигом массива N--; q--; if (q != (N - 1)) shift(q, N, A); //если удаляемый элемент - непоследний, тогда функция сдвига массива на один, иначе не сдвигаем; N--; i = -1; //обнуляем счетчик } } i++; //переходим к следующему элементу } cout << "размер полученного массива>>" << N << "\n"; cout << "измененный массив A>>"; for (i = 0; i < N; i++) { cout << A[i] << " "; } delete[] A; // очистка памяти return 0; }
/***************************************************************************************************** * 剑指offer第34题 * 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 * * Input: * Output: 第N个丑数 * * Note: * 关键在于思路 链接:https://www.nowcoder.com/questionTerminal/6aa9e04fc3794f68acf8778237ba065b 来源:牛客网 首先从丑数的定义我们知道,一个丑数的因子只有2,3,5,那么丑数p = 2 ^ x * 3 ^ y * 5 ^ z, 换句话说一个丑数一定由另一个丑数乘以2或者乘以3或者乘以5得到,那么我们从1开始乘以2,3,5, 就得到2,3,5三个丑数,在从这三个丑数出发乘以2,3,5就得到4,6,10,6,9,15,10,15,25九个丑数, 我们发现这种方法会得到重复的丑数,而且我们题目要求第N个丑数,这样的方法得到的丑数也是 无序的。那么我们可以维护三个队列: (1)丑数数组: 1 乘以2的队列:2 乘以3的队列:3 乘以5的队列:5 选择三个队列头最小的数2加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; (2)丑数数组:1,2 乘以2的队列:4 乘以3的队列:3,6 乘以5的队列:5,10 选择三个队列头最小的数3加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; (3)丑数数组:1,2,3 乘以2的队列:4,6 乘以3的队列:6,9 乘以5的队列:5,10,15 选择三个队列头里最小的数4加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; (4)丑数数组:1,2,3,4 乘以2的队列:6,8 乘以3的队列:6,9,12 乘以5的队列:5,10,15,20 选择三个队列头里最小的数5加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; ( 5)丑数数组:1,2,3,4,5 乘以2的队列:6,8,10, 乘以3的队列:6,9,12,15 乘以5的队列:10,15,20,25 选择三个队列头里最小的数6加入丑数数组,但我们发现,有两个队列头都为6,所以我们 弹出两个队列头,同时将12,18,30放入三个队列; * author: lcxanhui@163.com * time: 2019.5.16 ******************************************************************************************************/ #include<iostream> #include<vector> #include<algorithm> using namespace std; int UglyNum(int index) { // 0-6的丑数分别为0-6 if (index < 7) return index; vector<int> res(index); res[0] = 1; //t2,t3,t5分别为三个队列的指针,res[i]为从队列头选出来的最小数 int t2 = 0, t3 = 0, t5 = 0; for (int i = 1; i < index; i++) { //选出三个队列头最小的数 res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5)); //这三个if有可能进入一个或者多个,进入多个是三个队列头最小的数有多个的情况 if (res[i] == res[t2] * 2) t2++; if (res[i] == res[t3] * 3) t3++; if (res[i] == res[t5] * 5) t5++; } return res[index - 1]; } int main(void) { int index; cin >> index; int res = UglyNum(index); cout << res; return 0; }
#pragma once template <typename Type> tensor<Type>& tensor<Type>::transpose() { auto const copy = *this; cuda_blas::_transpose(copy.data_, data_, shape_); std::swap(shape_.first, shape_.second); return *this; } template <typename Type> tensor<Type> transpose(tensor<Type> tensor) { return tensor.transpose(); } template <typename Type> tensor<Type>& tensor<Type>::dot(tensor<Type> const& other) { if (shape_.second != other.shape_.first) throw std::runtime_error("Invalid shapes - " + to_string(shape_) + " and " + to_string(other.shape_) + "!"); auto const n = shape_.first; auto const m = shape_.second; auto const p = other.shape_.second; auto const other_transposed = std::move(cuda_blas::transpose(other)); tensor<Type> result; result.shape_ = { n, p }; result.data_ = create_tensor_data<Type>(n * p); cuda_blas::_matrix_multiply(data_, other_transposed.data_, result.data_, n, m, p); return (*this = std::move(result)); } template <typename Type> tensor<Type> dot(tensor<Type> lhs, tensor<Type> const& rhs) { auto result = lhs.dot(rhs); return result; } template <typename Type> template<uint_fast8_t Axis> tensor<Type> tensor<Type>::sum() const { if (Axis == 0) { tensor<Type> result({ 1, shape_.second }); auto s = [] __device__(Type first, Type second) { return first + second; }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } if (Axis == 1) { tensor<Type> result({ shape_.first, 1 }); auto s = [] __device__(Type first, Type second) { return first + second; }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> Type tensor<Type>::sum() const { Type sum = 0; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = 0; j < shape_.second; ++j) sum += data_[i * shape_.second + j]; return sum; } template <typename Type> template <uint_fast8_t Axis> tensor<Type> tensor<Type>::max() const { if (Axis == 0) { tensor<Type> result({ 1, shape_.second }); auto s = [] __device__(Type first, Type second) { return fmaxf(float(first), float(second)); }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } if (Axis == 1) { tensor<Type> result({ shape_.first, 1 }); auto s = [] __device__(Type first, Type second) { return fmaxf(float(first), float(second)); }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> Type tensor<Type>::max() const { Type max = data_[0]; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = 0; j < shape_.second; ++j) max = std::max(data_[i * shape_.second + j], max); return max; } template <typename Type> template <uint_fast8_t Axis> tensor<Type> tensor<Type>::min() const { if (Axis == 0) { tensor<Type> result({ 1, shape_.second }); auto s = [] __device__(Type first, Type second) { return fminf(float(first), float(second)); }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } if (Axis == 1) { tensor<Type> result({ shape_.first, 1 }); auto s = [] __device__(Type first, Type second) { return fminf(float(first), float(second)); }; cuda_blas::_aggregate<Type, Axis, decltype(s)>(data_, result.data_, shape_, s); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> Type tensor<Type>::min() const { Type min = data_[0]; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = 0; j < shape_.second; ++j) min = std::min(data_[i * shape_.second + j], min); return min; } template <typename Type> template <uint_fast8_t Axis> tensor<size_t> tensor<Type>::argmax() const { if (Axis == 0) { tensor<size_t> result({ 1, shape_.second }); cuda_blas::_argmax<Type, Axis>(data_, result.data_, shape_); return result; } if (Axis == 1) { tensor<size_t> result({ shape_.first, 1 }); cuda_blas::_argmax<Type, Axis>(data_, result.data_, shape_); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> tensor_index tensor<Type>::argmax() const { tensor_index max = { 0,0 }; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = 0; j < shape_.second; ++j) if ((data_[i * shape_.second + j] > data_[max.first * shape_.second + max.second])) max = tensor_index{ i, j }; return max; } template <typename Type> template <uint_fast8_t Axis> tensor<size_t> tensor<Type>::argmin() const { if (Axis == 0) { tensor<size_t> result({ 1, shape_.second }); cuda_blas::_argmin<Type, Axis>(data_, result.data_, shape_); return result; } if (Axis == 1) { tensor<size_t> result({ shape_.first, 1 }); cuda_blas::_argmin<Type, Axis>(data_, result.data_, shape_); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> tensor_index tensor<Type>::argmin() const { tensor_index min = { 0,0 }; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = 0; j < shape_.second; ++j) if ((data_[i * shape_.second + j] < data_[min.first * shape_.second + min.second])) min = tensor_index{ i, j }; return min; } template <typename Type> template <typename Reduction, uint_fast8_t Axis> tensor<Type> tensor<Type>::reduce(Reduction reduction) const { if (Axis == 0) { tensor<Type> result({ 1, shape_.second }); cuda_blas::_aggregate<Type, Axis, Reduction>(data_, result.data_, shape_, reduction); return result; } if (Axis == 1) { tensor<Type> result({ shape_.first, 1 }); cuda_blas::_aggregate<Type, Axis, Reduction>(data_, result.data_, shape_, reduction); return result; } throw std::runtime_error("Invalid axis template parameter!"); } template <typename Type> template <typename Reduction> Type tensor<Type>::reduce(Reduction reduction) const { Type r = data_[0]; for (int64_t i = 0; i < shape_.first; ++i) for (int64_t j = i == 0 ? 1 : 0; j < shape_.second; ++j) r = reduction(data_[i * shape_.second + j], r); return r; } template <typename Type> tensor<Type>& tensor<Type>::log() { cuda_blas::_apply(data_, [] __device__ (Type value) { return logf(float(value)); }, shape_); return *this; } template <typename Type> tensor<Type> log(tensor<Type> tensor) { return tensor.log(); } template <typename Type> tensor<Type>& tensor<Type>::exp() { cuda_blas::_apply(data_, [] __device__ (Type value) { return expf(float(value)); }, shape_); return *this; } template <typename Type> tensor<Type> exp(tensor<Type> tensor) { return tensor.exp(); } template <typename Type> tensor<Type>& tensor<Type>::abs() { cuda_blas::_apply(data_, [] __device__(Type value) { return fabsf(float(value)); }, shape_); return *this; } template <typename Type> tensor<Type> abs(tensor<Type> tensor) { return tensor.abs(); } template <typename Type> tensor<Type>& tensor<Type>::sqrt() { cuda_blas::_apply(data_, [] __device__(Type value) { return sqrtf(float(value)); }, shape_); return *this; } template <typename Type> tensor<Type> sqrt(tensor<Type> tensor) { return tensor.sqrt(); } template <typename Type> tensor<Type>& tensor<Type>::maximum(Type max) { cuda_blas::_apply(data_, [max] __device__(Type value) { return fmaxf(float(value), float(max)); }, shape_); return *this; } template <typename Type> tensor<Type> maximum(tensor<Type> tensor, Type max) { return tensor.maximum(max); } template <typename Type> tensor<Type>& tensor<Type>::minimum(Type min) { cuda_blas::_apply(data_, [min] __device__(Type value) { return fminf(float(value), float(min)); }, shape_); return *this; } template <typename Type> tensor<Type> minimum(tensor<Type> tensor, Type min) { return tensor.minimum(min); } template <typename Type> template <typename Function> tensor<Type> tensor<Type>::apply(Function func) { cuda_blas::_apply(data_, func, shape_); return *this; } template <typename Type, typename Function> tensor<Type> apply(tensor<Type> tensor, Function func) { return tensor.apply(func); } template<typename Type, typename Function> tensor<Type> produce(tensor<Type> lhs, tensor<Type> const& rhs, Function function) { if (lhs.shape().first == rhs.shape().first && rhs.shape().second == 1) cuda_blas::_produce<Type, Function, 0>(lhs.data_, rhs.data_, lhs.data_, function, lhs.shape_); else if (lhs.shape().second == rhs.shape().second && rhs.shape().first == 1) cuda_blas::_produce<Type, Function, 1>(lhs.data_, rhs.data_, lhs.data_, function, lhs.shape_); else if (lhs.shape().first == rhs.shape().first && lhs.shape().second == rhs.shape().second) cuda_blas::_produce(lhs.data_, rhs.data_, lhs.data_, function, lhs.shape_); else throw std::runtime_error("Invalid shapes - " + to_string(lhs.shape()) + " and " + to_string(rhs.shape()) + "!"); return lhs; }
/*************************************************************************** * Filename : WindowsWindow.h * Name : Ori Lazar * Date : 29/10/2019 * Description : Contains the windows OS specific window setup declarations. .---. .'_:___". |__ --==| [ ] :[| |__| I=[| / / ____| |-/.____.' /___\ /___\ ***************************************************************************/ #pragma once #include "Core/Window.h" #include "Core/Renderer/RenderingContext.h" #include <GLFW/glfw3.h> namespace Exalted { class WindowsWindow : public Window { public: WindowsWindow(const WindowProperties& properties); virtual ~WindowsWindow(); void OnUpdate() override; void SetVSync(bool enabled) override; inline void SetEventCallback(const EventCallbackFn& callback) override { m_WindowData.EventCallback = callback; } inline unsigned int GetWindowWidth() const override { return m_WindowData.Properties.Width; } inline unsigned int GetWindowHeight() const override { return m_WindowData.Properties.Height; } inline float GetTime() const override { return static_cast<float>(glfwGetTime()); } inline bool IsVSync() const override { return m_WindowData.VSync; } inline void* GetNativeWindow() const override { return m_Window; } private: virtual void Shutdown(); virtual void Init(const WindowProperties& properties); void InitGLFWWindow(); void SetGLFWConfigurations(); void SetGLFWCallbacks() const; private: struct WindowData { WindowProperties Properties; bool VSync; EventCallbackFn EventCallback; }; GLFWwindow* m_Window; Scope<RenderingContext> m_RenderingContext; WindowData m_WindowData; }; }
#include "timer.hpp" #include "object.hpp" #include "event.hpp" namespace GameEngine { Timer::Timer(void) { mNode.key = 0; mEvent = Event::sDummy; mEventLoop = &EventLoop::sMain; mPool = NULL; } Timer::Timer(tick_t tick, EventLoop *eventLoop, Event *event) { mNode.key = tick; mEventLoop = eventLoop; mEvent = event; mPool = NULL; } void Timer::SetTick(tick_t tick) { mNode.key = tick; } void Timer::SetEvent(Event *event) { mEvent = event; } void Timer::SetEventLoop(EventLoop *eventLoop) { mEventLoop = eventLoop; } void Timer::Open(TimerPool *pool) { pool->Enqueue(this); } void Timer::Close(void) { TimerPool *pool = mPool; if (pool == NULL) return; pool->Dequeue(this); } bool Timer::IsClosed(void) { return mPool == NULL; } void Timer::Lock(void) { mLock.lock(); } void Timer::Unlock(void) { mLock.unlock(); } ThreadedTimerPool::ThreadedTimerPool(tick_t startTick, int hz) { mLastTick = mTick = startTick; mHZ = hz; mThread = NULL; crh_init(&mCRH); crh_set_base(&mCRH, startTick); } ThreadedTimerPool::~ThreadedTimerPool(void) { Stop(); } void ThreadedTimerPool::Enqueue(Timer *timer) { mLock.lock(); timer->Lock(); if (timer->mPool == NULL) { if (crh_insert(&mCRH, &timer->mNode)) { if (timer->mEventLoop) timer->mEventLoop->Enqueue(timer->mEvent); } else timer->mPool = this; } timer->Unlock(); mLock.unlock(); mEventCV.notify_one(); } void ThreadedTimerPool::Dequeue(Timer *timer) { mLock.lock(); timer->Lock(); if (timer->mPool == this) { crh_remove(&mCRH, &timer->mNode); timer->mPool = NULL; } timer->Unlock(); mLock.unlock(); } void TimerThreadHelper::operator()(void) { mPool->DoThread(); } void ThreadedTimerPool::Start(void) { mThreadExit = false; mThreadPause = true; mThread = new std::thread(TimerThreadHelper(this)); } void ThreadedTimerPool::Stop(void) { mThreadExit = true; Pause(); mThread->join(); delete mThread; mThread = NULL; } void ThreadedTimerPool::Pause(void) { mThreadPause = true; mEventCV.notify_one(); } void ThreadedTimerPool::Resume(void) { mThreadPause = false; mEventCV.notify_one(); } void ThreadedTimerPool::DoThread() { mLock.lock(); mLastTime = std::chrono::system_clock::now(); mLastTick = mTick; while (!mThreadExit) { while (!mThreadPause) { tick_t tickDelta = mLastTick + (std::chrono::system_clock::now() - mLastTime).count() * ((double)mHZ * std::chrono::system_clock::period::num / std::chrono::system_clock::period::den); tickDelta -= mTick; while (tickDelta) { tick_t step = crh_max_step(&mCRH); if (step > tickDelta || step == 0) { step = tickDelta; mTick += step; crh_set_base(&mCRH, mTick); break; } mTick += step; tickDelta -= step; crh_node_t node = crh_set_base(&mCRH, mTick); if (node == NULL) continue; crh_node_t cur = node; while (1) { Timer *timer = (Timer *)((uintptr_t)cur - (uintptr_t)(&((Timer *)0)->mNode)); timer->Lock(); crh_remove(&mCRH, &timer->mNode); timer->mPool = NULL; if (timer->mEventLoop) timer->mEventLoop->Enqueue(timer->mEvent); cur->next->prev = cur->prev; cur->prev->next = cur->next; if (cur == cur->next) { timer->Unlock(); break; } else { cur = cur->next; timer->Unlock(); } } }; tick_t waitTick = crh_max_step(&mCRH); if (waitTick == 0) waitTick = mHZ; waitTick = (mTick - mLastTick + waitTick) / (double)mHZ / std::chrono::system_clock::period::num * std::chrono::system_clock::period::den; std::chrono::system_clock::time_point waitPoint = mLastTime + std::chrono::system_clock::duration(waitTick); mEventCV.wait_until(mLock, waitPoint); } mLastTime = std::chrono::system_clock::now(); mLastTick = mTick; if (!mThreadExit) mEventCV.wait(mLock); } mLock.unlock(); } tick_t ThreadedTimerPool::GetTick(void) { tick_t tick; mLock.lock(); if (mThreadPause) { tick = mTick; } else { tick = mLastTick + (std::chrono::system_clock::now() - mLastTime).count() * ((double)mHZ * std::chrono::system_clock::period::num / std::chrono::system_clock::period::den); } mLock.unlock(); return tick; } MonoTimerPool::MonoTimerPool(void) { mTick = 0; crh_init(&mCRH); crh_set_base(&mCRH, mTick); } MonoTimerPool::MonoTimerPool(tick_t startTick) { mTick = startTick; crh_init(&mCRH); crh_set_base(&mCRH, mTick); } MonoTimerPool::~MonoTimerPool(void) { } void MonoTimerPool::Enqueue(Timer *timer) { timer->Lock(); if (timer->mPool == NULL) { if (crh_insert(&mCRH, &timer->mNode)) { Event *event = timer->mEvent; timer->Unlock(); event->Activate(); return; } else timer->mPool = this; } timer->Unlock(); } void MonoTimerPool::Dequeue(Timer *timer) { timer->Lock(); if (timer->mPool == this) { crh_remove(&mCRH, &timer->mNode); timer->mPool = NULL; } timer->Unlock(); } void MonoTimerPool::SetTick(tick_t tick) { tick_t tickDelta = tick - mTick; while (tickDelta) { tick_t step = crh_max_step(&mCRH); if (step > tickDelta || step == 0) { step = tickDelta; mTick += step; crh_set_base(&mCRH, mTick); break; } mTick += step; tickDelta -= step; crh_node_t node = crh_set_base(&mCRH, mTick); if (node == NULL) continue; crh_node_t cur = node; while (1) { Timer *timer = (Timer *)((uintptr_t)cur - (uintptr_t)(&((Timer *)0)->mNode)); timer->Lock(); crh_remove(&mCRH, &timer->mNode); timer->mPool = NULL; Event *event = timer->mEvent; cur->next->prev = cur->prev; cur->prev->next = cur->next; if (cur == cur->next) { timer->Unlock(); event->Activate(); break; } else { cur = cur->next; timer->Unlock(); event->Activate(); } } } mTick = tick; crh_set_base(&mCRH, mTick); } tick_t MonoTimerPool::GetTick(void) { return mTick; } };
#include <iostream> #include <queue> #include <list> #include <cstdio> using namespace std; int main ( int argc , char * argv[] ) { int t; list<int> node[61]; int m[61][61]; cin >> t; getchar(); while ( t-- ) { char ch; int n = 0; node[0].clear(); while ( (ch = getchar()) != '\n' ) { n++; if ( ch == 'Y' ) { node[0].push_back(n-1); m[0][n-1] = 1; } else { m[0][n-1] = 0; } } for ( int i = 1 ; i < n ; i++ ) { node[i].clear(); n = 0; while ( (ch = getchar()) != '\n' ) { n++; if ( ch == 'Y' ) { node[i].push_back(n-1); m[i][n-1] = 1; } else { m[i][n-1] = 0; } } } /*cout << "-----------------------------------------------------------" << endl; for ( int i = 0 ; i < n ; i++ ) { cout << "Node : " << i << " -> "; for ( list<int>::iterator itr = node[i].begin() ; itr != node[i].end() ; itr++ ) { cout << *itr << " "; } cout << endl; } */ int max_count = 0 , max_n = 0; for ( int i = 0 ; i < n ; i++ ) { int count = 0; for ( list<int>::iterator itr = node[i].begin() ; itr != node[i].end() ; itr++ ) { int child = *itr; for ( list<int>::iterator itr_c = node[child].begin() ; itr_c != node[child].end() ; itr_c++ ) { if ( *itr_c != i && m[*itr_c][i] == 0 ) { count ++; //cout << "Adding count for grand_child = " << *itr_c << " and parent = " << i << endl; } } } if ( count > max_count ) { max_count = count; max_n = i; } } cout << max_n << " " << max_count << endl; } return 0; }
// distance.cpp // increment counter variable with ++ operator // uses unnamed temporary object #include <iostream> using namespace std; #include "distance.h" //Display as 2'-9" format void Distance::ShowDist() const { std::cout << feet() << "\'- " << inches() << "\"" << std::endl; } // Create operator to combine two distances Distance Distance::operator+(Distance rhs) const { int feet = feet_ + rhs.feet_; float inches = inches_ + rhs.inches_; // Update if more than 12 inches if (inches > 12.0) { inches -= 12.0; feet++; } return Distance(feet, inches); } // Define "<<"" operator // returning ref to output stream "os" // Do not include '\n' or endl, let user define std::ostream &operator<<(std::ostream &os, const Distance &distance) { os << "feet: " << distance.feet_ << " inches: " << distance.inches_; return os; } // Define "-" operator // Distance Distance::operator - (Distance rhs) const // { // int ft = feet_ - rhs.feet_; // float in = 0; // // Update if less than 12 inches // if (inches_ < rhs.inches_) // { // ft -= 1; // in = (inches_ + 12) - rhs.inches_; // } // return Distance(ft, in); // } // Two operators Distance operator - (Distance lhs, Distance rhs) //friend operator { int ft = lhs.feet_ - rhs.feet_; float in = 0; // Update if less than 12 inches if (lhs.inches_ < rhs.inches_) { ft -= 1; in = (lhs.inches_ + 12) - rhs.inches_; } return Distance(ft, in); } // Update function void Distance::update_distance(int ft, float in) { set_feet(ft); set_inches(in); } //Compare function bool Distance::operator<(Distance rhs) const { float ft1 = feet_ + inches_ / 12.0; //convert inches to feet float ft2 = rhs.feet_ + rhs.inches_ / 12.0; if (ft1 < ft2) { return true; } else { return false; } } //Equals operator "==", both ft and in are the same bool Distance::operator==(Distance rhs) const { float ft1 = feet_ + inches_ / 12.0; float ft2 = rhs.feet_ + rhs.inches_ / 12.0; return (ft1 == ft2) ? true : false; } Distance Distance::operator = (Distance& rhs) { std::cout << "Assign operator invoked!" << std::endl; feet_ = rhs.feet_; inches_ = rhs.inches_; return Distance(feet_, inches_); } Distance::Distance(const Distance& dist) { std:cout << "Copy constructed invoked!" << std::endl; feet_ = dist.feet_; inches_ = dist.inches_; }
#ifndef GEOMETRYVIEWPROVIDER_H_ #define GEOMETRYVIEWPROVIDER_H_ #include <QObject> #include <QPair> #include <QHash> #include "moduleBase/ModuleType.h" class vtkActor; class vtkPolyData; namespace GUI { class MainWindow; } namespace Geometry { class GeometryData; class GeometrySet; class GeometryDatum; } namespace MainWidget { class PreWindow; class GeometryViewData; class GeometryViewProvider: public QObject { Q_OBJECT public: GeometryViewProvider(GUI::MainWindow* mainwindow, PreWindow* preWin); ~GeometryViewProvider(); void updateGeoActors(); void updateGraphOption(); void updateDiaplayStates(Geometry::GeometrySet* s, bool visibility); QMultiHash<Geometry::GeometrySet*, int> getGeoSelectItems(); public slots: void showGeoSet(Geometry::GeometrySet* set, bool render = true); void showDatum(Geometry::GeometryDatum* datm); void removeActors(Geometry::GeometrySet* set); void setGeometryDisplay(bool v, bool c, bool f); void setGeoSelectMode(int); signals: void geoShapeSelected(Geometry::GeometrySet*shape, int index); private slots: //高亮显示函数 void highLightGeometrySet(Geometry::GeometrySet* s, bool on); void highLightGeometryFace(Geometry::GeometrySet* s, int id, bool on);//高亮显示面 void highLightGeometryEdge(Geometry::GeometrySet* s, int id, bool on);//高亮显示边 void highLightGeometryPoint(Geometry::GeometrySet* s, int id, bool on);//高亮显示点 void highLightGeometrySolid(Geometry::GeometrySet* s, int id, bool on); void selectGeometry(bool ctrlpress); void preSelectGeometry(vtkActor* ac, int index); void clearAllHighLight(); private: void init(); private: struct GeoViewObj { QPair<vtkActor*, vtkPolyData*> _faceObj{ nullptr,nullptr }; QPair<vtkActor*, vtkPolyData*> _edgeObj{ nullptr,nullptr }; QPair<vtkActor*, vtkPolyData*> _pointObj{ nullptr,nullptr }; }; PreWindow* _preWindow{}; GUI::MainWindow* _mainWindow{}; Geometry::GeometryData* _geoData{}; GeometryViewData* _viewData{}; QHash<Geometry::GeometrySet*, GeoViewObj> _geoViewHash{}; }; } #endif
// GetAngle.cpp : 实现文件 // #include "stdafx.h" #include "ImageProcessing.h" #include "GetAngle.h" #include "afxdialogex.h" // CGetAngle 对话框 IMPLEMENT_DYNAMIC(CGetAngle, CDialog) CGetAngle::CGetAngle(CWnd* pParent /*=NULL*/) : CDialog(CGetAngle::IDD, pParent) , angle(0) { } CGetAngle::~CGetAngle() { } void CGetAngle::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, angle); DDV_MinMaxInt(pDX, angle, 0, 360); } BEGIN_MESSAGE_MAP(CGetAngle, CDialog) ON_BN_CLICKED(IDOK, &CGetAngle::OnBnClickedOk) END_MESSAGE_MAP() // CGetAngle 消息处理程序 void CGetAngle::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 UpdateData(); CDialog::OnOK(); }
#ifndef CALCULATION_H #define CALCULATION_H #include "ssFrameLib.h" #include <vector> using namespace std; /* * this header file contain the device id and calculate the point coordinate * function. */ const unsigned char RFANS_PRODUCT_MODEL_V6G_X16_0X32 = 0X32; const unsigned char RFANS_PRODUCT_MODEL_V6G_X32_0X33 = 0X33; const unsigned char RFANS_PRODUCT_MODEL_V6_X32_0X40 = 0X40; const unsigned char RFANS_PRODUCT_MODEL_V6_X16A_0X41 = 0X41; const unsigned char RFANS_PRODUCT_MODEL_V6_X16B_0X42 = 0X42; const unsigned char RFANS_PRODUCT_MODEL_V6_X16Even_0X43 = 0X43; const unsigned char RFANS_PRODUCT_MODEL_V6_X16Odd_0X44 = 0X44; const unsigned char RFANS_PRODUCT_MODEL_V6P_X32_0X45 = 0X45; const unsigned char RFANS_PRODUCT_MODEL_V6P_X16A_0X46 = 0X46; const unsigned char RFANS_PRODUCT_MODEL_V6P_X16B_0X47 = 0X47; const unsigned char RFANS_PRODUCT_MODEL_V6P_X16Even_0X48 = 0X48; const unsigned char RFANS_PRODUCT_MODEL_V6P_X16Odd_0X49 = 0X49; const unsigned char RFANS_PRODUCT_MODEL_V6A_X32_0X4A = 0X4A; const unsigned char RFANS_PRODUCT_MODEL_V6A_X16A_0X4B = 0X4B; const unsigned char RFANS_PRODUCT_MODEL_V6A_X16B_0X4C = 0X4C; const unsigned char RFANS_PRODUCT_MODEL_V6A_X16Even_0X4D = 0X4D; const unsigned char RFANS_PRODUCT_MODEL_V6A_X16Odd_0X4E = 0X4E; const unsigned char RFANS_PRODUCT_MODEL_V6A_X16M_0X4F = 0X4F; const unsigned char RFANS_PRODUCT_MODEL_V6B_X32_0X50=0X50 ; const unsigned char RFANS_PRODUCT_MODEL_CFANS_X32_0X80=0X80 ;//???? const unsigned char RFANS_PRODUCT_MODEL_V6A_E1_0X55 = 0X55; const unsigned char RFANS_PRODUCT_MODEL_V6A_E2_0X56 = 0X56; const unsigned char RFANS_PRODUCT_MODEL_V6BC_16G_0X57 = 0X57; const unsigned char RFANS_PRODUCT_MODEL_V6BC_16M_0X58 = 0X58; const unsigned char RFANS_PRODUCT_MODEL_V6C_Z_X32_0X59 = 0X59; const unsigned char RFANS_PRODUCT_MODEL_V6K_32M_0X5A = 0X5A; const unsigned char RFANS_PRODUCT_MODEL_V6K_16M_0X5B = 0X5B; const unsigned char RFANS_PRODUCT_MODEL_V6K_16G_0x5C = 0x5C; const unsigned char CFNAS_32_0x81 = 0x81; const int RFANS_PRODUCT_MODEL_V6_X16A_0X41_LASER_ID[] = { 5, 7, 9, 11, 13, 15, 16, 18, 17, 19, 20, 21, 23, 25, 27, 29 }; const int RFANS_PRODUCT_MODEL_V6_X16A_0X42_LASER_ID[] = { 6,8,10,12,14,16,18,17,19,20,22,21,24,26,28,30 }; const int RFANS_PRODUCT_MODEL_V6_X16A_0X43_LASER_ID[] = { 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 }; const int RFANS_PRODUCT_MODEL_V6_X16A_0X44_LASER_ID[] = { 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30 }; const double HANGLE_V6B_X32_0x40[] = { 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, 6.01, -4.068, 3.377, -6.713, }; const double HANGLE_V6BC_16G_0x57[]={ 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, 6.01, 3.377, }; const double HANGLE_V6BC_16M_0x58[]={ 2.1889,-2.8544,2.1889,-2.8544, 2.1889,-2.8544,2.1889,-2.8544, 2.1889,-2.8544,2.1889,-2.8544, 2.1889,-2.8544,2.1889,-2.8544, }; const double HANGLE_V5_X16[] = { -2.5, 2.5, -2.5, 2.5, -2.5, 2.5, -2.5, 2.5, -2.5, 2.5, -2.5, 2.5, -2.5, 2.5, -2.5, 2.5 }; const double VANGLE_V5_X16[] = { -15.0, -13.0, -11.0, -9.0, -7.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0, 1.0, 3.0, 5.0, 7.0, 9.0, }; const double HANGLE_V6_X32_0x40[] = { 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, 6.35, -3.85, 3.85, -6.35, }; const double HANGLE_V6A_E1_0x55[] = { -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, -4.28, -6.713, }; const double VANGLE_V6_X32_0X40[] = { -20.5, -19.5, -18.5, -17.5, -16.5, -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, }; const double VAngle_V6C_Z_32[32] = { -15.5, -14.5, -13.5, -12.5 - 11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, +0.5, +1.5, +2.5, +3.5, +4.5, +5.5, +6.5, +7.5, +8.5, +9.5, +10.5, +11.5, +12.5, +13.5, +14.5, +15.5 }; const double VAngle_V6B_16M[16] = { -15, -13, -11, -9, -7, -5, -4, -3, -2, -1, 0, 1, 3, 5, 7, 9 }; const double VAngle_V6B_16G[16]={-15,-13,-11,-9,-7,-5,-3,-1,1,3,5,7,9,11,13,15}; const double VANGLE_V6A_X32[] = { -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, }; static double VAngle_16E1[16] = { -19.5, -17.5, -15.5, -13.5, -11.5, -9.5, -7.5, -5.5, -3.5, -1.5, 0.5, 2.5, 4.5, 6.5, 8.5, 10.5 }; static double VAngle_16E2[16] = { -19, -17, -15, -13, -11, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9, 11 }; /*const double HANGLE_V6G_X32_0X33[] = { 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, 5.52, -3.48, 3.48, -5.52, };*/ const double HANGLE_V6G_X32_0X33[] = { 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, 5.21, -3.48, 3.04, -5.62, }; const double VANGLE_V6G_X32_0X33[] = { -25, -22, -19, -16, -13, -11, -9, -7, -5.5, -4.5, -3.5, -2.9, -2.45, -2.1, -1.75, -1.4, -1.05, -0.7, -0.35, 0, 0.35, 0.7, 1.05, 1.4, 2.5, 3.5, 4.5, 6, 8, 10, 12, 15, }; //const double HANGLE_V6K_32M[] = { // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8, // 6.35, -3.7, 3.3, -5.8 //}; //const double VANGLE_V6K_32M[32] = { // -16.9, -15, -13.68, -12, // -10.5, -9.5, -8.5, -7.5, // -6.5, -6, -5.5, -5, // -4.5, -4, -3.5, -3, // -2.5, -2, -1.5, -1, // -0.5, 0, 0.5, 1, // 2, 3, 4, 5, // 6.37, 8, 9.26, 11 //}; //const double HANGLE_V6K_16M[] = { // 1.325, -1.325, 1.325, -1.325, // 1.325, -1.325, 1.325, -1.325, // 1.325, -1.325, 1.325, -1.325, // 1.325, -1.325, 1.325, -1.325 //}; //const double VAngle_V6K_16M[16] = { // -15, -12, -9.5, -7.5, // -6, -5, -4, -3, // -2, -1, 0, 1, // 3, 5, 8, 11 //}; //V6 0x40-0x44 v6A 0x4A-0x4E const double DELTA_T_V6_X32_0x40[] ={ 0, 3.125, 1.5625, 4.6875, 6.25, 9.375, 7.8125, 10.9375, 12.5, 15.625, 14.0625, 17.1875, 18.75, 21.875, 20.3125, 23.4375, 25, 28.125, 26.5625, 29.6875, 31.25, 34.375, 32.8125, 35.9375, 37.5, 40.625, 39.0625, 42.1875, 43.75,46.875, 45.3125, 48.4375, }; //V6G_0x33 V6B/C 0x50 0x5A const double DELTA_T_V6G_V6BC_X32_0x33_0x50[] ={ 0, 6.25, 12.5, 18.75, 1.5625, 7.8125, 14.0625, 20.3125, 3.125, 9.375, 15.625, 21.875, 4.6875, 10.9375, 17.1875, 23.4375, 25, 31.25, 37.5, 43.75, 26.562, 32.812, 39.062, 45.312, 28.125, 34.375, 40.625, 46.875, 29.6875,35.9375, 42.1875, 48.4375, }; //V6A-16M, V6A-16E1 0x4F 0x55 0x56 const double DELTA_T_V6A_X16M_0X4F_0x55_0x56[] ={ 0, 3.125, 6.25, 9.375, 12.5, 15.625, 18.75, 21.875, 25, 28.125, 31.25, 34.375, 37.5, 40.625, 43.75, 46.875, }; //V6B/C-16G, V6B/C-16M,0x57,0x58 const double DELTA_T_V6BC_16GM_0x57_0x58[] ={ 0, 12.5, 3.125, 15.625, 6.25, 18.75, 9.375, 21.875, 25, 37.5, 28.125,40.625, 31.25, 43.75, 34.375,46.875 }; //CFans const double DELTA_T_CFANS_0x80[] = { 4.6875, 10.9375, 17.1875,23.4375, 3.125, 9.375, 15.625, 21.875, 1.5625, 7.8125, 14.0625,20.3125, 0, 6.25, 12.5, 18.75, 29.6875, 35.9375, 42.1875, 48.4375, 28.125, 34.375, 40.625, 46.875, 26.5625, 32.8125, 39.0625, 45.3125, 25, 31.25, 37.5, 43.75 }; //V6K-16G const double DELTA_T_RFANS_V6K_16G_0x5C[]={ 0, 13.32, 3.33,16.65, 6.66, 19.98, 9.99, 23.31, 26.64, 39.96, 29.97, 43.29, 33.3, 46.62, 36.63, 49.95 }; // V6K-32M const double HANGLE_V6K_32M_0X5A[32]={ 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7, 3.7, -6.35, 6.35, -3.7 }; const double VANGLE_V6K_32M_0x5A[32]={ -16.9, -15, -13.68, -12, -10.5, -9.5, -8.5, -7.5, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 2, 3, 4, 5, 6.37, 8, 9.26, 11 }; const double DELTA_T_V6K_32M_0x5A[32]={ 0, 6.25, 12.5, 18.75, 1.5625, 7.8125, 14.0625,20.3125, 3.125, 9.375, 15.625, 21.875, 4.6875, 10.9375, 17.1875, 23.4375, 25, 31.25, 37.5, 43.75, 26.5625, 32.8125, 39.0625, 45.3125, 28.125, 34.375, 40.625, 46.875, 29.6875, 35.9375, 42.1875, 48.4375 }; //V6K-16M const double HANGLE_V6K_16M_0x5B[] = { 1.325, -1.325, 1.325, -1.325, 1.325, -1.325, 1.325, -1.325, 1.325, -1.325, 1.325, -1.325, 1.325, -1.325, 1.325, -1.325 }; const double VANGLE_V6K_16M_0x5B[]={ -12, -15, -7.5, -9.5, -5, -6,-3, -4, -1, -2,1, 0, 5, 3,11, 8 }; const double DELTA_T_V6K_16M_0x5B[]={ 13.32,0,16.65,3.33, 19.98,6.66,23.31,9.99, 39.96,26.64,43.29,29.97, 46.62,33.3,49.95,36.63 }; extern float m_anglePara[30]; extern double m_mirrorVector[4][3]; extern double m_lidarAngle[2][32]; extern std::vector<float> s_reviseangles; extern float cfans_lidarAngle[2][8]; extern float mirrorVector[4][3]; extern float m_anglePara_32[30]; extern std::vector<float> s_reviseangles_32; int calcXyz(unsigned char flag,float &mtRange, float &mtAngle, RFANS_XYZ_S &outXyz); int calcCFansCoor(float range ,float angle ,int index,int laserID, RFANS_XYZ_S &outXyz); int calcCFansXYZ_32(float range, float angle,int index, int laserID, RFANS_XYZ_S &outXyz); int initCFansPara(std::string reviseAngle); int initCFans_32(std::string revisePara); class Calculation{ public: explicit Calculation(); ~Calculation(); private: }; #endif // CALCULATION_H
/* * UDPConnection.hpp * * Created on: 13 Jun 2018 * Author: Thomas Maters * Email : thomasmaters@hotmail.com (TG.Maters@student.han.nl) */ #ifndef SRC_UDPCONNECTION_HPP_ #define SRC_UDPCONNECTION_HPP_ #include "../../Messages/SensorMessage.hpp" #include "../ConnectionInterface.hpp" #include <boost/asio/io_service.hpp> #include <boost/asio/ip/udp.hpp> #define UDP_BUFFER_SIZE 4096 using boost::asio::ip::udp; namespace Communication::UDP { /** * Class handles communicating over UDP. */ class UDPServerClient : public ConnectionInterface { public: UDPServerClient(boost::asio::io_service& io_service, const std::string& host, const std::string& remote_port, const std::string& local_port); /** * Sends a message. * @param message To send. * @param response_size Size of bytes to read into response. * @param has_response_head_and_body Read in 2 parts. */ void sendRequest(const SensorMessage& message, std::size_t response_size, bool has_response_head_and_body = false); /** * Sends a message. * @param message To send. * @param delimiter Read till delimeter found. * @param has_response_head_and_body Read in 2 parts. */ void sendRequest(const SensorMessage& message, char delimiter, bool has_response_head_and_body = false); /** * Sends a message from a string. * @param message To send. * @param response_size Size of bytes to read. */ void sendRequest(std::string message, std::size_t response_size); virtual ~UDPServerClient(); private: /** * Connect to outgoing ip. * @return True if connected. */ bool connectOutgoingSocket(); /** * Sends a message. * @param buffer * @param response_size * @param has_response_head_and_body */ void sendMessage(const boost::asio::mutable_buffer& buffer, std::size_t response_size, bool has_response_head_and_body); /** * Handler when ready to read response. * @param response_size * @param has_response_head_and_body * @param error * @param bytes_transferred */ void getResponse(std::size_t response_size, bool has_response_head_and_body, const boost::system::error_code& error, [[maybe_unused]] std::size_t bytes_transferred); /** * Handler when response has been read. * @param has_response_head_and_body * @param error * @param bytes_transferred */ void gotResponse(bool has_response_head_and_body, const boost::system::error_code& error, std::size_t bytes_transferred); /** * Starts listening on port. */ void startReceive(); /** * Received a message on a port. * @param error * @param bytes_transferred */ void handleReceive(const boost::system::error_code& error, std::size_t bytes_transferred); /** * Handle when response has been send on a message. * @param error * @param bytes_transferred */ void handleSend([[maybe_unused]] const boost::system::error_code& error, std::size_t bytes_transferred); std::array<uint8_t, UDP_BUFFER_SIZE> data_; std::string host_; std::string remote_port_; std::string local_port_; boost::asio::io_service& io_service_; boost::asio::ip::udp::endpoint local_endpoint_; boost::asio::ip::udp::endpoint remote_endpoint_; boost::asio::ip::udp::socket socket_outgoing_; boost::asio::ip::udp::socket socket_incomming_; }; } #endif /* SRC_UDPCONNECTION_HPP_ */
#include <stdio.h> long long next_val(long long prev_val) { long long div = 4294967296; return (prev_val * 214013 + 2531011) % div; } int l2i(long long prev_val) { return (int)(prev_val % 10000 + 1); } int main() { int c; scanf("%d",&c); while(c--) { int k,n; int f = 0; int r = 0; long long f_value = 1983; long long r_value = 1983; int sum = 1984; int count = 0; scanf("%d %d",&k,&n); while(1) { if(sum == k) { count+=1; sum -= l2i(f_value); r+=1; f+=1; f_value = next_val(f_value); r_value = next_val(r_value); sum += l2i(r_value); if(r == n) { if(sum == k) count+=1; break; } } else if(sum < k) { r+=1; r_value = next_val(r_value); sum += l2i(r_value); if(r == n) { if(sum == k) count+=1; break; } } else { f+=1; sum -= l2i(f_value); f_value = next_val(f_value); } } printf("%d\n",count); } }
#pragma once template <class T> class LLQueue { private: struct Node { T data; Node *next; Node(const T &data) : data(data), next(nullptr) {} }; Node *Front; Node *Rear; int count; public: LLQueue(); LLQueue(const LLQueue<T> &); ~LLQueue(); const LLQueue<T> &operator=(const LLQueue<T> &); //Capacity int size(); bool empty(); //Modifiers T front(); void enqueue(const T &); bool dequeue(); };
// -*- C++ -*- #include "ImageAnalyzer.hh" #include <fstream> #include <iostream> #include <opencv2/dnn.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> namespace { const std::string& class_name("ImageAnalyzer"); } //______________________________________________________________________________ ImageAnalyzer::ImageAnalyzer( const cv::String& network, const cv::String& caffe, const cv::String& mean, const cv::String& label, const cv::String& input ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); cv::dnn::initModule(); m_network = cv::dnn::readNetFromCaffe(network, caffe); m_image_original = cv::imread(input); m_image_mean = cv::imread(mean); m_label = ReadLabel(label); m_is_ready = ( CheckFile( m_network, network ) && CheckFile( m_image_original, input ) && CheckFile( m_image_mean, mean ) && CheckFile( m_label, label ) ); return; } //______________________________________________________________________________ ImageAnalyzer::~ImageAnalyzer( void ) { } //______________________________________________________________________________ template <typename T> bool ImageAnalyzer::CheckFile( T object, const cv::String& name ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); if( object.empty() ) std::cerr << "#E " << func_name << " no such file : " << name << std::endl; return !object.empty(); } //______________________________________________________________________________ bool ImageAnalyzer::Process( void ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); if( !m_is_ready ) return false; Resize( cv::Size(140, 140) ); SubtractMeanImage(); cv::dnn::Blob inputBlob = cv::dnn::Blob::fromImages(m_image_subtracted); m_network.setBlob(".data", inputBlob); //set the network input m_network.forward(); //compute output cv::dnn::Blob prob = m_network.getBlob("prob"); //gather output of "prob" layer double classProb; int classId = GetBestClass(prob, &classProb);//find the best class std::cout << "Best class: #" << classId << " '" << m_label.at(classId) << "'" << std::endl; std::cout << "Probability: " << classProb * 100 << "%" << std::endl; return true; } //______________________________________________________________________________ bool ImageAnalyzer::Resize( cv::Size s ) { cv::resize( m_image_original, m_image_original, s ); return true; } //______________________________________________________________________________ bool ImageAnalyzer::SubtractMeanImage( void ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); cv::Mat image_CV_16S; m_image_original.convertTo(image_CV_16S, CV_16S); cv::Mat mean_CV_16S; m_image_mean.convertTo(mean_CV_16S, CV_16S); cv::subtract(image_CV_16S, mean_CV_16S, m_image_subtracted); return true; } //______________________________________________________________________________ int ImageAnalyzer::GetBestClass( cv::dnn::Blob &probBlob, double *classProb ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); cv::Mat probMat = probBlob.matRefConst().reshape(1, 1); //reshape the blob to 1x1000 matrix cv::Point classNumber; cv::minMaxLoc( probMat, NULL, classProb, NULL, &classNumber ); return classNumber.x; } //______________________________________________________________________________ std::vector<cv::String> ImageAnalyzer::ReadLabel( const cv::String& file ) { static const std::string func_name("["+class_name+"::"+__func__+"()]"); std::ifstream ifs( file.c_str() ); std::string line; std::vector<cv::String> labels; while( ifs.good() && std::getline( ifs, line ) ){ if( line.length()>0 ) labels.push_back( line.substr(line.find(' ')+1) ); } return labels; }
// // Created by phith on 25.06.2021. // #ifndef TESTPROJEKT_TEST_H #define TESTPROJEKT_TEST_H class Test { public: char testchar = 'a'; }; #endif //TESTPROJEKT_TEST_H
#ifndef EFECTO_COLISION_I_H #define EFECTO_COLISION_I_H #include "objeto_juego_i.h" #include "espaciable.h" #include "efecto_colision_recogedor_i.h" namespace App_Interfaces { class Efecto_colision_I: public virtual Objeto_juego_I { public: ~Efecto_colision_I(); virtual void efecto_colision(App_Interfaces::Efecto_colision_recogedor_I&)=0; virtual bool es_colision_para(const App_Interfaces::Espaciable&)const=0; }; } #endif
#include <iostream> #include <cassert> #include "AVLTree.h" using namespace std; int main() { int commandCount = 0; std::cin >> commandCount; assert( commandCount >= 0 ); AVLTree<int> tree{}; while (commandCount--){ int command = 0, value = 0; cin >> command >> value; switch(command){ case 1: std::cout << tree.Add(value) << "\n"; break; case 2: //std::cout << tree.Delete(value)->key << "\n"; tree.RemoveByPos(value); break; default: std::cout << "No such command\n"; } } return 0; }
#pragma once #include <Windows.h> #include "logging.h" extern "C" { BOOL WINAPI ctrlHandler(DWORD ctrlType); } namespace RemoteGamepad { class StateManager { public: static StateManager& instance() { static StateManager manager{}; return manager; } void setUp() { if (!SetConsoleCtrlHandler(ctrlHandler, TRUE)) { Logging::StdErr()->error("Control handler was not set. You may not be able to leave the program in a correct way."); } } void setShouldCloseProgram() { m_shouldCloseProgram = true; } bool shouldCloseProgram() const { return m_shouldCloseProgram; } private: bool m_shouldCloseProgram{ false }; }; }
// // Created by vybirto1 on 15.3.18. // #ifndef ROGUE_CSDLCOLOR_H #define ROGUE_CSDLCOLOR_H #include <cstdint> class CSDLColor { public: static CSDLColor BLACK; static CSDLColor WHITE; CSDLColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a); CSDLColor(const CSDLColor &a); uint8_t getR() const; uint8_t getG() const; uint8_t getB() const; uint8_t getA() const; private: uint8_t r, g, b, a; }; #endif //ROGUE_CSDLCOLOR_H
#include "Printer.h" Printer::Printer(const char* text, size_t n, const char* pat, size_t m): text(text), n(n), pat(pat), m(m) {} /* * Acrescenta a ocorrência que se inicia em 'matchingStart' na linha correspondente */ void Printer::addMatching(int matchingStart) { int lineSt = matchingStart, lineEnd = matchingStart; while(lineSt > 0 && text[lineSt] != '\n') --lineSt; if(text[lineSt] == '\n') ++lineSt; while(lineEnd < n-1 && text[lineEnd] != '\n') ++lineEnd; if(text[lineEnd] == '\n') --lineEnd; linesOccs[make_pair(lineSt, lineEnd)].insert(matchingStart); } /* * Imprime todas as ocorrencias registradas do padrão 'pat' no texto 'text' */ void Printer::print() { for(map<pair<int,int>, set<int> >::iterator it = linesOccs.begin(); it != linesOccs.end(); ++it) {//Para toda linha int pos = (it->first).first, lastPos = (it->first).second; //os limites da linha atual for(set<int>::iterator occ = (it->second).begin(); occ != (it->second).end(); ++occ) {//Para toda ocorrencia na linha if(pos < *occ) { printf("%.*s", *occ - pos, text + pos); printf("\033[31m"); printf("%s", pat); printf("\033[0m"); pos = *occ + m; } else if(*occ + m > pos){ printf("\033[31m"); printf("%.*s", int(*occ + m - pos), pat + (pos-*occ)); printf("\033[0m"); pos = *occ + m; } } if(pos <= lastPos) printf("%.*s", lastPos - pos + 1, text + pos); printf("\n"); } }
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "SACPP/Public/CPP_SceneCapture.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeCPP_SceneCapture() {} // Cross Module References SACPP_API UClass* Z_Construct_UClass_ACPP_SceneCapture_NoRegister(); SACPP_API UClass* Z_Construct_UClass_ACPP_SceneCapture(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_SACPP(); ENGINE_API UClass* Z_Construct_UClass_USceneCaptureComponent2D_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_USceneComponent_NoRegister(); // End Cross Module References void ACPP_SceneCapture::StaticRegisterNativesACPP_SceneCapture() { } UClass* Z_Construct_UClass_ACPP_SceneCapture_NoRegister() { return ACPP_SceneCapture::StaticClass(); } struct Z_Construct_UClass_ACPP_SceneCapture_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SceneCapture_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_SceneCapture; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Root_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Root; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_ACPP_SceneCapture_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_SACPP, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ACPP_SceneCapture_Statics::Class_MetaDataParams[] = { { "IncludePath", "CPP_SceneCapture.h" }, { "ModuleRelativePath", "Public/CPP_SceneCapture.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_SceneCapture_MetaData[] = { { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPP_SceneCapture.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_SceneCapture = { "SceneCapture", nullptr, (EPropertyFlags)0x00100000000b0009, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ACPP_SceneCapture, SceneCapture), Z_Construct_UClass_USceneCaptureComponent2D_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_SceneCapture_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_SceneCapture_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_Root_MetaData[] = { { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPP_SceneCapture.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_Root = { "Root", nullptr, (EPropertyFlags)0x00100000000b0009, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ACPP_SceneCapture, Root), Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_Root_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_Root_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ACPP_SceneCapture_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_SceneCapture, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ACPP_SceneCapture_Statics::NewProp_Root, }; const FCppClassTypeInfoStatic Z_Construct_UClass_ACPP_SceneCapture_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<ACPP_SceneCapture>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ACPP_SceneCapture_Statics::ClassParams = { &ACPP_SceneCapture::StaticClass, "Engine", &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_ACPP_SceneCapture_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_ACPP_SceneCapture_Statics::PropPointers), 0, 0x009000A4u, METADATA_PARAMS(Z_Construct_UClass_ACPP_SceneCapture_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_ACPP_SceneCapture_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_ACPP_SceneCapture() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ACPP_SceneCapture_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(ACPP_SceneCapture, 3762483156); template<> SACPP_API UClass* StaticClass<ACPP_SceneCapture>() { return ACPP_SceneCapture::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_ACPP_SceneCapture(Z_Construct_UClass_ACPP_SceneCapture, &ACPP_SceneCapture::StaticClass, TEXT("/Script/SACPP"), TEXT("ACPP_SceneCapture"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(ACPP_SceneCapture); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
#include "Global.h" #define MAX_LINE_SIZE 5000 int main(int argc, char*argv[]) { int S = atoi(argv[1]); int N,K; cin >> N >> K ; cerr << N << " " << K <<endl; string line; getline(cin, line); // clears the endl at the first line string *LinesSampled = new string [S]; srand48(1973); for (int i = 0; i < N; i ++){ getline(cin, line); if (i < S){ LinesSampled[i] = line; //cout << "line "<<i<<": "<<LinesSampled[i]<<endl; }else{ int r = (int) floor(drand48() * (i+1)); if (r < S){ LinesSampled[r] = line; //cout << line<<endl; //cout << "line "<<r<<": "<<LinesSampled[r]<<endl; } } } //cout << "\nsample!\n"<<endl; cout << S << " " << K <<endl; for (int i = 0; i < S; i ++){ cout << LinesSampled[i]<<endl; } }
/** * @file UsbTypes.h * @author Lukas Schuller * @date Tue Nov 5 21:40:55 2013 * * @brief * */ #ifndef USBTYPES_H #define USBTYPES_H #include <libusb.h> #include <system_error> #include <memory> namespace Usb { // typedef std::shared_ptr<libusb_transfer> TransferPtr; typedef libusb_transfer * Transfer; typedef libusb_device_handle * DeviceHandle; // custom error conditions enum type: enum class UsbErrc { success=0, libError, logicError}; } namespace std { template<> struct is_error_condition_enum<Usb::UsbErrc> : public true_type {}; } namespace Usb { // custom category: class UsbErrorCategory : public std::error_category { public: virtual const char* name() const noexcept { return "usb"; } virtual std::error_condition default_error_condition (int ev) const noexcept { if(ev == 0) return std::error_condition(UsbErrc::success); if(ev == -1) return std::error_condition(UsbErrc::logicError); else return std::error_condition(UsbErrc::libError); } virtual bool equivalent (const std::error_code& code, int condition) const noexcept { return *this==code.category() && static_cast<int>(default_error_condition(code.value()).value())==condition; } virtual std::string message(int ev) const noexcept { return std::string(libusb_error_name(ev)); } }; extern UsbErrorCategory errorCategory; // make_error_code overload to generate custom conditions: std::error_condition make_error_condition (UsbErrc e); class Error : public std::system_error { public: Error(int usbErrno, std::string const & msg = "") : std::system_error(std::error_code(usbErrno, errorCategory), msg) { } Error(std::string const & msg = "") : std::system_error(std::error_code(-1, errorCategory), msg) { } }; } #endif /* USBERROR_H */
#pragma once #include "Command.h" class PlayerInfoCommand : public Command { public: PlayerInfoCommand(); ~PlayerInfoCommand(); void Run(list<string>* parameters, Game * game); };
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "Interfaces/PlayerPawnState.h" #include "Pawns/PlayerPawn.h" #include "TimerManager.h" #include "PPState_ROLL.generated.h" /** * */ UCLASS() class RPG_API UPPState_ROLL : public UObject, public IPlayerPawnState { GENERATED_BODY() public: /* Begin IPlayerPawnState */ virtual void Init(UPlayerFSMComponent* InPlayerFSMComponent) override; virtual void Enter() override; virtual void Execute(float DeltaSeconds) override; virtual void Exit() override; virtual EPlayerPawnState GetStateEnum() { return EPlayerPawnState::ROLL; } virtual const FString GetStateString() { return "ROLL"; } /* End IPlayerPawnState */ protected: UPROPERTY() UPlayerFSMComponent* PlayerFSMComponent = nullptr; UPROPERTY() APlayerPawn* PlayerPawn = nullptr; UPROPERTY() UPlayerPawnMovementComponent* MovementComponent = nullptr; UPROPERTY() UPlayerAnimInstance* AnimInstance = nullptr; UPROPERTY() FTimerHandle RollTimerHandle; UPROPERTY() float Direction = 1.F; UPROPERTY() float RollAlpha = 0.F; protected: void StartRollTimer(); UFUNCTION() void UpdateRollTimer(FVector InStartVector, FVector InTargetVector); void StopRollTimer(); void CheckGround(); };
#include <iostream> #include <PCANBasic.h> #include <ros/ros.h> //Vehicle Information Msg #include "vehicle_msgs/abs.h" #include "vehicle_msgs/esc.h" //ioniq chassis const std::string topic_abs= "abs"; const std::string topic_esc = "esc"; #define Can PCAN_USBBUS2 const double scale_factor = 0.03125; int main(int argc, char* argv[]){ ros::init(argc, argv, "chassi_receiver"); ros::NodeHandle nh("~"); //if you wirte this character "~" the the node name will be can_re~ TPCANMsg msg; TPCANStatus stat; ros::Publisher abs_pub = nh.advertise<vehicle_msgs::abs>(topic_abs,1); ros::Publisher esc_pub = nh.advertise<vehicle_msgs::esc>(topic_esc,1); stat = CAN_Initialize(Can, PCAN_BAUD_500K); if(stat != PCAN_ERROR_OK){ char error_message[50]; CAN_GetErrorText(stat, 0x09, error_message); printf("%s\n",error_message); ROS_INFO("%s\n",error_message); } vehicle_msgs::abs abs_msg; vehicle_msgs::esc esc_msg; while(ros::ok()){ ros::spinOnce(); stat = CAN_Read(Can, &msg, NULL); if(stat !=PCAN_ERROR_OK){ continue; } if(msg.ID == 0x386){ abs_msg.whl_spd_fl = (double)((uint16_t)(msg.DATA[0]) + ((uint16_t)(msg.DATA[1]&0x3f)<<8))*scale_factor; abs_msg.whl_spd_fr = (double)((uint16_t)(msg.DATA[2]) + ((uint16_t)(msg.DATA[3]&0x3f)<<8))*scale_factor; abs_msg.whl_spd_rl = (double)((uint16_t)(msg.DATA[4]) + ((uint16_t)(msg.DATA[5]&0x3f)<<8))*scale_factor; abs_msg.whl_spd_rr = (double)((uint16_t)(msg.DATA[6]) + ((uint16_t)(msg.DATA[7]&0x3f)<<8))*scale_factor; abs_pub.publish(abs_msg); } else if(msg.ID == 544){ esc_msg.lat_accel = (double)((uint16_t)(msg.DATA[0]) + ((uint16_t)(msg.DATA[1]&0b111)<<8))*0.01 - 10.23; esc_msg.long_accel = (double)((uint16_t)((msg.DATA[1]&0xe0)>>5) + ((uint16_t)(msg.DATA[2])<<3))*0.01 - 10.23; esc_msg.yaw_rate = (double)((uint16_t)(msg.DATA[5]) + ((uint16_t)(msg.DATA[6]&0x1f)<<8))*0.01 - 40.95; esc_pub.publish(esc_msg); } continue; } return 0; }
#pragma once #include <core/document/DocumentModel.hpp> #include <Scenario/Document/Constraint/Slot.hpp> #include <Scenario/Document/TimeNode/Trigger/TriggerModel.hpp> #include <Scenario/Document/ScenarioDocument/ScenarioDocumentModel.hpp> #include <Scenario/Document/State/ItemModel/MessageItemModel.hpp> #include <Scenario/Document/BaseScenario/BaseScenario.hpp> #include <Scenario/Process/ScenarioModel.hpp> #include <Loop/LoopProcessModel.hpp> #include <ImageProcess/ImageModel.hpp> #include <Scenario/Process/Algorithms/Accessors.hpp> #include <Scenario/Process/Algorithms/ContainersAccessors.hpp> #include <iscore/tools/SubtypeVariant.hpp> // Note : the audio plug-in is put in #ifdefs because // it requires Faust for now which can be a pain to compile. // Normal code shouldn't be that ugly :) #if defined(ISCORE_PLUGIN_AUDIO) #include <Audio/SoundProcess/SoundProcessModel.hpp> #endif namespace Segments { /** For the sake of convenience * we define here a type that allows to eaisly visit * the processes that we are interested in. * * There can be a lot of processes since they can be * implemented via plug-ins but most won't be useful * for segments (midi notes, automations, etc...) */ using SegmentsProcess = iscore::SubtypeVariant< const Process::ProcessModel, const Scenario::ProcessModel, const Loop::ProcessModel, const Image::ProcessModel #if defined(ISCORE_PLUGIN_AUDIO) , const Audio::Sound::ProcessModel #endif >; struct DepthVisitor { QDebug stream; int hierarchy_depth = 0; auto& print() { return stream << QString(hierarchy_depth, ' '); } void operator()(const Scenario::ConstraintModel& constraint) { print() << "Constraint: \n"; // First print the user metadata : name, label, etc. (*this)(constraint.metadata()); // Then the durations : print() << constraint.duration.defaultDuration() << " "; print() << constraint.duration.minDuration() << " "; print() << constraint.duration.maxDuration() << " \n"; // A constraint has : // Temporal processes (ie what happens at execution). // For instance : automation, etc... print() << "Processes: \n"; auto& processes = constraint.processes; hierarchy_depth++; for(SegmentsProcess process : processes) { process.apply(*this); print() << "\n"; } hierarchy_depth--; // Finally, a constraint is between two states : constraint.startState(); constraint.endState(); } void operator()(const Scenario::EventModel& event) { print() << "Event: \n"; (*this)(event.metadata()); // Events carry a condition print() << "Condition:" << event.condition().toString() << "\n"; // And ids of states // (they will be visited in operator()({Scenario,Loop}::ProcessModel)) for(auto& state_id : event.states()) { (void) state_id; // ... } } void operator()(const Scenario::StateModel& state) { print() << "State: \n"; (*this)(state.metadata()); // States carry messages print() << "Messages: " << Process::flatten(state.messages().rootNode()) << "\n"; // And instantaneous processes. // The only process currently is a javascript code one, it's not very useful for // Segments I guess. hierarchy_depth++; for(auto& state_process : state.stateProcesses) { print() << "State process: " << state_process.prettyName() << "\n"; print() << "\n"; } hierarchy_depth--; } void operator()(const Scenario::TimeNodeModel& timenode) { print() << "TimeNode: \n"; (*this)(timenode.metadata()); // Time nodes are used for synchronization and also carry a condition print() << "Condition:" << timenode.trigger()->expression().toString(); // And have ids of events for(auto& event_id : timenode.events()) { (void) event_id; // ... } } void operator()(const Scenario::BaseScenario& base) { // The top-level scenario print() << "Base Scenario: \n"; hierarchy_depth++; (*this)(base.startTimeNode()); (*this)(base.startEvent()); (*this)(base.startState()); (*this)(base.constraint()); (*this)(base.endState()); (*this)(base.endEvent()); (*this)(base.endTimeNode()); hierarchy_depth--; } // Here we list some of the processes that can be useful for Segments void operator()(const Scenario::ProcessModel& scenario) { print() << "Scenario: \n"; (*this)(scenario.metadata()); // Scenario is the "main" process in i-score. // Here we explore it "depth-first" : we check all of its elements. print() << "Constraints: \n"; hierarchy_depth++; for(auto& e : scenario.getConstraints()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "TimeNodes: \n"; hierarchy_depth++; for(auto& e : scenario.getTimeNodes()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "Events: \n"; hierarchy_depth++; for(auto& e : scenario.getEvents()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "States: \n"; hierarchy_depth++; for(auto& e : scenario.getStates()) { (*this)(e); print() << "\n"; } hierarchy_depth--; } void operator()(const Loop::ProcessModel& loop) { // Very similar to a scenario but has only one constraint // and two time nodes, two events, two states print() << "Loop: \n"; (*this)(loop.metadata()); print() << "Constraints: \n"; hierarchy_depth++; for(auto& e : loop.getConstraints()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "TimeNodes: \n"; hierarchy_depth++; for(auto& e : loop.getTimeNodes()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "Events: \n"; hierarchy_depth++; for(auto& e : loop.getEvents()) { (*this)(e); print() << "\n"; } hierarchy_depth--; print() << "States: \n"; hierarchy_depth++; for(auto& e : loop.getStates()) { (*this)(e); print() << "\n"; } hierarchy_depth--; } void operator()(const iscore::ModelMetadata& metadata) { print() << "Metadata: " << metadata.getName() << ", " << metadata.getLabel() << ", " << metadata.getComment() << ", " << metadata.getColor().getColor() << ", " << metadata.getExtendedMetadata() << "\n"; } void operator()(const Image::ProcessModel& image) { print() << "Image: " << image.imagePath() << "\n"; } #if defined(ISCORE_PLUGIN_AUDIO) void operator()(const Audio::Sound::ProcessModel& sound) { print() << "Sound: " << sound.file().name() << "\n"; } #endif void operator()() { } }; struct BreadthVisitor { QDebug stream; int hierarchy_depth = 0; auto& print() { return stream << QString(hierarchy_depth, ' '); } void operator()(const Scenario::ConstraintModel& constraint) { print() << "Constraint: \n"; // First print the user metadata : name, label, etc. (*this)(constraint.metadata()); print() << "Processes: \n"; auto& processes = constraint.processes; hierarchy_depth++; for(SegmentsProcess process : processes) { process.apply(*this); print() << "\n"; } hierarchy_depth--; // Visit the next time node : auto& scenar = Scenario::parentScenario(constraint); (*this)(Scenario::parentTimeNode( scenar.state(constraint.endState()), scenar)); // <!> <!> <!> // if two constraints end up rejoining themselves, // what's after them *WILL* be visited twice. // To prevent this it is necessary to add some kind of // marking or list of already-visited timenodes. // for instance std::unordered_set<Id<TimeNodeModel>> and check // for existance before visiting. // Since there are no cycles there cannot // be infinite loops however. } void operator()(const Scenario::EventModel& event) { print() << "Event: \n"; (*this)(event.metadata()); // Visit the states auto& scenar = Scenario::parentScenario(event); for(auto& state_id : event.states()) { (*this)(scenar.state(state_id)); } } void operator()(const Scenario::StateModel& state) { print() << "State: \n"; (*this)(state.metadata()); // Visit the next constraint if(state.nextConstraint()) { auto& scenar = Scenario::parentScenario(state); (*this)(scenar.constraint(*state.nextConstraint())); } } void operator()(const Scenario::TimeNodeModel& timenode) { print() << "TimeNode: \n"; (*this)(timenode.metadata()); // Visit all the events auto& scenar = Scenario::parentScenario(timenode); for(auto& event_id : timenode.events()) { (*this)(scenar.event(event_id)); } } void operator()(const Scenario::BaseScenario& base) { // The top-level scenario print() << "Base Scenario: \n"; hierarchy_depth++; (*this)(base.startTimeNode()); hierarchy_depth--; } // Processes void operator()(const Scenario::ProcessModel& scenario) { print() << "Scenario: \n"; (*this)(scenario.metadata()); // Scenario is the "main" process in i-score. // Here we explore it "breadth-first" : we start from // the first time node and go through all the elements in the "temporal order". hierarchy_depth++; (*this)(scenario.startTimeNode()); hierarchy_depth--; } void operator()(const Loop::ProcessModel& loop) { print() << "Loop: \n"; (*this)(loop.metadata()); hierarchy_depth++; (*this)(loop.startTimeNode()); hierarchy_depth--; } void operator()(const iscore::ModelMetadata& metadata) { print() << "Metadata: " << metadata.getName() << ", " << metadata.getLabel() << ", " << metadata.getComment() << ", " << metadata.getColor().getColor() << ", " << metadata.getExtendedMetadata() << "\n"; } void operator()(const Image::ProcessModel& image) { print() << "Image: " << image.imagePath() << "\n"; } #if defined(ISCORE_PLUGIN_AUDIO) void operator()(const Audio::Sound::ProcessModel& sound) { print() << "Sound: " << sound.file().name() << "\n"; } #endif void operator()() { } }; inline QString PrintScenario(const iscore::DocumentContext& doc) { // First get the "root" of an i-score score. // A BaseScenario is the topmost hierarchy level. Scenario::BaseScenario& base = iscore::IDocument::get<Scenario::ScenarioDocumentModel>(doc.document).baseScenario(); QString s; s.reserve(1024 * 8); QDebug dbg(&s); DepthVisitor vis{dbg.noquote().nospace()}; vis(base); dbg << "\n\n\n============================\n\n\n"; BreadthVisitor{dbg.noquote().nospace()}; vis(base); return s; } }
#include<iostream> #include<vector> #include<chrono> using namespace std; int64_t simpleSolver(int64_t N, int64_t e1, int64_t e2){ int64_t sum = 0; int64_t e3 = e1 * e2; for (int64_t e = e1; e < N; e += e1) sum += e; for (int64_t e = e2; e < N; e += e2) sum += e; for (int64_t e = e3; e < N; e += e3) sum -= e; return sum; } int64_t fasterSolver(int64_t N, int64_t e1, int64_t e2){ vector<int64_t> input{e1, e2, e1*e2}; vector<int64_t> output; for (auto e: input){ int64_t n = (N - 1) / e; output.push_back(e * ((1 + n) * n) / 2); } return output[0] + output[1] - output[2]; } void speedChecker(function<int64_t(int64_t, int64_t, int64_t)> f, int64_t n, int64_t e1, int64_t e2){ const auto startTime = chrono::system_clock::now(); cout << f(n, e1, e2) << endl; const auto endTime = chrono::system_clock::now(); const auto timeSpan = endTime - startTime; cout << "ProcessingTime: " << chrono::duration_cast<chrono::milliseconds>(timeSpan).count() << endl; } int main(void){ /* ProcessingTime: 1280 ProcessingTime: 0 */ speedChecker(simpleSolver, 1000000000, 3, 5); speedChecker(fasterSolver, 1000000000, 3, 5); }
/*********************************************************************** * created: 11/6/2011 * author: Martin Preisler *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/Base.h" #ifdef CEGUI_HAS_PCRE_REGEX #include "CEGUI/widgets/Spinner.h" #include "CEGUI/WindowManager.h" #include <boost/test/unit_test.hpp> #include <boost/timer.hpp> namespace std { ostream& operator<< (ostream& os, const CEGUI::Spinner::TextInputMode& value) { return os << static_cast<int>(value); } } /* * Used to bring some Spinners up for testing * * This is for exception safety, no matter what happens in the tests, * its destructor will be called */ struct SpinnerFixture { SpinnerFixture() { d_spinner = static_cast<CEGUI::Spinner*>(CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/Spinner")); d_defaultSpinner = static_cast<CEGUI::Spinner*>(CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/Spinner")); } ~SpinnerFixture() { CEGUI::WindowManager::getSingleton().destroyWindow(d_defaultSpinner); CEGUI::WindowManager::getSingleton().destroyWindow(d_spinner); } CEGUI::Spinner* d_spinner; CEGUI::Spinner* d_defaultSpinner; }; BOOST_FIXTURE_TEST_SUITE(Spinner, SpinnerFixture) BOOST_AUTO_TEST_CASE(Defaults) { // we can't use d_spinner because we have no idea what has been done to it BOOST_CHECK_EQUAL(d_defaultSpinner->getCurrentValue(), 0); BOOST_CHECK_EQUAL(d_defaultSpinner->getMinimumValue(), -32768); BOOST_CHECK_EQUAL(d_defaultSpinner->getMaximumValue(), 32767); BOOST_CHECK_EQUAL(d_defaultSpinner->getTextInputMode(), CEGUI::Spinner::TextInputMode::Integer); } BOOST_AUTO_TEST_CASE(MinMax) { d_spinner->setMinimumValue(0.0f); BOOST_CHECK_EQUAL(d_spinner->getMinimumValue(), 0.0f); d_spinner->setMaximumValue(10.0f); BOOST_CHECK_EQUAL(d_spinner->getMaximumValue(), 10.0f); d_spinner->setCurrentValue(10.0f); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 10.0f); d_spinner->setMaximumValue(9.0f); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 9.0f); d_spinner->setCurrentValue(5.0f); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 5.0f); d_spinner->setMinimumValue(6.0f); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 6.0f); } BOOST_AUTO_TEST_CASE(MinMaxStringProperty) { d_spinner->setProperty("MinimumValue", "-123.0"); BOOST_CHECK_EQUAL(d_spinner->getMinimumValue(), -123.0f); BOOST_CHECK_EQUAL(d_spinner->getProperty("MinimumValue"), "-123"); d_spinner->setProperty("MaximumValue", "123.0"); BOOST_CHECK_EQUAL(d_spinner->getMaximumValue(), 123.0f); BOOST_CHECK_EQUAL(d_spinner->getProperty("MaximumValue"), "123"); } BOOST_AUTO_TEST_CASE(CurrentValueStringProperty) { d_spinner->setProperty("CurrentValue", "0"); BOOST_CHECK_EQUAL(d_spinner->getProperty("CurrentValue"), "0"); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 0); d_spinner->setProperty("CurrentValue", "123"); BOOST_CHECK_EQUAL(d_spinner->getProperty("CurrentValue"), "123"); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), 123); d_spinner->setProperty("CurrentValue", "-123"); BOOST_CHECK_EQUAL(d_spinner->getProperty("CurrentValue"), "-123"); BOOST_CHECK_EQUAL(d_spinner->getCurrentValue(), -123); } BOOST_AUTO_TEST_SUITE_END() #endif
// // sceneManager.cpp // led_matrix // // Created by Alex on 17.11.15. // // #include "ofMain.h" #include "scenes.h" #include "sceneManager.h" void sceneManager::setup(){ currentScene = 0; intro.setup(); mirror.setup(); sceneChange = false; scenes.push_back(&intro); scenes.push_back(&mirror); alwaysOn = false; }; void sceneManager::update(){ scenes[currentScene]->update(); } void sceneManager::getSceneBlend(float crossfade, ofColor A[][10], ofColor B[][10]){ for(int i = 0; i < 10; i++){ for(int j=0; j < 10;j++){ if(alwaysOn) { pixelMatrixBlended[i][j] = A[i][j]; } else { pixelMatrixBlended[i][j] = A[i][j].lerp(B[i][j],1 - crossfade); } } } }
/* ASSIGNMENT 4 - COEN 244 Jean-Baptiste WARING 40054925 FAROUQ HAMEDALLAH 40087448 HOSPITAL MANAGEMENT SYSTEM */ #include "./account.h" using namespace std; Account::Account(){ balance = 0; } Account::Account(double t){ balance = t; } void Account::pay_amount(double a){ balance = balance - a; } void Account::get_balance(double &d){ d = balance; } double Account::get_balance(){ return balance; } string Account::get_balance_str(){ ostringstream tempFloatingPrecision; tempFloatingPrecision << fixed; tempFloatingPrecision << setprecision(2); tempFloatingPrecision << balance; return tempFloatingPrecision.str(); } void Account::add_charge(double d){ balance = balance + d; }
#pragma once #include <algorithm> using namespace std; template <typename T> class stack { private: int* array; int capacity; int top; public: stack(int stackcapacity); void push(T item); void pop(); T& Top(); void ChangeSize1D(T*&, const int, const int); bool isEmpty(); }; template <typename T> void stack<T>::ChangeSize1D(T*& a, const int oldSize, const int newSize) { if (newSize < 0) throw "New length must be >= 0"; T* temp = new T[newSize]; // new array int number = min(oldSize, newSize); // number to copy copy(a, a + number, temp); delete[] a; // deallocate old memory a = temp; } template <typename T> stack<T>::stack(int stackcapacity) : capacity(stackcapacity) { if (capacity < 1) cout << "크키가 1이상이어야 함" << endl; else { top = -1; array = new int[capacity]; } } template <typename T> T& stack<T>::Top() { return array[top]; } template <typename T> void stack<T>::push(T item) { if (capacity == top + 1) { ChangeSize1D(array, capacity, capacity * 2); capacity *= 2; } array[++top] = item; } template <typename T> void stack<T>::pop() { if (isEmpty()) cout << "비어있음" << endl; else top--; } template <typename T> bool stack<T>::isEmpty() { return (top == -1); }
#include "../Include/Factory_Line.h" #include "../Include/Botton.h" #include "../Include/Line.h" #include "../Include/PainterForLine.h" #include "../Include/StorerForLine.h" Factory_Line::Factory_Line() { id = 7; } Botton * Factory_Line::generateBotton() { Botton* tmp = new Botton; tmp = new Botton; tmp->setSize(60, 30); tmp->setPos(1170, 600); tmp->loadTexture("Textures/Line.bmp"); tmp->setId(id); tmp->setValue(0, 0); return tmp; } Graph * Factory_Line::generateGraph() { Graph* tmp = new Line; tmp->setId(id); return tmp; } Painter * Factory_Line::generatePainter() { Painter* tmp = new PainterForLine; return tmp; } Storer * Factory_Line::generateStorer() { Storer* tmp = new StorerForLine; return tmp; }
#include <gtest/gtest.h> #include <ostream> #include <istream> #include <sstream> #include <vector> #include <tags/tagmanager.h> #include <tags/tag.h> TEST(tag_test, can_add_elements) { const std::vector<core::UID> element_ids { core::UID::generateRandom(), core::UID::generateRandom(), core::UID::generateRandom(), core::UID::generateRandom() }; const core::UID id = core::UID::generateRandom(); Tag t1(id); for (std::size_t i = 0; i < element_ids.size(); ++i) { EXPECT_FALSE(t1.hasElementID(element_ids[i])) << "for element " << i; t1.addElementID(element_ids[i]); EXPECT_TRUE(t1.hasElementID(element_ids[i])) << "for element " << i; } } TEST(tag_test, can_remove_elements) { const std::vector<core::UID> element_ids { core::UID::generateRandom(), core::UID::generateRandom(), core::UID::generateRandom(), core::UID::generateRandom() }; const core::UID id = core::UID::generateRandom(); Tag t1(id); for (std::size_t i = 0; i < element_ids.size(); ++i) { t1.addElementID(element_ids[i]); } for (std::size_t i = 0; i < element_ids.size(); ++i) { EXPECT_TRUE(t1.hasElementID(element_ids[i])) << "for element " << i; t1.removeElementID(element_ids[i]); EXPECT_FALSE(t1.hasElementID(element_ids[i])) << "for element " << i; } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright (c) 2015 University of Szeged. // Copyright (c) 2015 The Chromium Authors. // All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sprocket/browser/ui/window.h" #include "base/android/jni_string.h" #include "content/public/browser/web_contents.h" #include "jni/SprocketWindow_jni.h" #include "sprocket/android/manager.h" #include "sprocket/browser/ui/authentication_dialog.h" #include "sprocket/browser/ui/javascript_dialog.h" #include "sprocket/browser/web_contents.h" #include <jni.h> using base::android::AttachCurrentThread; using base::android::ConvertUTF8ToJavaString; // static void SprocketWindow::PlatformInitialize() { } // static void SprocketWindow::PlatformExit() { } void SprocketWindow::PlatformCleanUp() { JNIEnv* env = AttachCurrentThread(); if (java_object_.is_null()) return; Java_SprocketWindow_onNativeDestroyed(env, java_object_.obj()); } void SprocketWindow::PlatformCreateWindow(int width, int height) { java_object_.Reset(AttachCurrentThread(), CreateSprocketWindow(this)); } void SprocketWindow::PlatformCloseWindow() { } void SprocketWindow::PlatformAddTab(SprocketWebContents* sprocket_web_contents) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_initFromNativeTabContents( env, java_object_.obj(), sprocket_web_contents->web_contents()->GetJavaWebContents().obj()); } void SprocketWindow::PlatformSelectTabAt(int index) { NOTIMPLEMENTED() << ": " << index; } void SprocketWindow::PlatformEnableUIControl(UIControl control, bool is_enabled) { JNIEnv* env = AttachCurrentThread(); if (java_object_.is_null()) return; Java_SprocketWindow_enableUiControl(env, java_object_.obj(), control, is_enabled); } void SprocketWindow::PlatformSetAddressBarURL(const GURL& url) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_url = ConvertUTF8ToJavaString(env, url.spec()); Java_SprocketWindow_onUpdateUrl(env, java_object_.obj(), j_url.obj()); } void SprocketWindow::PlatformSetIsLoading(bool loading) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_setIsLoading(env, java_object_.obj(), loading); } void SprocketWindow::PlatformSetTitle(const base::string16& title) { NOTIMPLEMENTED() << ": " << title; } bool SprocketWindow::PlatformHandleContextMenu(const content::ContextMenuParams& params) { return false; } void SprocketWindow::PlatformLoadProgressChanged(double progress) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_onLoadProgressChanged(env, java_object_.obj(), progress); } void SprocketWindow::PlatformShowJavaScriptDialog(SprocketJavaScriptDialog* dialog) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_showJavaScriptDialog(env, java_object_.obj(), dialog->GetJavaObject().obj()); } void SprocketWindow::PlatformShowColorChooserDialog(SprocketColorChooser* listener, SkColor initial_color) { // TODO: Implement! } void SprocketWindow::PlatformShowAuthenticationDialog(SprocketAuthenticationDialog* dialog) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_showAuthenticationDialog(env, java_object_.obj(), dialog->GetJavaObject().obj()); } void SprocketWindow::PlatformToggleFullscreenModeForTab(bool enter_fullscreen) { JNIEnv* env = AttachCurrentThread(); Java_SprocketWindow_toggleFullscreenModeForTab( env, java_object_.obj(), enter_fullscreen); } bool SprocketWindow::PlatformIsFullscreenForTabOrPending() const { JNIEnv* env = AttachCurrentThread(); return Java_SprocketWindow_isFullscreenForTabOrPending(env, java_object_.obj()); } void SprocketWindow::PlatformHandleKeyboardEvent(const content::NativeWebKeyboardEvent& event) { } // static bool SprocketWindow::Register(JNIEnv* env) { return RegisterNativesImpl(env); } void CloseSprocketWindow(JNIEnv* env, const JavaParamRef<jclass>& clazz, jlong sprocket_windowPtr) { SprocketWindow* sprocket_window = reinterpret_cast<SprocketWindow*>(sprocket_windowPtr); sprocket_window->Close(); }
#include <iostream> #include <sstream> using namespace std; int main () { string name = "Varun Ramani"; int age = 15; /* If I need to concatnate name and age, this: name + age does not work, since age and name are two different types. I can add together two strings like that, but there is no add method declared for an integer and a string. Therefore, I need to use stringstream. */ stringstream ss; // If I need to add all this stuff together, I can put it into a stream like I do with cout. ss << "My name is " << name << " and I am " << age << " years old."; cout << ss.str() << endl; // This pulls the string out of the stringstream, and allows me to put it to cout. return 0; }
#include "MissionImpossible/ad.hpp" #include "MissionImpossible/derivatives.hpp" #include <gtest/gtest.h> #include <vector> using namespace MissionImpossible; TEST(Nested, Rosenbrock) { AD<AD<double>> x0(3), x1(4), y; y = (1 - x0) * (1 - x0) + 10 * (x1 - x0 * x0) * (x1 - x0 * x0); // remark: y[x0] type is AD<AD<T>> EXPECT_EQ(y, 254); auto y_gradient = Jacobian_row(y); EXPECT_EQ(y_gradient[x0], 604); // remark: y_gradient[x0] type is AD<T> EXPECT_EQ(y_gradient[x1], -100); auto Hessian_x0_row = Jacobian_row(y_gradient[x0]); // remark: Hessian_x0_row[x0] type is T EXPECT_EQ(Hessian_x0_row[x0], 922); EXPECT_EQ(Hessian_x0_row[x1], -120); auto Hessian_x1_row = Jacobian_row(y_gradient[x1]); EXPECT_EQ(Hessian_x1_row[x0], -120); EXPECT_EQ(Hessian_x1_row[x1], 20); // Check tape length // EXPECT_EQ(x0.tape().statement_size(), 3); EXPECT_EQ(x0.value().tape().statement_size(), 39); EXPECT_EQ(x0.tape().memory_size(), 288); EXPECT_EQ(x0.value().tape().memory_size(), 1424); } TEST(Nested, Debug_op_eq_must_not_create_a_new_var_nested) { AD<AD<double>> x0(3); const std::size_t n_1 = x0.tape().statement_size(); const std::size_t nn_1 = x0.value().tape().statement_size(); const bool ok = x0 == 3; // this must not create an instance! NOT OK ASSERT_TRUE(ok); EXPECT_EQ(n_1, x0.tape().statement_size()); EXPECT_EQ(nn_1, x0.value().tape().statement_size()); } TEST(Nested, Debug_op_eq_must_not_create_a_new_var) { AD<double> x0(3); const std::size_t n_1 = x0.tape().statement_size(); const bool ok = x0 == 3; // this must not create an instance! OK ASSERT_TRUE(ok); EXPECT_EQ(n_1, x0.tape().statement_size()); } TEST(Nested, Simple_Polynomial) { AD<AD<double>> x(4), y; const std::size_t n_1 = x.tape().statement_size(); const std::size_t nn_1 = x.value().tape().statement_size(); y = x * x * x; EXPECT_EQ(y, 4 * 4 * 4); auto y_gradient = Jacobian_row(y); EXPECT_EQ(y_gradient[x], 3 * 4 * 4); auto Hessian_x_row = Jacobian_row(y_gradient[x]); EXPECT_EQ(Hessian_x_row[x], 3 * 2 * 4); EXPECT_EQ(1, x.tape().statement_size() - n_1); EXPECT_EQ(17, x.value().tape().statement_size() - nn_1); } // NOTE: when using ASSERT_DOUBLE_EQ instead of EXPECT_EQ, the // overloaded ==(AD,AD) operator is not used anymore and one must // provide a double. This force us to use the ugly syntax // y.value().value().value()... // TEST(Nested, Random_1) { AD<AD<double>> x1(1), x2(2), x3(3), y; y = 2 * x1 + x2 * x3 / (1 + x1 * x2 + x3); ASSERT_DOUBLE_EQ(y.value().value(), 3); auto y_gradient = Jacobian_row(y); ASSERT_DOUBLE_EQ(y_gradient[x1].value(), 5 / 3.); ASSERT_DOUBLE_EQ(y_gradient[x2].value(), 1 / 3.); ASSERT_DOUBLE_EQ(y_gradient[x3].value(), 1 / 6.); auto Hessian_row_x1 = Jacobian_row(y_gradient[x1]); ASSERT_DOUBLE_EQ(Hessian_row_x1[x1], +2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1[x2], -2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1[x3], 0.); auto Hessian_row_x2 = Jacobian_row(y_gradient[x2]); ASSERT_DOUBLE_EQ(Hessian_row_x2[x1], -2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x2[x2], -1 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x2[x3], +1 / 12.); auto Hessian_row_x3 = Jacobian_row(y_gradient[x3]); ASSERT_DOUBLE_EQ(Hessian_row_x3[x1], 0); ASSERT_DOUBLE_EQ(Hessian_row_x3[x2], +1 / 12.); ASSERT_DOUBLE_EQ(Hessian_row_x3[x3], -1 / 18.); } TEST(Nested, test_3_order) { AD<AD<AD<double>>> x1(1), x2(2), x3(3), y; const std::size_t n_1 = x1.tape().statement_size(); const std::size_t nn_1 = x1.value().tape().statement_size(); const std::size_t nnn_1 = x1.value().value().tape().statement_size(); y = 2 * x1 + x2 * x3 / (1 + x1 * x2 + x3); ASSERT_DOUBLE_EQ(y.value().value().value(), 3); auto y_gradient = Jacobian_row(y); ASSERT_DOUBLE_EQ(y_gradient[x1].value().value(), 5 / 3.); ASSERT_DOUBLE_EQ(y_gradient[x2].value().value(), 1 / 3.); ASSERT_DOUBLE_EQ(y_gradient[x3].value().value(), 1 / 6.); auto Hessian_row_x1 = Jacobian_row(y_gradient[x1]); ASSERT_DOUBLE_EQ(Hessian_row_x1[x1].value(), +2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1[x2].value(), -2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1[x3].value(), 0.); auto Hessian_row_x2 = Jacobian_row(y_gradient[x2]); ASSERT_DOUBLE_EQ(Hessian_row_x2[x1].value(), -2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x2[x2].value(), -1 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x2[x3].value(), +1 / 12.); auto Hessian_row_x3 = Jacobian_row(y_gradient[x3]); ASSERT_DOUBLE_EQ(Hessian_row_x3[x1].value(), 0); ASSERT_DOUBLE_EQ(Hessian_row_x3[x2].value(), +1 / 12.); ASSERT_DOUBLE_EQ(Hessian_row_x3[x3].value(), -1 / 18.); ////////////////// auto Hessian_row_x1_x1 = Jacobian_row(Hessian_row_x1[x1]); ASSERT_DOUBLE_EQ(Hessian_row_x1_x1[x1], -2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1_x1[x2], +2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1_x1[x3], -1 / 27.); auto Hessian_row_x1_x2 = Jacobian_row(Hessian_row_x1[x2]); ASSERT_DOUBLE_EQ(Hessian_row_x1_x2[x1], +2 / 9.); ASSERT_DOUBLE_EQ(Hessian_row_x1_x2[x2], 0.); ASSERT_DOUBLE_EQ(Hessian_row_x1_x2[x3], -1 / 54.); // EXPECT_EQ(x1.tape().statement_size() - n_1, 1); EXPECT_EQ(x1.value().tape().statement_size() - nn_1, 23); EXPECT_EQ(x1.value().value().tape().statement_size() - nnn_1, 295); }
#pragma once #include "Characters.h" #include <string> using namespace std; /* Özet: S?n?f olu?turulurken yerine koyulacak alfabe küçük harflere kar??l?k gelmektedir. Örnek yerine koyulan alfabe a?a??dad?r ve Program?n Türkçe format?na uygun olacak biçimde kay?t edilmi?tir.*/ class YerineKoyma : public Characters { private: char PTurkish[29] = { 'f','d','e','a','c','h','g','b','ğ','ç','v','s','j','l','k','ı','n','r','z','p','ü','i','ş','y','u','o','m','t','ö' }; public: void Encryption(string& mesaj); void Decryption(string& mesaj); };
#ifndef STICKUINO_COMPONENTS_LIGHTSENSOR_H #define STICKUINO_COMPONENTS_LIGHTSENSOR_H #include "Component.h" namespace Stickuino { namespace Components { /// <summary> /// A light sensor. /// </summary> class LightSensor : public Component { public: /// <summary> /// Creates a new LightSensor. /// </summary> /// <param name="pin">The pin the LightSensor is hooked up to.</param> LightSensor(const int& pin); /// <summary> /// Gets the current value sensed by the LightSensor. /// </summary> /// <returns>The current sensor value. Ranges from 0-1023.</returns> int getLightValue() const; }; } } #endif
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package #ifndef JACTORIO_INCLUDE_PROTO_ABSTRACT_HEALTH_ENTITY_H #define JACTORIO_INCLUDE_PROTO_ABSTRACT_HEALTH_ENTITY_H #pragma once #include "proto/abstract/entity.h" namespace jactorio::proto { struct HealthEntityData : EntityData { uint16_t health = 0; CEREAL_SERIALIZE(archive) { archive(cereal::base_class<EntityData>(this), health); } }; class HealthEntity : public Entity { /// Default health of all Health entities static constexpr uint16_t kDefaultHealth = 1; protected: HealthEntity() = default; public: /// How many hit points this entity can have before it dies /// \remark 0 max health is invalid PYTHON_PROP_REF_I(uint16_t, maxHealth, kDefaultHealth); void PostLoadValidate(const data::PrototypeManager& proto) const override { Entity::PostLoadValidate(proto); J_PROTO_ASSERT(maxHealth > 0, "Max health must be greater than 0"); } }; } // namespace jactorio::proto #endif // JACTORIO_INCLUDE_PROTO_ABSTRACT_HEALTH_ENTITY_H
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MeshBasedCellPopulation.hpp" #include "VtkMeshWriter.hpp" #include "CellBasedEventHandler.hpp" #include "Cylindrical2dMesh.hpp" #include "Cylindrical2dVertexMesh.hpp" #include "Toroidal2dMesh.hpp" #include "Toroidal2dVertexMesh.hpp" #include "NodesOnlyMesh.hpp" #include "CellId.hpp" #include "CellVolumesWriter.hpp" #include "CellPopulationElementWriter.hpp" #include "VoronoiDataWriter.hpp" #include "NodeVelocityWriter.hpp" #include "CellPopulationAreaWriter.hpp" template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::MeshBasedCellPopulation(MutableMesh<ELEMENT_DIM,SPACE_DIM>& rMesh, std::vector<CellPtr>& rCells, const std::vector<unsigned> locationIndices, bool deleteMesh, bool validate) : AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>(rMesh, rCells, locationIndices), mpVoronoiTessellation(nullptr), mDeleteMesh(deleteMesh), mUseAreaBasedDampingConstant(false), mAreaBasedDampingConstantParameter(0.1), mWriteVtkAsPoints(false), mBoundVoronoiTessellation(false), mHasVariableRestLength(false) { mpMutableMesh = static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>* >(&(this->mrMesh)); assert(this->mCells.size() <= this->mrMesh.GetNumNodes()); if (validate) { Validate(); } // Initialise the applied force at each node to zero for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rGetMesh().GetNodeIteratorBegin(); node_iter != this->rGetMesh().GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::MeshBasedCellPopulation(MutableMesh<ELEMENT_DIM,SPACE_DIM>& rMesh) : AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>(rMesh) { mpMutableMesh = static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>* >(&(this->mrMesh)); mpVoronoiTessellation = nullptr; mDeleteMesh = true; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::~MeshBasedCellPopulation() { delete mpVoronoiTessellation; if (mDeleteMesh) { delete &this->mrMesh; } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> bool MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::UseAreaBasedDampingConstant() { return mUseAreaBasedDampingConstant; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetAreaBasedDampingConstant( [[maybe_unused]] bool useAreaBasedDampingConstant) // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9 { if constexpr (SPACE_DIM == 2) { mUseAreaBasedDampingConstant = useAreaBasedDampingConstant; } else { NEVER_REACHED; } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> unsigned MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AddNode(Node<SPACE_DIM>* pNewNode) { return mpMutableMesh->AddNode(pNewNode); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetNode(unsigned nodeIndex, ChastePoint<SPACE_DIM>& rNewLocation) { static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).SetNode(nodeIndex, rNewLocation, false); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetDampingConstant(unsigned nodeIndex) { double damping_multiplier = AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetDampingConstant(nodeIndex); /* * The next code block computes the area-dependent damping constant as given by equation * (5) in the following reference: van Leeuwen et al. 2009. An integrative computational model * for intestinal tissue renewal. Cell Prolif. 42(5):617-636. doi:10.1111/j.1365-2184.2009.00627.x */ if (mUseAreaBasedDampingConstant) { /** * We use a linear dependence of the form * * new_damping_const = old_damping_const * (d0+d1*A) * * where d0, d1 are parameters, A is the cell's area, and old_damping_const * is the damping constant if not using mUseAreaBasedDampingConstant */ if constexpr (SPACE_DIM == 2) { double rest_length = 1.0; double d0 = mAreaBasedDampingConstantParameter; /** * Compute the parameter d1 such that d0+A*d1=1, where A is the equilibrium area * of a cell (this is equal to sqrt(3.0)/4, which is a third of the area of a regular * hexagon of edge length 1) */ double d1 = 2.0*(1.0 - d0)/(sqrt(3.0)*rest_length*rest_length); double area_cell = GetVolumeOfVoronoiElement(nodeIndex); /** * The cell area should not be too large - the next assertion is to avoid * getting an infinite cell area, which may occur if area-based viscosity * is chosen in the absence of ghost nodes. */ assert(area_cell < 1000); damping_multiplier = d0 + area_cell*d1; } else { NEVER_REACHED; } } return damping_multiplier; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::Validate() { std::vector<bool> validated_node = std::vector<bool>(this->GetNumNodes(), false); for (typename AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>::Iterator cell_iter=this->Begin(); cell_iter!=this->End(); ++cell_iter) { unsigned node_index = this->GetLocationIndexUsingCell(*cell_iter); validated_node[node_index] = true; } for (unsigned i=0; i<validated_node.size(); i++) { if (!validated_node[i]) { EXCEPTION("At time " << SimulationTime::Instance()->GetTime() << ", Node " << i << " does not appear to have a cell associated with it"); } } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> MutableMesh<ELEMENT_DIM,SPACE_DIM>& MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::rGetMesh() { return *mpMutableMesh; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> const MutableMesh<ELEMENT_DIM,SPACE_DIM>& MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::rGetMesh() const { return *mpMutableMesh; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetTetrahedralMeshForPdeModifier() { return mpMutableMesh; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> unsigned MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::RemoveDeadCells() { unsigned num_removed = 0; for (std::list<CellPtr>::iterator it = this->mCells.begin(); it != this->mCells.end(); ) { if ((*it)->IsDead()) { // Check if this cell is in a marked spring std::vector<const std::pair<CellPtr,CellPtr>*> pairs_to_remove; // Pairs that must be purged for (std::set<std::pair<CellPtr,CellPtr> >::iterator it1 = this->mMarkedSprings.begin(); it1 != this->mMarkedSprings.end(); ++it1) { const std::pair<CellPtr,CellPtr>& r_pair = *it1; for (unsigned i=0; i<2; i++) { CellPtr p_cell = (i==0 ? r_pair.first : r_pair.second); if (p_cell == *it) { // Remember to purge this spring pairs_to_remove.push_back(&r_pair); break; } } } // Purge any marked springs that contained this cell for (std::vector<const std::pair<CellPtr,CellPtr>* >::iterator pair_it = pairs_to_remove.begin(); pair_it != pairs_to_remove.end(); ++pair_it) { this->mMarkedSprings.erase(**pair_it); } // Remove the node from the mesh num_removed++; static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).DeleteNodePriorToReMesh(this->GetLocationIndexUsingCell((*it))); // Update mappings between cells and location indices unsigned location_index_of_removed_node = this->GetLocationIndexUsingCell((*it)); this->RemoveCellUsingLocationIndex(location_index_of_removed_node, (*it)); // Update vector of cells it = this->mCells.erase(it); } else { ++it; } } return num_removed; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::Update(bool hasHadBirthsOrDeaths) { ///\todo check if there is a more efficient way of keeping track of node velocity information (#2404) bool output_node_velocities = (this-> template HasWriter<NodeVelocityWriter>()); /** * If node radii are set, then we must keep a record of these, since they will be cleared during * the remeshing process. We then restore these attributes to the nodes after calling ReMesh(). * * At present, we check whether node radii are set by interrogating the radius of the first node * in the mesh and asking if it is strictly greater than zero (the default value, as set in the * NodeAttributes constructor). Hence, we assume that either ALL node radii are set, or NONE are. * * \todo There may be a better way of checking if node radii are set (#2694) */ std::map<unsigned, double> old_node_radius_map; old_node_radius_map.clear(); if (this->mrMesh.GetNodeIteratorBegin()->HasNodeAttributes()) { if (this->mrMesh.GetNodeIteratorBegin()->GetRadius() > 0.0) { for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->mrMesh.GetNodeIteratorBegin(); node_iter != this->mrMesh.GetNodeIteratorEnd(); ++node_iter) { unsigned node_index = node_iter->GetIndex(); old_node_radius_map[node_index] = node_iter->GetRadius(); } } } std::map<unsigned, c_vector<double, SPACE_DIM> > old_node_applied_force_map; old_node_applied_force_map.clear(); if (output_node_velocities) { /* * If outputting node velocities, we must keep a record of the applied force at each * node, since this will be cleared during the remeshing process. We then restore * these attributes to the nodes after calling ReMesh(). */ for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->mrMesh.GetNodeIteratorBegin(); node_iter != this->mrMesh.GetNodeIteratorEnd(); ++node_iter) { unsigned node_index = node_iter->GetIndex(); old_node_applied_force_map[node_index] = node_iter->rGetAppliedForce(); } } NodeMap node_map(this->mrMesh.GetNumAllNodes()); // We must use a static_cast to call ReMesh() as this method is not defined in parent mesh classes static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).ReMesh(node_map); if (!node_map.IsIdentityMap()) { UpdateGhostNodesAfterReMesh(node_map); // Update the mappings between cells and location indices std::map<Cell*, unsigned> old_cell_location_map = this->mCellLocationMap; // Remove any dead pointers from the maps (needed to avoid archiving errors) this->mLocationCellMap.clear(); this->mCellLocationMap.clear(); for (std::list<CellPtr>::iterator it = this->mCells.begin(); it != this->mCells.end(); ++it) { unsigned old_node_index = old_cell_location_map[(*it).get()]; // This shouldn't ever happen, as the cell vector only contains living cells assert(!node_map.IsDeleted(old_node_index)); unsigned new_node_index = node_map.GetNewIndex(old_node_index); this->SetCellUsingLocationIndex(new_node_index,*it); if (old_node_radius_map[old_node_index] > 0.0) { this->GetNode(new_node_index)->SetRadius(old_node_radius_map[old_node_index]); } if (output_node_velocities) { this->GetNode(new_node_index)->AddAppliedForceContribution(old_node_applied_force_map[old_node_index]); } } this->Validate(); } else { if (old_node_radius_map[this->mCellLocationMap[(*(this->mCells.begin())).get()]] > 0.0) { for (std::list<CellPtr>::iterator it = this->mCells.begin(); it != this->mCells.end(); ++it) { unsigned node_index = this->mCellLocationMap[(*it).get()]; this->GetNode(node_index)->SetRadius(old_node_radius_map[node_index]); } } if (output_node_velocities) { for (std::list<CellPtr>::iterator it = this->mCells.begin(); it != this->mCells.end(); ++it) { unsigned node_index = this->mCellLocationMap[(*it).get()]; this->GetNode(node_index)->AddAppliedForceContribution(old_node_applied_force_map[node_index]); } } } // Purge any marked springs that are no longer springs std::vector<const std::pair<CellPtr,CellPtr>*> springs_to_remove; for (std::set<std::pair<CellPtr,CellPtr> >::iterator spring_it = this->mMarkedSprings.begin(); spring_it != this->mMarkedSprings.end(); ++spring_it) { CellPtr p_cell_1 = spring_it->first; CellPtr p_cell_2 = spring_it->second; Node<SPACE_DIM>* p_node_1 = this->GetNodeCorrespondingToCell(p_cell_1); Node<SPACE_DIM>* p_node_2 = this->GetNodeCorrespondingToCell(p_cell_2); bool joined = false; // For each element containing node1, if it also contains node2 then the cells are joined std::set<unsigned> node2_elements = p_node_2->rGetContainingElementIndices(); for (typename Node<SPACE_DIM>::ContainingElementIterator elem_iter = p_node_1->ContainingElementsBegin(); elem_iter != p_node_1->ContainingElementsEnd(); ++elem_iter) { if (node2_elements.find(*elem_iter) != node2_elements.end()) { joined = true; break; } } // If no longer joined, remove this spring from the set if (!joined) { springs_to_remove.push_back(&(*spring_it)); } } // Remove any springs necessary for (std::vector<const std::pair<CellPtr,CellPtr>* >::iterator spring_it = springs_to_remove.begin(); spring_it != springs_to_remove.end(); ++spring_it) { this->mMarkedSprings.erase(**spring_it); } // Tessellate if needed TessellateIfNeeded(); static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).SetMeshHasChangedSinceLoading(); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::TessellateIfNeeded() { if ((SPACE_DIM==2 || SPACE_DIM==3)&&(ELEMENT_DIM==SPACE_DIM)) { CellBasedEventHandler::BeginEvent(CellBasedEventHandler::TESSELLATION); if (mUseAreaBasedDampingConstant || this-> template HasWriter<VoronoiDataWriter>() || this-> template HasWriter<CellPopulationAreaWriter>() || this-> template HasWriter<CellVolumesWriter>()) { CreateVoronoiTessellation(); } CellBasedEventHandler::EndEvent(CellBasedEventHandler::TESSELLATION); } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::DivideLongSprings([[maybe_unused]] double springDivisionThreshold) // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9 { // Only implemented for 2D elements if constexpr (ELEMENT_DIM == 2) { std::vector<c_vector<unsigned, 5> > new_nodes; new_nodes = rGetMesh().SplitLongEdges(springDivisionThreshold); // Add new cells onto new nodes for (unsigned index=0; index<new_nodes.size(); index++) { // Copy the cell attached to one of the neighbouring nodes onto the new node unsigned new_node_index = new_nodes[index][0]; unsigned node_a_index = new_nodes[index][1]; unsigned node_b_index = new_nodes[index][2]; CellPtr p_neighbour_cell = this->GetCellUsingLocationIndex(node_a_index); // Create copy of cell property collection to modify for daughter cell CellPropertyCollection daughter_property_collection = p_neighbour_cell->rGetCellPropertyCollection(); // Remove the CellId from the daughter cell a new one will be assigned in the constructor daughter_property_collection.RemoveProperty<CellId>(); CellPtr p_new_cell(new Cell(p_neighbour_cell->GetMutationState(), p_neighbour_cell->GetCellCycleModel()->CreateCellCycleModel(), p_neighbour_cell->GetSrnModel()->CreateSrnModel(), false, daughter_property_collection)); // Add new cell to cell population this->mCells.push_back(p_new_cell); this->AddCellUsingLocationIndex(new_node_index,p_new_cell); // Update rest lengths // Remove old node pair // note node_a_index < node_b_index std::pair<unsigned,unsigned> node_pair = this->CreateOrderedPair(node_a_index, node_b_index); double old_rest_length = mSpringRestLengths[node_pair]; std::map<std::pair<unsigned,unsigned>, double>::iterator iter = mSpringRestLengths.find(node_pair); mSpringRestLengths.erase(iter); // Add new pairs node_pair = this->CreateOrderedPair(node_a_index, new_node_index); mSpringRestLengths[node_pair] = 0.5*old_rest_length; node_pair = this->CreateOrderedPair(node_b_index, new_node_index); mSpringRestLengths[node_pair] = 0.5*old_rest_length; // If necessary add other new spring rest lengths for (unsigned pair_index=3; pair_index<5; pair_index++) { unsigned other_node_index = new_nodes[index][pair_index]; if (other_node_index != UNSIGNED_UNSET) { node_pair = this->CreateOrderedPair(other_node_index, new_node_index); double new_rest_length = rGetMesh().GetDistanceBetweenNodes(new_node_index, other_node_index); mSpringRestLengths[node_pair] = new_rest_length; } } } } else { NEVER_REACHED; } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> Node<SPACE_DIM>* MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetNode(unsigned index) { return this->mrMesh.GetNode(index); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> unsigned MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetNumNodes() { return this->mrMesh.GetNumAllNodes(); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::UpdateGhostNodesAfterReMesh(NodeMap& rMap) { } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> CellPtr MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AddCell(CellPtr pNewCell, CellPtr pParentCell) { assert(pNewCell); assert(pParentCell); // Add new cell to population CellPtr p_created_cell = AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AddCell(pNewCell, pParentCell); assert(p_created_cell == pNewCell); // Mark spring between parent cell and new cell std::pair<CellPtr,CellPtr> cell_pair = this->CreateCellPair(pParentCell, p_created_cell); this->MarkSpring(cell_pair); // Return pointer to new cell return p_created_cell; } ////////////////////////////////////////////////////////////////////////////// // Output methods // ////////////////////////////////////////////////////////////////////////////// template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::OpenWritersFiles(OutputFileHandler& rOutputFileHandler) { if (this->mOutputResultsForChasteVisualizer) { if (!this-> template HasWriter<CellPopulationElementWriter>()) { this-> template AddPopulationWriter<CellPopulationElementWriter>(); } } AbstractCentreBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>::OpenWritersFiles(rOutputFileHandler); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::WriteResultsToFiles(const std::string& rDirectory) { if (SimulationTime::Instance()->GetTimeStepsElapsed() == 0 && this->mpVoronoiTessellation == nullptr) { TessellateIfNeeded(); // Update isn't run on time-step zero } AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::WriteResultsToFiles(rDirectory); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AcceptPopulationWriter(boost::shared_ptr<AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> > pPopulationWriter) { pPopulationWriter->Visit(this); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AcceptPopulationCountWriter(boost::shared_ptr<AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM> > pPopulationCountWriter) { pPopulationCountWriter->Visit(this); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AcceptPopulationEventWriter(boost::shared_ptr<AbstractCellPopulationEventWriter<ELEMENT_DIM, SPACE_DIM> > pPopulationEventWriter) { pPopulationEventWriter->Visit(this); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::AcceptCellWriter(boost::shared_ptr<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> > pCellWriter, CellPtr pCell) { pCellWriter->VisitCell(pCell, this); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::WriteVtkResultsToFile(const std::string& rDirectory) { #ifdef CHASTE_VTK // Store the present time as a string unsigned num_timesteps = SimulationTime::Instance()->GetTimeStepsElapsed(); std::stringstream time; time << num_timesteps; // Store the number of cells for which to output data to VTK unsigned num_cells_from_mesh = GetNumNodes(); // When outputting any CellData, we assume that the first cell is representative of all cells unsigned num_cell_data_items = this->Begin()->GetCellData()->GetNumItems(); std::vector<std::string> cell_data_names = this->Begin()->GetCellData()->GetKeys(); std::vector<std::vector<double> > cell_data; for (unsigned var=0; var<num_cell_data_items; var++) { std::vector<double> cell_data_var(num_cells_from_mesh); cell_data.push_back(cell_data_var); } if (mWriteVtkAsPoints) { // Create mesh writer for VTK output VtkMeshWriter<ELEMENT_DIM, SPACE_DIM> cells_writer(rDirectory, "mesh_results_"+time.str(), false); // Iterate over any cell writers that are present unsigned num_cells = this->GetNumAllCells(); for (typename std::vector<boost::shared_ptr<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator cell_writer_iter = this->mCellWriters.begin(); cell_writer_iter != this->mCellWriters.end(); ++cell_writer_iter) { // Create vector to store VTK cell data std::vector<double> vtk_cell_data(num_cells); // Loop over cells for (typename AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>::Iterator cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { // Get the node index corresponding to this cell unsigned node_index = this->GetLocationIndexUsingCell(*cell_iter); // Populate the vector of VTK cell data vtk_cell_data[node_index] = (*cell_writer_iter)->GetCellDataForVtkOutput(*cell_iter, this); } cells_writer.AddPointData((*cell_writer_iter)->GetVtkCellDataName(), vtk_cell_data); } // Loop over cells for (typename AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>::Iterator cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { // Get the node index corresponding to this cell unsigned node_index = this->GetLocationIndexUsingCell(*cell_iter); for (unsigned var=0; var<num_cell_data_items; var++) { cell_data[var][node_index] = cell_iter->GetCellData()->GetItem(cell_data_names[var]); } } for (unsigned var=0; var<num_cell_data_items; var++) { cells_writer.AddPointData(cell_data_names[var], cell_data[var]); } // Write data using the mesh cells_writer.WriteFilesUsingMesh(rGetMesh()); *(this->mpVtkMetaFile) << " <DataSet timestep=\""; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << "\" group=\"\" part=\"0\" file=\"mesh_results_"; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << ".vtu\"/>\n"; } if (mpVoronoiTessellation != nullptr) { // Create mesh writer for VTK output VertexMeshWriter<ELEMENT_DIM, SPACE_DIM> mesh_writer(rDirectory, "voronoi_results", false); std::vector<double> cell_volumes(num_cells_from_mesh); // Iterate over any cell writers that are present unsigned num_cells = this->GetNumAllCells(); for (typename std::vector<boost::shared_ptr<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator cell_writer_iter = this->mCellWriters.begin(); cell_writer_iter != this->mCellWriters.end(); ++cell_writer_iter) { // Create vector to store VTK cell data std::vector<double> vtk_cell_data(num_cells); // Loop over elements of mpVoronoiTessellation for (typename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator elem_iter = mpVoronoiTessellation->GetElementIteratorBegin(); elem_iter != mpVoronoiTessellation->GetElementIteratorEnd(); ++elem_iter) { // Get index of this element in mpVoronoiTessellation unsigned elem_index = elem_iter->GetIndex(); // Get the cell corresponding to this element, via the index of the corresponding node in mrMesh unsigned node_index = mpVoronoiTessellation->GetDelaunayNodeIndexCorrespondingToVoronoiElementIndex(elem_index); CellPtr p_cell = this->GetCellUsingLocationIndex(node_index); // Populate the vector of VTK cell data vtk_cell_data[elem_index] = (*cell_writer_iter)->GetCellDataForVtkOutput(p_cell, this); } mesh_writer.AddCellData((*cell_writer_iter)->GetVtkCellDataName(), vtk_cell_data); } // Loop over elements of mpVoronoiTessellation for (typename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator elem_iter = mpVoronoiTessellation->GetElementIteratorBegin(); elem_iter != mpVoronoiTessellation->GetElementIteratorEnd(); ++elem_iter) { // Get index of this element in mpVoronoiTessellation unsigned elem_index = elem_iter->GetIndex(); // Get the cell corresponding to this element, via the index of the corresponding node in mrMesh unsigned node_index = mpVoronoiTessellation->GetDelaunayNodeIndexCorrespondingToVoronoiElementIndex(elem_index); CellPtr p_cell = this->GetCellUsingLocationIndex(node_index); for (unsigned var=0; var<num_cell_data_items; var++) { cell_data[var][elem_index] = p_cell->GetCellData()->GetItem(cell_data_names[var]); } } for (unsigned var=0; var<cell_data.size(); var++) { mesh_writer.AddCellData(cell_data_names[var], cell_data[var]); } mesh_writer.WriteVtkUsingMesh(*mpVoronoiTessellation, time.str()); *(this->mpVtkMetaFile) << " <DataSet timestep=\""; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << "\" group=\"\" part=\"0\" file=\"voronoi_results_"; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << ".vtu\"/>\n"; } #endif //CHASTE_VTK } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetVolumeOfCell(CellPtr pCell) { double cell_volume = 0; if (ELEMENT_DIM == SPACE_DIM) { // Ensure that the Voronoi tessellation exists if (mpVoronoiTessellation == nullptr) { CreateVoronoiTessellation(); } // Get the node index corresponding to this cell unsigned node_index = this->GetLocationIndexUsingCell(pCell); // Try to get the element index of the Voronoi tessellation corresponding to this node index try { unsigned element_index = mpVoronoiTessellation->GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(node_index); // Get the cell's volume from the Voronoi tessellation cell_volume = mpVoronoiTessellation->GetVolumeOfElement(element_index); } catch (Exception&) { // If it doesn't exist this must be a boundary cell, so return infinite volume cell_volume = DBL_MAX; } } else if (SPACE_DIM==3 && ELEMENT_DIM==2) { unsigned node_index = this->GetLocationIndexUsingCell(pCell); Node<SPACE_DIM>* p_node = rGetMesh().GetNode(node_index); assert(!(p_node->rGetContainingElementIndices().empty())); for (typename Node<SPACE_DIM>::ContainingElementIterator elem_iter = p_node->ContainingElementsBegin(); elem_iter != p_node->ContainingElementsEnd(); ++elem_iter) { Element<ELEMENT_DIM,SPACE_DIM>* p_element = rGetMesh().GetElement(*elem_iter); c_matrix<double, SPACE_DIM, ELEMENT_DIM> jacob; double det; p_element->CalculateJacobian(jacob, det); cell_volume += fabs(p_element->GetVolume(det)); } // This calculation adds a third of each element to the total area cell_volume /= 3.0; } else { // Not implemented for other dimensions NEVER_REACHED; } return cell_volume; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetWriteVtkAsPoints(bool writeVtkAsPoints) { mWriteVtkAsPoints = writeVtkAsPoints; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> bool MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetWriteVtkAsPoints() { return mWriteVtkAsPoints; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetBoundVoronoiTessellation(bool boundVoronoiTessellation) { mBoundVoronoiTessellation = boundVoronoiTessellation; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> bool MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetBoundVoronoiTessellation() { return mBoundVoronoiTessellation; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::WriteDataToVisualizerSetupFile(out_stream& pVizSetupFile) { if (bool(dynamic_cast<Cylindrical2dMesh*>(&(this->mrMesh)))) { *pVizSetupFile << "MeshWidth\t" << this->GetWidth(0) << "\n"; } if (bool(dynamic_cast<Toroidal2dMesh*>(&(this->mrMesh)))) { *pVizSetupFile << "MeshWidth\t" << this->GetWidth(0) << "\n"; *pVizSetupFile << "MeshHeight\t" << this->GetWidth(1) << "\n"; } } ////////////////////////////////////////////////////////////////////////////// // Spring iterator class // ////////////////////////////////////////////////////////////////////////////// template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> Node<SPACE_DIM>* MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::GetNodeA() { return mEdgeIter.GetNodeA(); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> Node<SPACE_DIM>* MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::GetNodeB() { return mEdgeIter.GetNodeB(); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> CellPtr MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::GetCellA() { assert((*this) != mrCellPopulation.SpringsEnd()); return mrCellPopulation.GetCellUsingLocationIndex(mEdgeIter.GetNodeA()->GetIndex()); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> CellPtr MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::GetCellB() { assert((*this) != mrCellPopulation.SpringsEnd()); return mrCellPopulation.GetCellUsingLocationIndex(mEdgeIter.GetNodeB()->GetIndex()); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> bool MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::operator!=(const typename MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator& rOther) { return (mEdgeIter != rOther.mEdgeIter); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> typename MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator& MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::operator++() { bool edge_is_ghost = false; do { ++mEdgeIter; if (*this != mrCellPopulation.SpringsEnd()) { bool a_is_ghost = mrCellPopulation.IsGhostNode(mEdgeIter.GetNodeA()->GetIndex()); bool b_is_ghost = mrCellPopulation.IsGhostNode(mEdgeIter.GetNodeB()->GetIndex()); edge_is_ghost = (a_is_ghost || b_is_ghost); } } while (*this!=mrCellPopulation.SpringsEnd() && edge_is_ghost); return (*this); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator::SpringIterator( MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation, typename MutableMesh<ELEMENT_DIM,SPACE_DIM>::EdgeIterator edgeIter) : mrCellPopulation(rCellPopulation), mEdgeIter(edgeIter) { if (mEdgeIter!=static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>*>(&(this->mrCellPopulation.mrMesh))->EdgesEnd()) { bool a_is_ghost = mrCellPopulation.IsGhostNode(mEdgeIter.GetNodeA()->GetIndex()); bool b_is_ghost = mrCellPopulation.IsGhostNode(mEdgeIter.GetNodeB()->GetIndex()); if (a_is_ghost || b_is_ghost) { ++(*this); } } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> typename MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringsBegin() { return SpringIterator(*this, static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).EdgesBegin()); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> typename MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringIterator MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SpringsEnd() { return SpringIterator(*this, static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).EdgesEnd()); } /** * */ template<> void MeshBasedCellPopulation<2>::CreateVoronoiTessellation() { delete mpVoronoiTessellation; // Check if the mesh associated with this cell population is periodic bool is_mesh_periodic = false; if (bool(dynamic_cast<Cylindrical2dMesh*>(&mrMesh))) { is_mesh_periodic = true; mpVoronoiTessellation = new Cylindrical2dVertexMesh(static_cast<Cylindrical2dMesh &>(this->mrMesh), mBoundVoronoiTessellation); } else if (bool(dynamic_cast<Toroidal2dMesh*>(&(this->mrMesh)))) { is_mesh_periodic = true; mpVoronoiTessellation = new Toroidal2dVertexMesh(static_cast<Toroidal2dMesh &>(this->mrMesh), mBoundVoronoiTessellation); } else { mpVoronoiTessellation = new VertexMesh<2, 2>(static_cast<MutableMesh<2, 2> &>((this->mrMesh)), is_mesh_periodic, mBoundVoronoiTessellation); } } /** * Can't tessellate 2d meshes in 3d space yet. */ // LCOV_EXCL_START template<> void MeshBasedCellPopulation<2,3>::CreateVoronoiTessellation() { // We don't allow tessellation yet. NEVER_REACHED; } // LCOV_EXCL_STOP /** * The cylindrical mesh is only defined in 2D, hence there is * a separate definition for this method in 3D, which doesn't have the capability * of dealing with periodic boundaries in 3D. This is \todo #1374. */ template<> void MeshBasedCellPopulation<3>::CreateVoronoiTessellation() { delete mpVoronoiTessellation; mpVoronoiTessellation = new VertexMesh<3, 3>(static_cast<MutableMesh<3, 3> &>((this->mrMesh))); } /** * The VoronoiTessellation class is only defined in 2D or 3D, hence there * are two definitions to this method (one templated and one not). */ // LCOV_EXCL_START template<> void MeshBasedCellPopulation<1, 1>::CreateVoronoiTessellation() { // No 1D Voronoi tessellation NEVER_REACHED; } // LCOV_EXCL_STOP /** * The VoronoiTessellation class is only defined in 2D or 3D, hence there * are two definitions to this method (one templated and one not). */ // LCOV_EXCL_START template<> void MeshBasedCellPopulation<1, 2>::CreateVoronoiTessellation() { // No 1D Voronoi tessellation NEVER_REACHED; } // LCOV_EXCL_STOP /** * The VoronoiTessellation class is only defined in 2D or 3D, hence there * are two definitions to this method (one templated and one not). */ // LCOV_EXCL_START template<> void MeshBasedCellPopulation<1, 3>::CreateVoronoiTessellation() { // No 1D Voronoi tessellation NEVER_REACHED; } // LCOV_EXCL_STOP template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> VertexMesh<ELEMENT_DIM,SPACE_DIM>* MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetVoronoiTessellation() { assert(mpVoronoiTessellation!=nullptr); return mpVoronoiTessellation; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetVolumeOfVoronoiElement(unsigned index) { unsigned element_index = mpVoronoiTessellation->GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(index); double volume = mpVoronoiTessellation->GetVolumeOfElement(element_index); return volume; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetSurfaceAreaOfVoronoiElement(unsigned index) { unsigned element_index = mpVoronoiTessellation->GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(index); double surface_area = mpVoronoiTessellation->GetSurfaceAreaOfElement(element_index); return surface_area; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetVoronoiEdgeLength(unsigned index1, unsigned index2) { unsigned element_index1 = mpVoronoiTessellation->GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(index1); unsigned element_index2 = mpVoronoiTessellation->GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(index2); try { double edge_length = mpVoronoiTessellation->GetEdgeLength(element_index1, element_index2); return edge_length; } catch (Exception&) { // The edge was between two (potentially infinite) cells on the boundary of the mesh EXCEPTION("Spring iterator tried to calculate interaction between degenerate cells on the boundary of the mesh. Have you set ghost layers correctly?"); } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::CheckCellPointers() { bool res = true; for (std::list<CellPtr>::iterator it=this->mCells.begin(); it!=this->mCells.end(); ++it) { CellPtr p_cell = *it; assert(p_cell); AbstractCellCycleModel* p_model = p_cell->GetCellCycleModel(); assert(p_model); // Check cell exists in cell population unsigned node_index = this->GetLocationIndexUsingCell(p_cell); std::cout << "Cell at node " << node_index << " addr " << p_cell << std::endl << std::flush; CellPtr p_cell_in_cell_population = this->GetCellUsingLocationIndex(node_index); // LCOV_EXCL_START //Debugging code. Shouldn't fail under normal conditions if (p_cell_in_cell_population != p_cell) { std::cout << " Mismatch with cell population" << std::endl << std::flush; res = false; } // Check model links back to cell if (p_model->GetCell() != p_cell) { std::cout << " Mismatch with cycle model" << std::endl << std::flush; res = false; } } UNUSED_OPT(res); assert(res); // LCOV_EXCL_STOP res = true; for (std::set<std::pair<CellPtr,CellPtr> >::iterator it1 = this->mMarkedSprings.begin(); it1 != this->mMarkedSprings.end(); ++it1) { const std::pair<CellPtr,CellPtr>& r_pair = *it1; for (unsigned i=0; i<2; i++) { CellPtr p_cell = (i==0 ? r_pair.first : r_pair.second); assert(p_cell); AbstractCellCycleModel* p_model = p_cell->GetCellCycleModel(); assert(p_model); unsigned node_index = this->GetLocationIndexUsingCell(p_cell); std::cout << "Cell at node " << node_index << " addr " << p_cell << std::endl << std::flush; // LCOV_EXCL_START //Debugging code. Shouldn't fail under normal conditions // Check cell is alive if (p_cell->IsDead()) { std::cout << " Cell is dead" << std::endl << std::flush; res = false; } // Check cell exists in cell population CellPtr p_cell_in_cell_population = this->GetCellUsingLocationIndex(node_index); if (p_cell_in_cell_population != p_cell) { std::cout << " Mismatch with cell population" << std::endl << std::flush; res = false; } // Check model links back to cell if (p_model->GetCell() != p_cell) { std::cout << " Mismatch with cycle model" << std::endl << std::flush; res = false; } } // LCOV_EXCL_STOP } assert(res); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetAreaBasedDampingConstantParameter() { return mAreaBasedDampingConstantParameter; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetAreaBasedDampingConstantParameter(double areaBasedDampingConstantParameter) { assert(areaBasedDampingConstantParameter >= 0.0); mAreaBasedDampingConstantParameter = areaBasedDampingConstantParameter; } // LCOV_EXCL_START template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> std::vector< std::pair<Node<SPACE_DIM>*, Node<SPACE_DIM>* > >& MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::rGetNodePairs() { //mNodePairs.Clear(); NEVER_REACHED; return mNodePairs; } // LCOV_EXCL_STOP template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::OutputCellPopulationParameters(out_stream& rParamsFile) { *rParamsFile << "\t\t<UseAreaBasedDampingConstant>" << mUseAreaBasedDampingConstant << "</UseAreaBasedDampingConstant>\n"; *rParamsFile << "\t\t<AreaBasedDampingConstantParameter>" << mAreaBasedDampingConstantParameter << "</AreaBasedDampingConstantParameter>\n"; *rParamsFile << "\t\t<WriteVtkAsPoints>" << mWriteVtkAsPoints << "</WriteVtkAsPoints>\n"; *rParamsFile << "\t\t<BoundVoronoiTessellation>" << mBoundVoronoiTessellation << "</BoundVoronoiTessellation>\n"; *rParamsFile << "\t\t<HasVariableRestLength>" << mHasVariableRestLength << "</HasVariableRestLength>\n"; // Call method on direct parent class AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::OutputCellPopulationParameters(rParamsFile); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetWidth(const unsigned& rDimension) { // Call GetWidth() on the mesh double width = this->mrMesh.GetWidth(rDimension); return width; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> std::set<unsigned> MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetNeighbouringNodeIndices(unsigned index) { // Get pointer to this node Node<SPACE_DIM>* p_node = this->mrMesh.GetNode(index); // Loop over containing elements std::set<unsigned> neighbouring_node_indices; for (typename Node<SPACE_DIM>::ContainingElementIterator elem_iter = p_node->ContainingElementsBegin(); elem_iter != p_node->ContainingElementsEnd(); ++elem_iter) { // Get pointer to this containing element Element<ELEMENT_DIM,SPACE_DIM>* p_element = static_cast<MutableMesh<ELEMENT_DIM,SPACE_DIM>&>((this->mrMesh)).GetElement(*elem_iter); // Loop over nodes contained in this element for (unsigned i=0; i<p_element->GetNumNodes(); i++) { // Get index of this node and add its index to the set if not the original node unsigned node_index = p_element->GetNodeGlobalIndex(i); if (node_index != index) { neighbouring_node_indices.insert(node_index); } } } return neighbouring_node_indices; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::CalculateRestLengths() { mSpringRestLengths.clear(); // Iterate over all springs and add calculate separation of adjacent node pairs for (SpringIterator spring_iterator = SpringsBegin(); spring_iterator != SpringsEnd(); ++spring_iterator) { // Note that nodeA_global_index is always less than nodeB_global_index Node<SPACE_DIM>* p_nodeA = spring_iterator.GetNodeA(); Node<SPACE_DIM>* p_nodeB = spring_iterator.GetNodeB(); unsigned nodeA_global_index = p_nodeA->GetIndex(); unsigned nodeB_global_index = p_nodeB->GetIndex(); // Calculate the distance between nodes double separation = rGetMesh().GetDistanceBetweenNodes(nodeA_global_index, nodeB_global_index); // Order node indices std::pair<unsigned,unsigned> node_pair = this->CreateOrderedPair(nodeA_global_index, nodeB_global_index); mSpringRestLengths[node_pair] = separation; } mHasVariableRestLength = true; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::GetRestLength(unsigned indexA, unsigned indexB) { if (mHasVariableRestLength) { std::pair<unsigned,unsigned> node_pair = this->CreateOrderedPair(indexA, indexB); std::map<std::pair<unsigned,unsigned>, double>::const_iterator iter = mSpringRestLengths.find(node_pair); if (iter != mSpringRestLengths.end()) { // Return the stored rest length return iter->second; } else { EXCEPTION("Tried to get a rest length of an edge that doesn't exist. You can only use variable rest lengths if SetUpdateCellPopulationRule is set on the simulation."); } } else { return 1.0; } } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void MeshBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>::SetRestLength(unsigned indexA, unsigned indexB, double restLength) { if (mHasVariableRestLength) { std::pair<unsigned,unsigned> node_pair = this->CreateOrderedPair(indexA, indexB); std::map<std::pair<unsigned,unsigned>, double>::iterator iter = mSpringRestLengths.find(node_pair); if (iter != mSpringRestLengths.end()) { // modify the stored rest length iter->second = restLength; } else { EXCEPTION("Tried to set the rest length of an edge not in the mesh."); } } else { EXCEPTION("Tried to set a rest length in a simulation with fixed rest length. You can only use variable rest lengths if SetUpdateCellPopulationRule is set on the simulation."); } } // Explicit instantiation template class MeshBasedCellPopulation<1,1>; template class MeshBasedCellPopulation<1,2>; template class MeshBasedCellPopulation<2,2>; template class MeshBasedCellPopulation<1,3>; template class MeshBasedCellPopulation<2,3>; template class MeshBasedCellPopulation<3,3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_ALL_DIMS(MeshBasedCellPopulation)
#include "sdw_file.h" #include "sdw_string.h" #if !defined(__ANDROID__) void fu16printf(FILE* a_pFile, const wchar_t* a_szFormat, ...) { va_list vaList; va_start(vaList, a_szFormat); wstring sFormatted = FormatV(a_szFormat, vaList); va_end(vaList); U16String sString = WToU16(sFormatted); fwrite(sString.c_str(), 2, sString.size(), a_pFile); } #endif FILE* Fopen(const char* a_pFileName, const char* a_pMode, bool a_bVerbose /* = true */) { FILE* fp = fopen(a_pFileName, a_pMode); if (fp == nullptr && a_bVerbose) { #if !defined(SDW_ANDROID_HIDE_LOG_STRING) printf("ERROR: open file %s failed\n\n", a_pFileName); #endif } return fp; } #if SDW_PLATFORM == SDW_PLATFORM_WINDOWS FILE* FopenW(const wchar_t* a_pFileName, const wchar_t* a_pMode, bool a_bVerbose /* = true */) { FILE* fp = _wfopen(a_pFileName, a_pMode); if (fp == nullptr && a_bVerbose) { #if !defined(SDW_ANDROID_HIDE_LOG_STRING) wprintf(L"ERROR: open file %ls failed\n\n", a_pFileName); #endif } return fp; } #endif
#include <windows.h> #include <fstream> #include <stdio.h> #include <ctime> #include "detours.h" #include "wrapper.h" #include "IFPLoader.h" #pragma comment(lib, "detours.lib") void PrepareOutputStreams(); inline bool isKeyPressed(unsigned int keyCode); extern std::ofstream ofs; extern std::wofstream ofsW; std::map<DWORD, std::string> g_mapOfAnimHierarchyHashes; void * g_Clump = nullptr; bool g_bAllowToPlayCustomAnimation = false; CAnimBlendStaticAssociation * pAnimStaticAssoc1 = nullptr; CAnimBlendStaticAssociation * pAnimStaticAssoc2 = nullptr; hGetAnimationBlock OLD_GetAnimationBlock = (hGetAnimationBlock)0x4d3940; hGetAnimation OLD_GetAnimation = (hGetAnimation)0x4d42f0; hGetAnimBlockName OLD_GetAnimBlockName = (hGetAnimBlockName) 0x4d3a30; hAddAnimAssocDefinition OLD_AddAnimAssocDefinition = (hAddAnimAssocDefinition) 0x4D3BA0; hRegisterAnimBlock OLD_RegisterAnimBlock = (hRegisterAnimBlock) 0x4D3E50; hCreateAssociations_Clump OLD_CreateAssociations_Clump = (hCreateAssociations_Clump) 0x4CE6E0; hCreateAssociations OLD_CreateAssociations = (hCreateAssociations) 0x4CE3B0; hRpAnimBlendClumpGetAssociation OLD_RpAnimBlendClumpGetAssociation = (hRpAnimBlendClumpGetAssociation) 0x4d6870; hRpAnimBlendClumpGetAssociationAnimId OLD_RpAnimBlendClumpGetAssociationAnimId = (hRpAnimBlendClumpGetAssociationAnimId) 0x4D68B0; hGetAnimAssociationAnimId OLD_GetAnimAssociationAnimId = (hGetAnimAssociationAnimId) 0x4d3a60; hCreateAnimAssociation OLD_CreateAnimAssociation = (hCreateAnimAssociation)0x4d3a40; hAddAnimation OLD_AddAnimation = (hAddAnimation)0x4d3aa0; hAddAnimationAndSync OLD_AddAnimationAndSync = (hAddAnimationAndSync)0x004D3B30; hGetAnimGroupName OLD_GetAnimGroupName = (hGetAnimGroupName)0x4d3a20; hCAnimBlendStaticAssociation_Constructor OLD_CAnimBlendStaticAssociation_Constructor = *(hCAnimBlendStaticAssociation_Constructor)0x4CE940; hCAnimBlendStaticAssociation_Init OLD_CAnimBlendStaticAssociation_Init = (hCAnimBlendStaticAssociation_Init)0x004CEC20; hCAnimBlendAssociation_Init_reference OLD_CAnimBlendAssociation_Init_reference = (hCAnimBlendAssociation_Init_reference)0x4CEEC0; hCAnimBlendAssociation_Init OLD_CAnimBlendAssociation_Init = (hCAnimBlendAssociation_Init)0x4CED50; hCAnimBlendHierarchy_SetName OLD_CAnimBlendHierarchy_SetName = (hCAnimBlendHierarchy_SetName)0x4CF2D0; hGetUppercaseKey OLD_GetUppercaseKey = (hGetUppercaseKey)0x53CF30; hLoadAnimFile_stream OLD_LoadAnimFile_stream = (hLoadAnimFile_stream)0x4d47f0; hAddAnimation_hier OLD_AddAnimation_hier = (hAddAnimation_hier)0x4d4330; hLoadPedAnimIFPFile OLD_LoadPedAnimIFPFile = (hLoadPedAnimIFPFile)0x004D5620; CAnimBlendAssociation *__cdecl OriginalAddAnimation(int pClump, int GroupID, int AnimID); CAnimBlendAssociation * __cdecl OriginalAddAnimationAndSync(int pClump, CAnimBlendAssociation * pAnimAssocToSyncWith, int GroupID, int AnimID); void HookFunctions() { DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach ( &(PVOID&) OLD_AddAnimAssocDefinition, NEW_AddAnimAssocDefinition ); DetourAttach ( &(PVOID&) OLD_RegisterAnimBlock , NEW_RegisterAnimBlock ); //DetourAttach ( &(PVOID&) OLD_CreateAssociations_Clump, NEW_CreateAssociations_Clump ); //DetourAttach ( &(PVOID&) OLD_CreateAssociations , NEW_CreateAssociations ); //DetourAttach(&(PVOID&)OLD_CreateAnimAssociation, NEW_CreateAnimAssociation); DetourAttach(&(PVOID&)OLD_AddAnimation, NEW_AddAnimation); DetourAttach(&(PVOID&)OLD_AddAnimationAndSync, NEW_AddAnimationAndSync); //DetourAttach(&(PVOID&)OLD_AddAnimation, OriginalAddAnimation); //DetourAttach(&(PVOID&)OLD_AddAnimationAndSync, OriginalAddAnimationAndSync); DetourAttach(&(PVOID&)OLD_GetUppercaseKey, NEW_GetUppercaseKey); //DetourAttach(&(PVOID&)OLD_LoadAnimFile_stream, NEW_LoadAnimFile_stream); //DetourAttach(&(PVOID&)OLD_LoadPedAnimIFPFile, NEW_LoadPedAnimIFPFile); DetourTransactionCommit(); } DWORD WINAPI Main_thread(LPVOID lpParam) { if (AllocConsole()) { freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } PrepareOutputStreams(); /* ofs << "GetNumAnimations = " << GetNumAnimations() << std::endl << std::endl; ofs << "GetNumAnimBlocks = " << GetNumAnimBlocks() << std::endl << std::endl; */ HookFunctions(); printf("calling LoadIFPFile now\n"); //LoadIFPFile("C:\\Users\\danish\\Desktop\\gtaTxdDff\\ped.ifp"); // ANP3 GTA SA //LoadIFPFile ("C:\\Program Files (x86)\\Rockstar Games\\GTA3\\anim\\ped.ifp"); // ANPK GTA 3 LoadIFPFile ("C:\\Program Files (x86)\\Rockstar Games\\GTA Vice City\\ped.ifp"); // ANPK GTA VC ofs << "finished calling LoadIFPFile " << std::endl; printf("finished calling LoadIFPFile\n"); clock_t OnePressTMR = clock(); while (1) { if (clock() - OnePressTMR > 400) { if (isKeyPressed('6') && (clock() - OnePressTMR > 1000)) { OnePressTMR = clock(); printf("calling LoadIFPFile now\n"); LoadIFPFile("C:\\Users\\danish\\Desktop\\gtaTxdDff\\ped.ifp"); ofs << "finished calling LoadIFPFile " << std::endl; printf("finished calling LoadIFPFile\n"); clock_t OnePressTMR = clock(); } if (isKeyPressed('0')) { OnePressTMR = clock(); printAnimBlocks(); // Print the hierarchies information to file printHierarchies(); } if (isKeyPressed('5')) { OnePressTMR = clock(); ofs << std::endl << "Pressed Key '5'" << std::endl << std::endl; g_bAllowToPlayCustomAnimation = true; } } } // delete pBlock; return S_OK; } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: { CreateThread(0, NULL, &Main_thread, 0, 0, NULL); break; } case DLL_PROCESS_DETACH: { break; } case DLL_THREAD_ATTACH: { break; } case DLL_THREAD_DETACH: { break; } } /* Return TRUE on success, FALSE on failure */ return TRUE; } inline bool isKeyPressed(unsigned int keyCode) { return (GetKeyState(keyCode) & 0x8000) != 0; }
#ifndef DIALOGCREATEPOINT_H_ #define DIALOGCREATEPOINT_H_ #include "geoDialogBase.h" namespace Ui { class CreatePoint; } namespace GeometryWidget { class GeoPointWidget; class GEOMETRYWIDGETSAPI CreatePointDialog : public GeoDialogBase { Q_OBJECT public: CreatePointDialog(GUI::MainWindow* m, MainWidget::PreWindow* p); CreatePointDialog(GUI::MainWindow* m, MainWidget::PreWindow* p,Geometry::GeometrySet* set); ~CreatePointDialog(); private: void init(); // void closeEvent(QCloseEvent *); void reject() override; void accept() override; bool getPara(double* p); private: Ui::CreatePoint* _ui{}; GeoPointWidget* _pw{}; }; } #endif
#include "Config.hpp" #include "ConfigImpl.hpp" #include <memory> namespace engine { Config& Config::GetInstance() { static ConfigImpl config; return config; } } // namespace engine
#ifndef RESOURCESSYSTEM_H_ #define RESOURCESSYSTEM_H_ #include"../Defs.h" #include "../Game loaders/model.h" class PhysicsSystem; class ResourcesSystem { friend class Scene; friend class RenderingSystem; friend class MovementSystem; Model** models; Shader* ModelShader; Shader* lightingShader; public: ResourcesSystem(PhysicsSystem* physicsSystem); ~ResourcesSystem(); }; #endif /* RESOURCESSYSTEM_H_ */
#include "stdafx.h" #include "RestCommand.h" RestCommand::RestCommand() { } RestCommand::~RestCommand() { } void RestCommand::Run(list<string>* parameters, Game * game) { Player* p = game->getPlayer(); if (p->getCurrentHealth() < p->getTotalHealth()) { int chance = 20; int randomEnemy = rnd.generateInt(0, 100); int restAmount = 20 + (2 * p->getLevel()); if (chance > randomEnemy) { Enemy* enemy = new Enemy(); enemy->setIsAlive(true); enemy->setName("Goblin"); enemy->setAttack(25 * game->getLevel()->getFloor()); enemy->setDefence(10 * game->getLevel()->getFloor()); enemy->setHealth(100 * game->getLevel()->getFloor()); //delete p->getCurrentRoom()->getEnemy(); p->getCurrentRoom()->setEnemy(enemy); p->setCurrentHealth(p->getCurrentHealth() + (restAmount / 2)); std::cout << "Halfway your rest you got interrupted by an enemy!" << endl; } else { p->setCurrentHealth(p->getCurrentHealth() + restAmount); std::cout << "After a little rest your hero feels a bit better without being found." << endl; } } else { std::cout << "Your hero doesn't need to rest." << endl; } }
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <cstring> #include <queue> #include <sstream> #include <cmath> #include <unordered_set> using namespace std; struct UndirectedGraphNode { int label; vector<struct UndirectedGraphNode *> neighbors; UndirectedGraphNode(int x) : label(x) {} }; class Path { public: bool helper(UndirectedGraphNode* a, UndirectedGraphNode* b){ queue<UndirectedGraphNode* > q; unordered_set<UndirectedGraphNode* > s; q.push(a); s.insert(a); while(!q.empty()){ UndirectedGraphNode* t = q.front(); if(t == b) return true; q.pop(); for(int i = 0; i < t->neighbors.size(); ++i){ if(t->neighbors[i] && s.find(t->neighbors[i]) == s.end()){ q.push(t->neighbors[i]); s.insert(t->neighbors[i]); } } } return false; } bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) { if(a == NULL || b == NULL) return false; return helper(a, b) || helper(b, a); } }; int main(){ return 0; }
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。 // inv_link6逆解函数 pose_initial_goal 插补函数 #include <math.h> #include "stdafx.h" #include <iostream> #include <Eigen/Dense> #include<ctime> #include<vector> #include"interpolation_quater.h" #include "IK_group.h" //#include"RRT.h" using namespace Eigen; using namespace std; Eigen::MatrixXd pinv_eigen_based(Eigen::MatrixXd & origin, const float er = 0) { // 进行svd分解 Eigen::JacobiSVD<Eigen::MatrixXd> svd_holder(origin, Eigen::ComputeThinU | Eigen::ComputeThinV); // 构建SVD分解结果 Eigen::MatrixXd U = svd_holder.matrixU(); Eigen::MatrixXd V = svd_holder.matrixV(); Eigen::MatrixXd D = svd_holder.singularValues(); // 构建S矩阵 Eigen::MatrixXd S(V.cols(), U.cols()); S.setZero(); for (unsigned int i = 0; i < D.size(); ++i) { if (D(i, 0) > er) { S(i, i) = 1 / D(i, 0); } else { S(i, i) = 0; } } // pinv_matrix = V * S * U^T return V * S * U.transpose(); } struct DH { float alpha1; float a1; float theta1; float d1; float alpha2; float a2; float theta2; float d2; float alpha3; float a3; float theta3; float d3; float alpha4; float a4; float theta4; float d4; float alpha5; float a5; float theta5; float d5; float alpha6; float a6; float theta6; float d6; }; struct Position //位置+欧拉角 { float x; float y; float z; float Euler_z; float Euler_y; float Euler_x; float Quaternion[4]; }; struct joint //六个关节角度 { float joint1; float joint2; float joint3; float joint4; float joint5; float joint6; }; Matrix<double, 4, 4> QuaternionToRot(double q[4]) //四元数转换旋转矩阵 { MatrixXd R(4, 4); R(0, 0) = q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]; R(0, 1) = 2.0*(q[1] * q[2] - q[0] * q[3]); R(0, 2) = 2.0*(q[0] * q[2] + q[1] * q[3]); R(0, 3) = 0; R(1, 0) = 2.0*(q[0] * q[3] + q[1] * q[2]); R(1, 1) = q[0] * q[0] - q[1] * q[1] + q[2] * q[2] - q[3] * q[3]; R(1, 2) = 2.0*(q[2] * q[3] - q[0] * q[1]); R(1, 3) = 0; R(2, 0) = 2.0*(q[1] * q[3] - q[0] * q[2]); R(2, 1) = 2.0*(q[0] * q[1] + q[2] * q[3]); R(2, 2) = q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]; R(2, 3) = 0; R(3, 0) = 0; R(3, 1) = 0; R(3, 2) = 0; R(3, 3) = 1; return R; } struct Quaternion1 { float x; float y; float z; float w; }; struct rotMatrix { float m11, m12, m13; float m21, m22, m23; float m31, m32, m33; }; //fuction:旋转矩阵到四元数的转换 void rotMatrixToQuternion(Quaternion1 &q, rotMatrix &r) { float tr = r.m11 + r.m22 + r.m33; float temp = 0.0; if (tr > 0.0) { temp = 0.5f / sqrtf(tr + 1); q.w = 0.25f / temp; q.x = (r.m23 - r.m32) * temp; q.y = (r.m31 - r.m13) * temp; q.z = (r.m12 - r.m21) * temp; } else { if (r.m11 > r.m22 && r.m11 > r.m33) { temp = 2.0f * sqrtf(1.0f + r.m11 - r.m22 - r.m33); q.w = (r.m32 - r.m23) / temp; q.x = 0.25f * temp; q.y = (r.m12 + r.m21) / temp; q.z = (r.m13 + r.m31) / temp; } else if (r.m22 > r.m33) { temp = 2.0f * sqrtf(1.0f + r.m22 - r.m11 - r.m33); q.w = (r.m13 - r.m31) / temp; q.x = (r.m12 + r.m21) / temp; q.y = 0.25f * temp; q.z = (r.m23 + r.m32) / temp; } else { temp = 2.0f * sqrtf(1.0f + r.m33 - r.m11 - r.m22); q.w = (r.m21 - r.m12) / temp; q.x = (r.m13 + r.m31) / temp; q.y = (r.m23 + r.m32) / temp; q.z = 0.25f * temp; } } } void rotToQuaternion1(double R[3][3], double q[4]) { float tr = R[0][0] + R[1][1] + R[2][2]; float temp = 0.0; if (tr > 0.0) { temp = 0.5f / sqrtf(tr + 1); q[0] = 0.25f / temp; q[1] = (R[2][1] - R[1][2]) * temp; q[2] = (R[0][2] - R[2][0]) * temp; q[3] = (R[1][0] - R[0][1]) * temp; } else { if (R[0][0] > R[1][1] && R[0][0] > R[2][2]) { temp = 2.0f * sqrtf(1.0f + R[0][0] - R[1][1] - R[2][2]); q[0] = (R[2][1] - R[1][2]) / temp; q[1] = 0.25f * temp; q[2] = (R[0][1] + R[1][0]) / temp; q[3] = (R[0][2] + R[2][0]) / temp; } else if (R[1][1] >R[2][2]) { temp = 2.0f * sqrtf(1.0f + R[1][1] - R[0][0] - R[2][2]); q[0] = (R[0][2] - R[2][0]) / temp; q[1] = (R[0][1] + R[1][0]) / temp; q[2] = 0.25f * temp; q[3] = (R[1][2] + R[2][1]) / temp; } else { temp = 2.0f * sqrtf(1.0f + R[2][2] - R[0][0] - R[1][1]); q[0] = (R[1][0] - R[0][1]) / temp; q[1] = (R[0][2] + R[2][0]) / temp; q[2] = (R[1][2] + R[2][1]) / temp; q[3] = 0.25f * temp; } } } int main() { struct DH dh2;//定义工业机器人(带球形腕关节)的dh表参数,d-h表的参数定义并不一定相同,实际使用中,需要调整d-h参数匹配该逆解。关节的旋转参考如下矩阵 dh2.theta1 = 0; dh2.d1 = 495; dh2.a1 = 175; dh2.alpha1 = 3.1415 / 2; dh2.theta2 = 0; dh2.d2 = 0; dh2.a2 = 900; dh2.alpha2 = 0; dh2.theta3 = 0; dh2.d3 = 175; dh2.a3 = 960; dh2.alpha3 = 3.1415 / 2; dh2.theta4 = 0; dh2.d4 = 0; dh2.a4 = 0; dh2.alpha4 = -3.1415 / 2; dh2.theta5 = 0; dh2.d5 = 0; dh2.a5 = 0; dh2.alpha5 = 3.1415 / 2; dh2.theta6 = 0; dh2.d6 = 135; dh2.a6 = 0; dh2.alpha6 = 0; ////dh表参数定义 Position pose_initial; //position pose_goal; float *vec_angles; int me[3] = { 0,0,0 }; Position pose1; pose_initial.x = 806.29; pose_initial.y = 0; pose_initial.z = 1154; pose_initial.Euler_z = 3.1415; pose_initial.Euler_y = 1.0472; pose_initial.Euler_x = 3.1415; ////起始位置//位置+欧拉角(弧度) ////起始位置// //float rx; //float ry; //double q[4]; //q[0] = 0.5; //q[1] = 0; //q[2] = 0.866; //q[3] = 0; //double p[3]; ////rx= 2.0*(q[1] * q[3] - q[0] * q[2]); //ry= 2.0*(q[0] * q[1] + q[2] * q[3]); ////quat2euler(q, p); ////cout << p[0] << endl; ////cout << p[1] << endl; ////cout << p[2] << endl; ////cout << rx << endl; ////cout << ry << endl; ////目标位置// //pose_goal.x =1019.61; //pose_goal.y = 0; //pose_goal.z = 1217.5; //pose_goal.euler_z =3.1415; //pose_goal.euler_y = 1.0472; //pose_goal.euler_x = 3.1415; //pose_goal.quaternion[0] = q[0]; //pose_goal.quaternion[1] = q[1]; //pose_goal.quaternion[2] = q[2]; //pose_goal.quaternion[3] = q[3]; ////目标位置// //joint joint_6link;//路径关节点 //joint joint_initial;//初始关节点 //joint joint_goal;//目标关节点 //vector<joint> joint_path;//测试直线插值后的求逆的解 //vector<joint> joint_path2;//测试关节插值 //vector<joint> joint_path3;//测试直线插值 // int me[3] = {0,0,0};//轴1,3,4的正反向,机器人形态的控制参数 // int issolved; ////rotationstatus choose; //double omg[3] = {0,1,0}; //double theta = 0; double q1[4]= { 0.3705 , -0.0118076 , -0.917115930 , 0.050726}; //AxisAngToQuaternion1(omg, theta, q1); double R[3][3]; MatrixXd R1(4, 4); R1=QuaternionToRot(q1); cout << R1 << endl; //std::cout << QuaternionToRot(q1) << endl; /*R[0][0] = R1(0, 0); R[0][1] = R1(0, 1); R[0][2] = R1(0, 2); R[1][0] = R1(1, 0); R[1][1] = R1(1, 1); R[1][2] = R1(1, 2); R[2][0] = R1(2, 0); R[2][1] = R1(2, 1); R[2][2] = R1(2, 2);*/ R[0][0] =0.567; R[0][1] = 0.8157; R[0][2] = 0.115; R[1][0] = 0.8015; R[1][1] = -0.5785; R[1][2] = 0.1513; R[2][0] = 0.1899; R[2][1] = 0.0064; R[2][2] = -0.9818; rotMatrix r1; Quaternion1 q2; r1.m11 = 0.7358; r1.m12 = 0.5651; r1.m13 = -0.373; r1.m21 = 0.3738; r1.m22 = 0.12; r1.m23 = 0.9197; r1.m31 = 0.5646; r1.m32 = -0.8162; r1.m33 = -0.1227; rotMatrixToQuternion(q2, r1); RotToQuaternion(R, q1); //cout << q1[0] << "::" << q1[1] << "::" << q1[2] << "::" << q1[3] << endl; cout << q2.w << "::" << q2.x << "::" << q2.y << "::" << q2.z << endl; rotToQuaternion1(R, q1); cout << q1[0] << "::R::" << q1[1] << "::" << q1[2] << "::" << q1[3] << endl; //q1[0] = q2.w; //q1[1] = q2.x; //q1[2] = q2.y; //q1[3] = q2.z; q1[1] = -q1[1]; q1[2] = -q1[2]; q1[3] = -q1[3]; R1 = QuaternionToRot(q1); cout << R1 << endl; //joint_path=pose_initial_goal(pose_initial, pose_goal, 1000,ME,dh1,RZYX);//姿态插补程序,输入初始姿态结构体,输入目标姿态结构体,输入插补个数 ME=姿态选择,dh1=DH表,RZYX=欧拉角旋转顺序 clock_t startTime = clock(); clock_t endTime = clock(); Eigen::MatrixXd M(4, 3) ; M << 1, 0, 1, 0, 1, 2, 2, 3, 4, 5, 6, 7; cout << M << endl; cout << "M::" << pinv_eigen_based(M) << endl; //cout << "整个程序用时:" << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; system("pause"); return 0; }
#include<iostream> #include<cmath> double deg_func(int n, int k) { double res = 0; for(int i = 1; i <= n; ++i) { res += pow(i, k); } return res; } int main() { int n; int k; std :: cin >> n; std :: cin >> k; std :: cout << '\n' << deg_func(n, k); }
#include <gtest/gtest.h> #include <vector> #include <deus/unicode_view_impl/EncodingImpl.hpp> //------------------------------------------------------------------------------ // FIXTURE //------------------------------------------------------------------------------ class ASCIIFindTest : public ::testing::Test { protected: //---------------------------------STRUCTS---------------------------------- struct TestData { deus::UnicodeStorage a; deus::UnicodeStorage b; std::size_t position; std::size_t expected; TestData(const char* a_, const char* b_) : a (a_, deus::Encoding::kASCII) , b (b_, deus::Encoding::kASCII) , position(0) { expected = a.get_string().find(b.get_string()); } TestData(const char* a_, const char* b_, std::size_t position_) : a (a_, deus::Encoding::kASCII) , b (b_, deus::Encoding::kASCII) , position(position_) { expected = a.get_string().find(b.get_string(), position); } }; //--------------------------------ATTRIBUTES-------------------------------- std::vector<TestData> test_data; //--------------------------------FUNCTIONS--------------------------------- virtual void SetUp() { test_data = { // TestData("", ""), // TestData("a", ""), // TestData("Hello world!", ""), // TestData("a", "a"), // TestData("aaaaaaa", "a"), // TestData("Hello world!", "Hello"), // TestData("Hello world!", "wolrd!"), // TestData("Hello world!", "lo wo!"), // TestData("Hello world!", "hello"), // TestData( // "This string is quite a bit longer and contains the subject " // "string more than once", // "string" // ), // TestData( // "This string is quite a bit longer and but does not contain " // "the subject string", // "and\t" // ), // TestData( // "This string contains the subject right near the end of the " // "string, and the subject is a single character: \'x\'.", // "x" // ), TestData("", "", 0), // TestData("", "", 1), // TestData("a", "a", 0), // TestData("a", "a", 1), // TestData("aaaaaaa", "a", 3), // TestData("aaaaaaa", "a", 6), // TestData("Hello world!", "Hello", 1), // TestData("Hello world!", "wolrd!", 5), // TestData( // "This string is quite a bit longer and contains the subject " // "string more than once", // "string", // 26 // ), // TestData( // "This string is quite a bit longer and but does not contain " // "the subject string", // "and\t", // 13 // ), // TestData( // "This string contains the subject right near the end of the " // "string, and the subject is a single character: \'x\'.", // "x", // 32 // ) }; } }; //------------------------------------------------------------------------------ // TESTS //------------------------------------------------------------------------------ TEST_F(ASCIIFindTest, naive) { for(const TestData& data : test_data) { std::size_t result = deus::generic_inl::find_naive( data.a.get_view(), data.b.get_view(), data.position ); EXPECT_EQ(result, data.expected) << "Incorrect result when searching \"" << data.a.get_string() << "\" for \"" << data.b.get_string() << "\" from position: " << data.position; } }
#ifndef SHS2605_AUTONOMOUSBEHAVIOR_H #define SHS2605_AUTONOMOUSBEHAVIOR_H #include <Behaviors/IBehavior.h> #include <Actions/ActionController.h> #include <Hardware/Drive/MecanumDriveTrain.h> #include <Hardware/Drive/IQuadRectangularDriveBase.h> #include <Sensing/IAngularInput.h> #include "AutonomousActions/TurnAction.h" #include "AutonomousActions/DriveAction.h" #include "AutonomousActions/WinchPositionAction.h" #include "AutonomousActions/BallastPositionAction.h" #include "AutonomousActions/WaitAction.h" #define AUTOBEHAVIOR_BID "autonomous" class AutonomousBehavior : public IBehavior { public: AutonomousBehavior ( MecanumDriveTrain * Drive, LinearSlide * Winch, LinearSlide * Ballast, IAngularInput * RobotYaw, double MotorSpeed, IQuadRectangularDriveBase * DriveBase ); ~AutonomousBehavior (); void Init ( BehaviorController * Controller, const char * AppliedID ); void Destroy (); void Start (); void Stop (); void Update (); static const char * GetDefaultBehaviorID (); private: MecanumDriveTrain * Drive; LinearSlide * Winch; LinearSlide * Ballast; double MotorSpeed; IQuadRectangularDriveBase * DriveBase; DriveAction Drive1; WinchPositionAction WinchPos1; WaitAction Wait1; TurnAction Turn1; DriveAction Drive2; WinchPositionAction WinchPos2; BallastPositionAction BallastPos1; BallastPositionAction BallastPos2; ActionController Actions; }; #endif
#include<stdio.h> int main() { char zimu; for (zimu = 'a'; zimu <= 'z'; zimu++) printf("%3d\n", zimu); }
#pragma once #include <boostGraphCFG.h> #include "rose.h" #include <vector> #include <set> #include <map> #include <iterator> #include <boost/foreach.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/topological_sort.hpp> namespace ssa_private { using namespace std; using namespace boost; /** Given the dominance frontiers of each node and a set of start nodes, calculate the iterated dominance frontier * of the start nodes. */ template<class CfgNodeT> set<CfgNodeT> calculateIteratedDominanceFrontier(const map<CfgNodeT, set<CfgNodeT> >& dominanceFrontiers, const vector<CfgNodeT>& startNodes) { set<CfgNodeT> result; set<CfgNodeT> visitedNodes; vector<CfgNodeT> worklist; worklist.insert(worklist.end(), startNodes.begin(), startNodes.end()); while (!worklist.empty()) { CfgNodeT currentNode = worklist.back(); worklist.pop_back(); visitedNodes.insert(currentNode); //Get the dominance frontier of the node and add it to the results ROSE_ASSERT(dominanceFrontiers.count(currentNode) != 0); const set<CfgNodeT>& dominanceFrontier = dominanceFrontiers.find(currentNode)->second; //Add all the children to the result and to the worklist BOOST_FOREACH(CfgNodeT dfNode, dominanceFrontier) { if (visitedNodes.count(dfNode) > 0) continue; result.insert(dfNode); worklist.push_back(dfNode); } } return result; } /** Calculates the dominance frontier for each node in the control flow graph of the given function. * @param iDominatorMap map from each node to its immediate dominator * @param iPostDominatorMap map from each node to its immediate postdominator */ template<class CfgNodeT, class CfgEdgeT> map<CfgNodeT, set<CfgNodeT> > calculateDominanceFrontiers(SgFunctionDefinition* func, map<CfgNodeT, CfgNodeT>* iDominatorMap, map<CfgNodeT, CfgNodeT>* iPostDominatorMap) { typedef CFG<CfgNodeT, CfgEdgeT> ControlFlowGraph; //Build a CFG first ControlFlowGraph functionCfg(func); //Build the dominator tree typename ControlFlowGraph::VertexVertexMap dominatorTreeMap = functionCfg.getDominatorTree(); //TODO: This code converts a VertexVertex Map to a boost graph. Should be factored out typedef adjacency_list<vecS, vecS, bidirectionalS, CfgNodeT> TreeType; TreeType domTree; typedef typename graph_traits<TreeType>::vertex_descriptor TreeVertex; set<CfgNodeT> addedNodes; map<CfgNodeT, TreeVertex> cfgNodeToVertex; BOOST_FOREACH(typename ControlFlowGraph::VertexVertexMap::value_type& nodeDominatorPair, dominatorTreeMap) { CfgNodeT node = *functionCfg[nodeDominatorPair.first]; CfgNodeT dominator = *functionCfg[nodeDominatorPair.second]; if (addedNodes.count(dominator) == 0) { TreeVertex newVertex = add_vertex(domTree); cfgNodeToVertex[dominator] = newVertex; domTree[newVertex] = dominator; addedNodes.insert(dominator); } if (addedNodes.count(node) == 0) { TreeVertex newVertex = add_vertex(domTree); cfgNodeToVertex[node] = newVertex; domTree[newVertex] = node; addedNodes.insert(node); } //Add the edge from dominator to node add_edge(cfgNodeToVertex[dominator], cfgNodeToVertex[node], domTree); if (iDominatorMap != NULL) { ROSE_ASSERT(iDominatorMap->count(node) == 0); iDominatorMap->insert(make_pair(node, dominator)); } } //Get a topological ordering of the vertices vector<TreeVertex> reverseTopological; topological_sort(domTree, back_inserter(reverseTopological)); //Calculate all the dominance frontiers. This algorithm is from figure 10, Cytron et. al 1991 map<CfgNodeT, set<CfgNodeT> > dominanceFrontiers; BOOST_FOREACH(TreeVertex v, reverseTopological) { CfgNodeT currentNode = domTree[v]; set<CfgNodeT>& currentDominanceFrontier = dominanceFrontiers[currentNode]; //Local contribution: Iterate over all the successors of v in the control flow graph BOOST_FOREACH(CfgEdgeT outEdge, currentNode.outEdges()) { CfgNodeT successor = outEdge.target(); //Get the immediate dominator of the successor typename ControlFlowGraph::Vertex successorVertex = functionCfg.getVertexForNode(successor); #if !USE_ROSE // DQ (11/3/2011): EDG compilains about this (but GNU allowed it, I think that EDG might be correct. // since it might be a private variable. But since we are only trying to compile ROSE with ROSE (using the // new EDG 4.3 front-end as a tests) we can just skip this case for now. ROSE_ASSERT(successorVertex != ControlFlowGraph::GraphTraits::null_vertex()); #endif ROSE_ASSERT(dominatorTreeMap.count(successorVertex) == 1); typename ControlFlowGraph::Vertex iDominatorVertex = dominatorTreeMap[successorVertex]; CfgNodeT iDominator = *functionCfg[iDominatorVertex]; //If we have a successor that we don't dominate, that successor is in our dominance frontier if (iDominator != currentNode) { currentDominanceFrontier.insert(successor); } } //"Up" contribution. Iterate over all children in the dominator tree typename graph_traits<TreeType>::adjacency_iterator currentIter, lastIter; for (tie(currentIter, lastIter) = adjacent_vertices(v, domTree); currentIter != lastIter; currentIter++) { CfgNodeT childNode = domTree[*currentIter]; const set<CfgNodeT>& childDominanceFrontier = dominanceFrontiers[childNode]; BOOST_FOREACH(CfgNodeT childDFNode, childDominanceFrontier) { //Get the immediate dominator of the child DF node typename ControlFlowGraph::Vertex childDFVertex = functionCfg.getVertexForNode(childDFNode); #if !USE_ROSE // DQ (11/3/2011): EDG compilains about this (but GNU allowed it, I think that EDG might be correct. // since it might be a private variable. But since we are only trying to compile ROSE with ROSE (using the // new EDG 4.3 front-end as a tests) we can just skip this case for now. ROSE_ASSERT(childDFVertex != ControlFlowGraph::GraphTraits::null_vertex()); #endif ROSE_ASSERT(dominatorTreeMap.count(childDFVertex) == 1); typename ControlFlowGraph::Vertex iDominatorVertex = dominatorTreeMap[childDFVertex]; CfgNodeT iDominator = *functionCfg[iDominatorVertex]; if (iDominator != currentNode) { currentDominanceFrontier.insert(childDFNode); } } } } //While we're at it, calculate the postdominator tree if (iPostDominatorMap != NULL) { typename ControlFlowGraph::VertexVertexMap postDominatorTreeMap = functionCfg.getPostdominatorTree(); BOOST_FOREACH(typename ControlFlowGraph::VertexVertexMap::value_type& nodePostDominatorPair, postDominatorTreeMap) { CfgNodeT node = *functionCfg[nodePostDominatorPair.first]; CfgNodeT postDominator = *functionCfg[nodePostDominatorPair.second]; ROSE_ASSERT(iPostDominatorMap->count(node) == 0); iPostDominatorMap->insert(make_pair(node, postDominator)); } } return dominanceFrontiers; } }
#pragma once #include <iostream> #include "Customer.h" #include "Video.h" using namespace std; class Link { public: void SettingHead(Customer* cHead,Video *vHead); };
// // Copyright Jason Rice 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_WEBSOCKET_DETAIL_MESSAGE_SENDER_HPP #define NBDL_WEBSOCKET_DETAIL_MESSAGE_SENDER_HPP #include <nbdl/promise.hpp> #include <algorithm> #include <boost/asio.hpp> #include <boost/hana/integral_constant.hpp> #include <iterator> namespace nbdl::websocket::detail { namespace asio = boost::asio; using asio::ip::tcp; namespace hana = boost::hana; using namespace std::string_view_literals; using std::string_view; enum class opcode_kind : unsigned char { continuation = 0x0 , text = 0x1 , binary = 0x2 , close = 0x8 , ping = 0x9 , pong = 0xA }; template <typename Payload> struct message_data; template <typename Payload, typename MaxFrameSize = hana::size_t<125>> struct message_sender { static constexpr std::size_t max_frame_size = MaxFrameSize::value; message_sender(tcp::socket& s) : socket(s) , data() { } template <typename Handler> void send_frame_impl(asio::const_buffer, Handler&&); template <typename Resolver, typename Begin, typename End> void send_message_impl(Resolver&, Begin, End); void set_opcode(unsigned char x) { data.header_byte = x; } Payload& payload() { return data.payload; } tcp::socket& socket; detail::message_data<Payload> data; }; template <typename Payload> struct message_data { void apply_fin_bit() { header_byte |= (1 << 7); } void apply_mask_bit(std::size_t) { // Masks are required for client-to-server frames. // Having the server require it is silly because // anyone can provide any mask they want to. // This implementation relaxes that requirement. } asio::const_buffer encoded_length_buffer(std::size_t); unsigned char header_byte; std::array<unsigned char, 9> length_data; Payload payload; }; template <typename Payload> asio::const_buffer message_data<Payload>::encoded_length_buffer(std::size_t length) { if (length < 126) { length_data[0] = length; return asio::const_buffer(static_cast<void const*>(length_data.data()), 1); } else if (length < 65536) { // 16 bit + 1 byte length_data[0] = 126; length_data[1] = length >> 8; length_data[2] = length; return asio::const_buffer(static_cast<void const*>(length_data.data()), 3); } else { // 64 bit + 1 byte length_data[0] = 127; length_data[1] = length >> 56; length_data[2] = length >> 48; length_data[3] = length >> 40; length_data[4] = length >> 32; length_data[5] = length >> 24; length_data[6] = length >> 16; length_data[7] = length >> 8; length_data[8] = length; return asio::const_buffer(static_cast<void const*>(length_data.data()), 9); } }; template <typename Payload, typename MaxFrameSize> template <typename Handler> void message_sender<Payload, MaxFrameSize>:: send_frame_impl( asio::const_buffer frame_payload_buffer , Handler&& handler ) { asio::async_write( socket , std::array<asio::const_buffer, 3>{{ asio::buffer(static_cast<void const*>(&data.header_byte), 1) , data.encoded_length_buffer(frame_payload_buffer.size()) , frame_payload_buffer }} , std::forward<Handler>(handler) ); } template <typename Payload, typename MaxFrameSize> template <typename Resolver, typename PayloadBegin, typename PayloadEnd> void message_sender<Payload, MaxFrameSize>:: send_message_impl(Resolver& resolver, PayloadBegin begin, PayloadEnd end) { auto frag_end = std::next(begin, MaxFrameSize::value); if (frag_end > end) { frag_end = end; data.apply_fin_bit(); } auto frame_payload_buffer = asio::buffer( static_cast<void const*>(&(*begin)) , std::distance(begin, frag_end) ); send_frame_impl( frame_payload_buffer , [new_begin = frag_end, end, &resolver, this](std::error_code error_code, std::size_t) { if (error_code) { resolver.reject(error_code); } else if (new_begin == end) { resolver.resolve(*this); } else { set_opcode(static_cast<unsigned char>(opcode_kind::continuation)); // generate_mask(); send_message_impl(resolver, new_begin, end); } } ); } template <unsigned char opcode> struct send_impl_fn { template <typename Resolver, typename MessageSender> void operator()(Resolver& resolver, MessageSender& sender) const { sender.set_opcode(opcode); sender.send_message_impl( resolver , sender.data.payload.begin() , sender.data.payload.end() ); } }; template <unsigned char opcode> constexpr auto send_impl = send_impl_fn<opcode>{}; constexpr auto send_text = detail::send_impl< static_cast<unsigned char>(opcode_kind::text) >; constexpr auto send_binary = detail::send_impl< static_cast<unsigned char>(opcode_kind::binary)>; constexpr auto send_close = detail::send_impl< static_cast<unsigned char>(opcode_kind::close) >; constexpr auto send_ping = detail::send_impl< static_cast<unsigned char>(opcode_kind::ping) >; constexpr auto send_pong = detail::send_impl< static_cast<unsigned char>(opcode_kind::pong) >; } #endif
/* * Copyright (C) 2018-2019 wuuhii. All rights reserved. * * The file is encoding with utf-8 (with BOM). It is a part of QtSwissArmyKnife * project. The project is a open source project, you can get the source from: * https://github.com/wuuhii/QtSwissArmyKnife * https://gitee.com/wuuhii/QtSwissArmyKnife * * If you want to know more about the project, please join our QQ group(952218522). * In addition, the email address of the project author is wuuhii@outlook.com. */ #include "SAKGlobal.hh" #include "SAKSettings.hh" #include <QApplication> SAKSettings* SAKSettings::_instance = nullptr; SAKSettings* SAKSettings::instance() { if (!_instance){ const QString fileName = QString("%1/%2.ini").arg(SAKGlobal::dataPath()).arg(qApp->applicationName()); new SAKSettings(fileName, QSettings::IniFormat, qApp); } return _instance; } SAKSettings::SAKSettings(const QString &fileName, Format format, QObject *parent) :QSettings(fileName, format, parent) { _instance = this; settingStringEnableAutoUpdate = QString("Universal/enableAutoCheckForUpdate"); } SAKSettings::~SAKSettings() { _instance = nullptr; } bool SAKSettings::enableAutoCheckForUpdate() { bool enable = value(settingStringEnableAutoUpdate).toBool(); return enable; } void SAKSettings::setEnableAutoCheckForUpdate(bool enable) { setValue(settingStringEnableAutoUpdate, enable); }
#include "ofApp.h" // for time stamps #include <ctime> using namespace ofxCv; using namespace cv; void ofApp::setup() { // init shaders //shader.load("shadersES2/mix-shader"); #ifdef TARGET_OPENGLES shader.load("shadersES2/mix-shader"); #else if (ofIsGLProgrammableRenderer()) { shader.load("shadersGL3/mix-shader"); } else { shader.load("shadersGL2/mix-shader"); } #endif // signal handler for clean exit image.loadImage("img.jpg"); // load config file config.loadFile("config.xml"); int frameRate; if (config.tagExists("config:frameRate", 0)) { frameRate = config.getValue("config:frameRate", 30); cout << "\nframe rate from config file" << frameRate << "\n"; } else { cout << "\nerror reading frameRate from xml config file\n"; cout << "\nframe rate from config file" << frameRate << "\n"; } double smoothingRate; if (config.tagExists("config:smoothingRate", 0)) { smoothingRate = config.getValue("config:smoothingRate", 0.2); cout << "smoothing rate from config file: " << smoothingRate << "\n"; } else { cout << "error reading smoothingRate from xml config file\n"; smoothingRate = 0.2; } int cannyPruning; if (config.tagExists("config:cannyPruning", 0)) { cannyPruning = config.getValue("config:cannyPruning", 0); } else { cout << "error reading cannyPruning from xml config file\n"; cannyPruning = 1; } if (config.tagExists("config:face_dropped_threshold")) { face_dropped_threshold = config.getValue("config:face_dropped_threshold", FACE_DROPPED_THRESHOLD); } else { cout << "error reading face_dropped_threshold from xml config file\n"; face_dropped_threshold = FACE_DROPPED_THRESHOLD; } if (config.tagExists("config:nod_threshold")) { nod_threshold = config.getValue("config:nod_threshold", NOD_THRESHOLD); } else { cout << "error reading nod_threshold from xml config file\n"; nod_threshold = NOD_THRESHOLD; } if (config.tagExists("config:num_images")) { num_images = config.getValue("config:num_images", NUM_IMAGES); cout << "num_images from config file: " << num_images << "\n"; } else { cout << "error reading num_images from xml config file\n"; num_images = NUM_IMAGES; } #ifdef RPI if (signal(SIGUSR1, clean_exit) == SIG_ERR) { cout << "can't catch signal\n"; } #endif ofSetVerticalSync(true); ofSetFrameRate(frameRate); // smaller = smoother //finder.getTracker().setSmoothingRate(smoothingRate); // ignore low-contrast regions finder.setCannyPruning((cannyPruning > 0)); finder.setup("haarcascade_frontalface_default.xml"); finder.setPreset(ObjectFinder::Fast); finder.setFindBiggestObject(true); finder.getTracker().setSmoothingRate(smoothingRate); //cam.listDevices(); cam.setDeviceID(0); cam.setup(CAM_WIDTH, CAM_HEIGHT); ofEnableAlphaBlending(); id = 0; grabimg.allocate(CAM_WIDTH, CAM_HEIGHT, OF_IMAGE_COLOR); colorimg.allocate(CAM_WIDTH, CAM_HEIGHT); grayimg.allocate(CAM_WIDTH, CAM_HEIGHT); // something to display if facefinder doesn't grayimg.set(127.0); // state machine handling state.set(S_IDLE, 0); // allocate array of images for (int i = 0; i < num_images; i++) { gray_images.push_back(ofImage()); gray_rects.push_back(ofRectangle()); } msg.loadFont("impact.ttf", 36, true, false, true, 0.1); facerect = ofRectangle(0, 0, 0, 0); // load stored images init_idle(); // setup shader FBOs //fbo.allocate(SCREEN_WIDTH, SCREEN_HEIGHT); fbo.allocate(image.getWidth(),image.getHeight()); maskFbo.allocate(SCREEN_WIDTH, SCREEN_HEIGHT); } void ofApp::update() { ofVec2f vel; cam.update(); if (cam.isFrameNew()) { grabimg.setFromPixels(cam.getPixels()); colorimg.setFromPixels(grabimg.getPixels()); // convert to grayscale grayimg = colorimg; // do face detection in grayscale finder.update(grayimg); //cropimg = grayimg(cropr); vel.set(0, 0); if (finder.size() > 0) { cv::Vec2f v = finder.getVelocity(0); vel = toOf(v); facerect = finder.getObjectSmoothed(0); // scale by size of camera and face rect to normalize motion vel.x *= 500. / facerect.x; vel.y *= 500. / facerect.y; //cout << "velx:" << setw(6) << setprecision(2) << vel.x; //cout << " vely: " << setw(6) << setprecision(2) << vel.y << "\n"; float mix = 0.3; avg_xvel = mix*abs(vel.x) + 0.9*(1 - mix)*avg_xvel; avg_yvel = mix*abs(vel.y) + 0.9*(1 - mix)*avg_yvel; /* cout << " avg_x:" << fixed << setw(6) << setprecision(1) << avg_xvel; cout << " avg_y: " << fixed << setw(6) << setprecision(1) << avg_yvel << "\n"; if (avg_xvel > 35) cout << "X NO----"; else cout << " "; if (avg_yvel > 25) cout << "Y+YES+++\n"; else cout << " \n"; */ } } // state machine handling switch (state.state) { case S_IDLE: if (false) { //disable for testing //if (finder.size() > 0) { // found face, so go to capture mode // check for face size here if (state.timeout() && (facerect.width*xscale > ofGetWidth() / 5.0)) { state.set(S_HELLO, 2.); // grab image when first detected } } break; case S_HELLO: /* if (finder.size() == 0) { state.set(S_NO_IMG, 2.); } */ //update_idle(); yes_flag = false; avg_xvel = 0; avg_yvel = 0; if (state.timeout()) { state.set(S_QUESTION, 5); } case S_QUESTION: if (state.timeout()) { // no obvious yes, so default to no state.set(S_NO_IMG, 2.); } if (finder.size() > 0) { if (avg_yvel > nod_threshold) { state.set(S_THREE, 1.); } //if (avg_xvel > 45.0) { // state.set(S_NO_IMG, 2.); // yes_flag = false; //} } break; case S_THREE: if (state.timeout()) { state.set(S_TWO, 1.); } case S_TWO: if (state.timeout()) { state.set(S_ONE, 1.); } case S_ONE: if (state.timeout()) { state.set(S_CAPTURE, 2); } case S_CAPTURE: //if (finder.size() == 0) { // state.set(S_NO_IMG, 2.); //} if (state.timeout()) { state.set(S_YES_IMG, 2); saveimg.setFromPixels(cam.getPixels()); saverect = finder.getObjectSmoothed(0); store_image(); yes_flag = true; } case S_YES_IMG: if (state.timeout()) { state.set(S_IDLE, 10); } break; case S_NO_IMG: if (state.timeout()) { state.set(S_IDLE, 10); } break; } } void ofApp::draw() { fbo.begin(); ofClear(0, 0, 127, 255); shader.begin(); shader.setUniformTexture("tex0", image, 1); //shader.setUniformTexture("tex1", grayimg, 2); //shader.setUniformTexture("tex2", grayimg, 3); //shader.setUniformTexture("tex1", image, 2); //shader.setUniformTexture("tex2", movie.getTextureReference(), 3); //shader.setUniformTexture("imageMask", maskFbo.getTextureReference(), 4); // we are drawing this fbo so it is used just as a frame. maskFbo.draw(0, 0); shader.end(); fbo.end(); fbo.draw(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); fbo.draw(0, 0, 320, 240); image.draw(320, 240, 320, 240); return; ofSetHexColor(0xFFFFFFFF); // disable for testing idle grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); ofNoFill(); ofSetHexColor(0xFFFF00FF); ofDrawRectRounded(facerect.x * xscale, facerect.y*yscale, facerect.width*xscale, facerect.height*yscale, 30.0); float underface_x = facerect.x * xscale; //float underface_y = min(float(facerect.y + facerect.height + 10.), ofGetHeight() - 30.); float underface_y = std::min(float(facerect.getBottom()*yscale + 20.0), float(ofGetHeight() - 30)); switch (state.state) { case S_IDLE: //draw_idle(); draw_idle1(); break; case S_HELLO: msg.drawString("Hello!", 50, 100); break; case S_QUESTION: msg.drawString("Hello!", 50, 100); msg.drawString("May we take your picture?", 50, ofGetHeight() - 150); msg.drawString("(nod yes or no)", 50, ofGetHeight() - 75); break; case S_THREE: msg.drawString("Ready! 3...", underface_x, underface_y); break; case S_TWO: msg.drawString("Ready! 3... 2...", underface_x, underface_y); break; case S_ONE: msg.drawString("Ready! 3... 2... 1...", underface_x, underface_y); break; case S_CAPTURE: msg.drawString("Ready! 3... 2... 1... Pose!", underface_x, underface_y); break; case S_YES_IMG: msg.drawString("Thank you!", underface_x, underface_y); ofSetColor(255, 255, 255, 127); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); break; case S_NO_IMG: msg.drawString("OK, thanks anyway!", 50, ofGetHeight() - 100); break; } } void ofApp::init_idle() { //some path, may be absolute or relative to bin/data cout << "init idle\n"; string path = ""; ofDirectory imgs(path); //only show png files imgs.allowExt("png"); //populate the directory object //imgs.listDir(); imgs.getSorted(); imgs.listDir(); // if (imgs.size() > 0) { // cout << "loading color file " << imgs.getPath(imgs.size() - 1) << "\n"; // idle_image.load(imgs.getFile(imgs.size()-1)); // } int img_count = 0; int num_dir_images = imgs.size(); for (int i = 0; i < std::min(num_images, num_dir_images); i++) { // load most recent images int j = imgs.size() - i - 1; cout << "loading gray file " << imgs.getPath(j) << "\n"; gray_images[i].load(imgs.getFile(j)); gray_images[i].setImageType(OF_IMAGE_GRAYSCALE); img_count++; // parse rectangle out of file name ofRectangle r = gray_rects[i]; unsigned int x, y, w, h; char timestamp[20]; sscanf(imgs.getPath(j).c_str(), "%14sx%3uy%3uw%3uh%3u.png", timestamp, &x, &y, &w, &h); gray_rects[i].set(x, y, w, h); cout << "timestamp: " << timestamp << "\n"; cout << "x: " << x << " y:" << y << "\n"; cout << "w: " << w << " h:" << h << "\n"; } num_images = img_count; } void ofApp::store_image() { time_t rawtime; time(&rawtime); struct tm *timeinfo; timeinfo = localtime(&rawtime); char timestamp[80]; strftime(timestamp, 80, "%m-%d-%H-%M-%S", timeinfo); cout << timestamp << std::endl; ofRectangle r = facerect; char name[256]; sprintf(name, "%sx%03dy%03dw%03dh%03d.png", timestamp, int(r.x), int(r.y), int(r.width), int(r.height)); cout << "saving image: " << name; saveimg.save(name); idle_image.clone(saveimg); id++; } //-------------------------------------------------------------- void ofApp::draw_idle1() { // list of images in ofDirectory imgs, load and display // idle1: align faces & crossfade ofSetColor(255, 255, 255, 255); if (yes_flag) { ofSetColor(255, 255, 255, int(127 * (cos(0.5*state.time_elapsed()) + 1))); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); } ofSetColor(255, 255, 255, 127); //grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); for (int i = 0; i < num_images; i++) { ofRectangle r = gray_rects[i]; ofPoint fc = gray_rects[i].getCenter(); ofPoint cp = ofPoint(ofGetWidth() / 2, ofGetHeight() / 2, 0.); //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); // draw image so faces are centered. Face center is at fc ofPushMatrix(); ofSetColor(0, 255, 0, 255); // scale faces to take up 1/3 of screen float scale = ofGetWidth() / (3*r.width); //scale = 1.0; ofScale(scale, scale, 1.0); ofTranslate((cp.x/scale) - fc.x, (cp.y/scale) - fc.y); ofRect(r); ofSetColor(255, 255, 255, 127); gray_images[i].draw(0, 0); //x += ss; ofPopMatrix(); } return; // brady bunch int x = 0; int y = 0; int maxy = -1; for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int(127 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, 255); ofRectangle r = gray_rects[i]; //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); gray_images[i].drawSubsection(x, y, r.width, r.height, r.x, r.y); //x += ss; if (r.height > maxy) { maxy = r.height; } x += r.width; if (x > ofGetWidth() - 150) { y += maxy; x = 0; maxy = -1; } } } //-------------------------------------------------------------- void ofApp::draw_idle() { // boring plain image crossfade // list of images in ofDirectory imgs, load and display ofSetColor(255, 255, 255, 255); for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int((100 / (i + 1)) * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, int(100 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1. / (i + 1)))); //ofSetColor(255, 255, 255, 100); gray_images[i].draw(0, 0, ofGetWidth(), ofGetHeight()); //ofSetColor(0,255,0,255); //ofRect(gray_rects[i]); } if (yes_flag) { ofSetColor(255, 255, 255, int(127 * (cos(0.5*state.time_elapsed()) + 1))); idle_image.draw(0, 0, ofGetWidth(), ofGetHeight()); } ofSetColor(255, 255, 255, 127); grayimg.draw(0, 0, ofGetWidth(), ofGetHeight()); return; // brady bunch int x = 0; int y = 0; int maxy = -1; for (int i = 0; i < num_images; i++) { //ofSetColor(255, 255, 255, int(127 * (sin(float(i)*0.2*ofGetElapsedTimef()) + 1.))); ofSetColor(255, 255, 255, 255); ofRectangle r = gray_rects[i]; //gray_images[i].drawSubsection(x, y, ss, ss, r.width, r.height, r.x, r.y); gray_images[i].drawSubsection(x, y, r.width, r.height, r.x, r.y); //x += ss; if (r.height > maxy) { maxy = r.height; } x += r.width; if (x > ofGetWidth() - 150) { y += maxy; x = 0; maxy = -1; } } } void ofApp::clean_exit(int signal) { // clean exit, signal handler cout << "Exit signal caught, bye!\n"; ofExit(); } void ofApp::keyPressed(int key) { if (key == 'x') { ofExit(); } if (key == 's') { // test back-to-idle handling saveimg.setFromPixels(cam.getPixels()); if (finder.size()) { saverect = finder.getObjectSmoothed(0); store_image(); } init_idle(); } if (key == 'p') { time_t rawtime; time(&rawtime); struct tm *timeinfo; timeinfo = localtime(&rawtime); //char buffer[80]; //strftime(buffer, 80, "Now it's %I:%M%p.", timeinfo); char timestamp[80]; strftime(timestamp, 80, "%m-%d-%H-%M-%S", timeinfo); //cout << "Current time is :: " << ctime(&rawtime) << std::endl; cout << timestamp << std::endl; } } // State machine handling ------------------------------------------------------------ void StateMach::set(int next_state, float timeout) { state = next_state; timeout_time = timeout; // default no timeout if (timeout >= 0) { ofResetElapsedTimeCounter(); reset_timer(); } print(); } void StateMach::reset_timer(void) { start_time = ofGetElapsedTimef(); } float StateMach::time_elapsed(void) { return(ofGetElapsedTimef() - start_time); } // return the fraction of elapsed time that has passed float StateMach::frac_time_elapsed(void) { if (time_elapsed() > timeout_time) { return 1.0; } return(time_elapsed() / timeout_time); } bool StateMach::timeout(void) { if (timeout_time < 0) return(true); if (time_elapsed() > timeout_time) return(true); return(false); } void StateMach::print(void) { cout << "State ID:" << state << " "; switch (state) { case S_IDLE: cout << "State: IDLE\n"; break; case S_HELLO: cout << "State: HELLO\n"; break; case S_QUESTION: cout << "State: QUESTION\n"; break; case S_THREE: cout << "State: THREE\n"; break; case S_TWO: cout << "State: TWO\n"; break; case S_ONE: cout << "State: ONE\n"; break; case S_YES_COUNT: cout << "State: YES_COUNT\n"; break; case S_CAPTURE: cout << "State: CAPTURE\n"; break; case S_NO_IMG: cout << "State: NO_IMG\n"; break; case S_YES_IMG: cout << "State: YES_IMG\n"; break; default: cout << "unknown state\n"; break; } }
#include <iostream> #include <cstring> using namespace std; string love = "I love that "; string hate = "I hate that "; string love_end = "I love it"; string hate_end = "I hate it"; int main(int argc, char *argv[]) { int n; cin >> n; string result; for (int i = 1; i <= n; i++){ if (i == n){ if (i & 1) result += hate_end; else result += love_end; } else { if (i & 1) result += hate; else result += love; } } cout << result << endl; return 0; }
#include <bits/stdc++.h> using namespace std; void rvereseArray(int arr[], int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); cout<<"original array"<<endl; for(int i=0 ; i<n ; i++){ cout<<arr[i]<<" "; } cout<<endl; rvereseArray(arr, 0, n-1); cout << "Reversed array is" << endl; for(int i=0 ; i<n ; i++){ cout<<arr[i]<<" "; } cout<<endl; return 0; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Devices.Scanners.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_80646519_5e2a_595d_a8cd_2a24b4067f1b #define WINRT_GENERIC_80646519_5e2a_595d_a8cd_2a24b4067f1b template <> struct __declspec(uuid("80646519-5e2a-595d-a8cd-2a24b4067f1b")) __declspec(novtable) IVectorView<Windows::Storage::StorageFile> : impl_IVectorView<Windows::Storage::StorageFile> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_2f74576f_0498_5348_bc3b_a70d1a771718 #define WINRT_GENERIC_2f74576f_0498_5348_bc3b_a70d1a771718 template <> struct __declspec(uuid("2f74576f-0498-5348-bc3b-a70d1a771718")) __declspec(novtable) IAsyncOperation<Windows::Devices::Scanners::ImageScannerPreviewResult> : impl_IAsyncOperation<Windows::Devices::Scanners::ImageScannerPreviewResult> {}; #endif #ifndef WINRT_GENERIC_6e6e228a_f618_5d33_8523_02d16672665b #define WINRT_GENERIC_6e6e228a_f618_5d33_8523_02d16672665b template <> struct __declspec(uuid("6e6e228a-f618-5d33-8523-02d16672665b")) __declspec(novtable) IAsyncOperationWithProgress<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> : impl_IAsyncOperationWithProgress<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> {}; #endif #ifndef WINRT_GENERIC_75d78736_6c52_551e_ab5f_50674f323431 #define WINRT_GENERIC_75d78736_6c52_551e_ab5f_50674f323431 template <> struct __declspec(uuid("75d78736-6c52-551e-ab5f-50674f323431")) __declspec(novtable) IAsyncOperation<Windows::Devices::Scanners::ImageScanner> : impl_IAsyncOperation<Windows::Devices::Scanners::ImageScanner> {}; #endif } namespace ABI::Windows::Foundation::Collections { #ifndef WINRT_GENERIC_fcbc8b8b_6103_5b4e_ba00_4bc2cedb6a35 #define WINRT_GENERIC_fcbc8b8b_6103_5b4e_ba00_4bc2cedb6a35 template <> struct __declspec(uuid("fcbc8b8b-6103-5b4e-ba00-4bc2cedb6a35")) __declspec(novtable) IVector<Windows::Storage::StorageFile> : impl_IVector<Windows::Storage::StorageFile> {}; #endif #ifndef WINRT_GENERIC_9ac00304_83ea_5688_87b6_ae38aab65d0b #define WINRT_GENERIC_9ac00304_83ea_5688_87b6_ae38aab65d0b template <> struct __declspec(uuid("9ac00304-83ea-5688-87b6-ae38aab65d0b")) __declspec(novtable) IIterable<Windows::Storage::StorageFile> : impl_IIterable<Windows::Storage::StorageFile> {}; #endif #ifndef WINRT_GENERIC_43e29f53_0298_55aa_a6c8_4edd323d9598 #define WINRT_GENERIC_43e29f53_0298_55aa_a6c8_4edd323d9598 template <> struct __declspec(uuid("43e29f53-0298-55aa-a6c8-4edd323d9598")) __declspec(novtable) IIterator<Windows::Storage::StorageFile> : impl_IIterator<Windows::Storage::StorageFile> {}; #endif } namespace ABI::Windows::Foundation { #ifndef WINRT_GENERIC_c054a410_ac3c_5353_b1ee_e85e78faf3f1 #define WINRT_GENERIC_c054a410_ac3c_5353_b1ee_e85e78faf3f1 template <> struct __declspec(uuid("c054a410-ac3c-5353-b1ee-e85e78faf3f1")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Scanners::ImageScannerPreviewResult> : impl_AsyncOperationCompletedHandler<Windows::Devices::Scanners::ImageScannerPreviewResult> {}; #endif #ifndef WINRT_GENERIC_d1662baa_4f20_5d18_97f1_a01a6d0dd980 #define WINRT_GENERIC_d1662baa_4f20_5d18_97f1_a01a6d0dd980 template <> struct __declspec(uuid("d1662baa-4f20-5d18-97f1-a01a6d0dd980")) __declspec(novtable) AsyncOperationProgressHandler<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> : impl_AsyncOperationProgressHandler<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> {}; #endif #ifndef WINRT_GENERIC_bd8bdbd8_459a_52dc_b101_75b398a61aef #define WINRT_GENERIC_bd8bdbd8_459a_52dc_b101_75b398a61aef template <> struct __declspec(uuid("bd8bdbd8-459a-52dc-b101-75b398a61aef")) __declspec(novtable) AsyncOperationWithProgressCompletedHandler<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> : impl_AsyncOperationWithProgressCompletedHandler<Windows::Devices::Scanners::ImageScannerScanResult, uint32_t> {}; #endif #ifndef WINRT_GENERIC_b35ad6b4_0da0_5241_87ff_eef3a1883243 #define WINRT_GENERIC_b35ad6b4_0da0_5241_87ff_eef3a1883243 template <> struct __declspec(uuid("b35ad6b4-0da0-5241-87ff-eef3a1883243")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Scanners::ImageScanner> : impl_AsyncOperationCompletedHandler<Windows::Devices::Scanners::ImageScanner> {}; #endif } namespace Windows::Devices::Scanners { struct IImageScanner : Windows::Foundation::IInspectable, impl::consume<IImageScanner> { IImageScanner(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerFeederConfiguration : Windows::Foundation::IInspectable, impl::consume<IImageScannerFeederConfiguration>, impl::require<IImageScannerFeederConfiguration, Windows::Devices::Scanners::IImageScannerFormatConfiguration, Windows::Devices::Scanners::IImageScannerSourceConfiguration> { IImageScannerFeederConfiguration(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerFormatConfiguration : Windows::Foundation::IInspectable, impl::consume<IImageScannerFormatConfiguration> { IImageScannerFormatConfiguration(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerPreviewResult : Windows::Foundation::IInspectable, impl::consume<IImageScannerPreviewResult> { IImageScannerPreviewResult(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerScanResult : Windows::Foundation::IInspectable, impl::consume<IImageScannerScanResult> { IImageScannerScanResult(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerSourceConfiguration : Windows::Foundation::IInspectable, impl::consume<IImageScannerSourceConfiguration>, impl::require<IImageScannerSourceConfiguration, Windows::Devices::Scanners::IImageScannerFormatConfiguration> { IImageScannerSourceConfiguration(std::nullptr_t = nullptr) noexcept {} }; struct IImageScannerStatics : Windows::Foundation::IInspectable, impl::consume<IImageScannerStatics> { IImageScannerStatics(std::nullptr_t = nullptr) noexcept {} }; } }
#include <string> typedef enum { typeCon, typeId, typeOpr } nodeEnum; /*constant, identifier, or operation*/ /* constants */ typedef struct { int value; /* value of constant */ } conNodeType; /* identifiers */ typedef struct { int i; /* subscript to sym array */ } idNodeType; /* operators */ typedef struct { int oper; /* operator */ int nops; /* number of operands */ struct nodeTypeTag *op[1]; /* operands, extended at runtime */ } oprNodeType; typedef struct nodeTypeTag { nodeEnum type; /* type of node */ union { conNodeType con; /* constants */ idNodeType id; /* identifiers */ oprNodeType opr; /* operators */ }; } nodeType; extern int sym[26];
#include<string> #include<sstream> #pragma once using namespace std; class Property { public: Property::Property(bool rental, int value, string address); ~Property(); bool getRental(); int getValue(); string getAddress(); virtual double getTax(); int getID() const; virtual string toString(); int ID = 0; protected: bool rental; int value; string address; double tax; };
//tic tac toe implementation file #include <iostream> #include <iomanip> #include "ticTacToe.h" #include <string> using namespace std; int PLAYER1WINS = 0; int PLAYER2WINS = 0; double PLAYER1KDRAT = 0.00; double PLAYER2KDRAT = 0.00; void ticTacToe::play() { bool done = false; char player1 = ' '; char player = ' '; char again = ' '; char choice = ' '; string player1Name = " "; string player2Name = " "; if (player1Name == " ") { cout << "Enter the name of player 1: " << endl; cin >> player1Name; cout << "Enter the name of player 2: " << endl; cin >> player2Name; } cout << player1Name << " enter X/x or O/o" << endl; cin >> player; if (player == 'x' || player == 'X') { player = 'X'; player1 = 'X'; } else if (player == 't') { ticTacToe game; game.stats(player1Name, player2Name); } else { player = 'O'; player1 = 'O'; } system("CLS"); displayBoard(); while (!done) { done = getXOMove(player, player1, player1Name, player2Name); if (player == 'X') player = 'O'; else player = 'X'; } } void ticTacToe::displayBoard() const { cout << " 1 2 3" << endl << endl; for (int row = 0; row < 3; row++) { cout << row + 1; for (int col = 0; col < 3; col++) { cout << setw(3) << board[row][col]; if (col != 2) cout << " |"; } cout << endl; if (row != 2) { cout << " ____|____|____" << endl << " | | " << endl; } } cout << endl; } bool ticTacToe::isValidMove(int row, int col) const { if (0 <= row && row <= 2 && 0 <= col && col <= 2 && board[row][col] == ' ') return true; else return false; } bool ticTacToe::getXOMove(char playerSymbol, char firstPlayer, string name1, string name2) { int row, col; char again = ' '; do { if (playerSymbol == firstPlayer) { cout << name1 << " enter move, row first, space, then column: "; cin >> row >> col; cout << endl; while (board[row - 1][col - 1] != ' ') { cout << "Invalid input, try again. Row first, space, then column: "; cin >> row >> col; } } else { cout << name2 << " enter move, row first, space, then column: "; cin >> row >> col; cout << endl; while (board[row - 1][col - 1] != ' ') { cout << "Invalid input, try again. Row first, space, then column: "; cin >> row >> col; } } } while (!isValidMove(row - 1, col - 1)); row--; col--; noOfMoves++; board[row][col] = playerSymbol; system("CLS"); displayBoard(); //check each play for a winner status gStatus = gameStatus(); if (gStatus == WIN) { if (playerSymbol == firstPlayer) { cout << name1 << " wins!" << endl; PLAYER1WINS += 1; ticTacToe::stats(name1, name2); } else { cout << name2 << " wins" << endl; PLAYER2WINS += 1; cout << PLAYER2WINS; ticTacToe::stats(name1, name2); } return true; } else if (gStatus == DRAW) { cout << "This game is a draw!" << endl; return true; } else return false; } status ticTacToe::gameStatus() { //Check rows for a win for (int row = 0; row < 3; row++) if (board[row][0] != ' ' && (board[row][0] == board[row][1]) && (board[row][1] == board[row][2])) return WIN; for (int col = 0; col < 3; col++) { if (board[0][col] != ' ' && (board[0][col] == board[1][col]) && (board[1][col] == board[2][col])) return WIN; } //check diagnosis for a win if (board[0][0] != ' ' && (board[0][0] == board[1][1]) && (board[1][1] && board[1][1] == board[2][2])) { return WIN; } if (board[2][0] != ' ' && (board[2][0] == board[1][1]) && (board[1][1] == board[0][2])) { return WIN; } if (noOfMoves < 9) return CONTINUE; return DRAW; } void ticTacToe::reStart() { for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { board[row][col] = ' '; } } noOfMoves = 0; } void ticTacToe::stats(string name1, string name2) { char choice = ' '; cout << "Would you like to view stats? y/n" << endl; cin >> choice; if (choice == 'y' || choice == 'Y') { if (PLAYER2WINS != 0) { PLAYER1KDRAT = PLAYER1WINS / PLAYER2WINS; } else PLAYER1KDRAT = PLAYER1WINS; if (PLAYER1WINS != 0) PLAYER2WINS = PLAYER2WINS / PLAYER1WINS; else PLAYER2KDRAT = PLAYER2WINS; cout << " Name: " << setw(10) << left << name1 << setw(11) << name2 << endl << " Wins: " << setw(5) << right << PLAYER1WINS << setw(9) << right << PLAYER2WINS << endl << "K/D Ratio: " << setw(5) << right << PLAYER1KDRAT << setw(9) << right << PLAYER2KDRAT << endl; cout << "Would you like to play again? "; cin >> choice; if (choice == 'y' || choice == 'Y') { system("CLS"); ticTacToe(); } } else { cout << "Would you like to play again? "; cin >> choice; if (choice == 'y' || choice == 'Y') ticTacToe(); else exit(0); } } ticTacToe::ticTacToe() { for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { board[row][col] = ' '; } } noOfMoves = 0; ticTacToe::play(); }
#include "register_types.h" #if defined(__APPLE__) #include "ios/LocalNotification.h" #endif void register_localnotification_types() { #if defined(__APPLE__) ClassDB::register_class<GodotLocalNotification>(); #endif } void unregister_localnotification_types() { }
#include <algorithm> #include <iostream> #include <vector> #define LL long long #define MOD 1000000007 using namespace std; struct Matrix { int n, m; LL a[51][51]; Matrix (int n, int m, LL init) { this->n = n; this->m = m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = init; } } } Matrix (int n) { this->n = this->m = n; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = (i == j); } } } Matrix operator* (const Matrix &b) const { Matrix ans(n, b.m, 0); for (int i = 0; i < n; i++) { for (int k = 0; k < m; k++) { for (int j = 0; j < b.m; j++) { ans.a[i][j] = (ans.a[i][j] + a[i][k] * b.a[k][j]) % MOD; } } } return ans; } }; int main () { int n, m, k; cin >> n >> m >> k; vector<pair<int,vector<int> > > forbid; Matrix trans(m+1, m+1, 1); for (int i = 0; i < m+1; i++) trans.a[0][i] = 0; while (k--) { char t; cin >> t; if (t == 'A') { int x, y; cin >> x >> y; trans.a[x][y] = trans.a[y][x] = 0; } else if (t == 'B') { int i, p; cin >> i >> p; vector<int> c(p); for (int j = 0; j < p; j++) cin >> c[j]; forbid.push_back({i, c}); } } sort(forbid.begin(), forbid.end()); vector<Matrix> base{trans}; for (int i = 1; i < 32; i++) { base.push_back(base.back() * base.back()); } Matrix ans(m+1, 1, 0); ans.a[0][0] = 1; for (int i = 0; i <= forbid.size(); i++) { int start = i == 0 ? 0 : forbid[i-1].first; int end = i == forbid.size() ? n : forbid[i].first; int b = end - start; for (int j = 0; b; j++, b>>=1) { if (b & 1) ans = base[j] * ans; } if (i == forbid.size()) continue; for (int c : forbid[i].second) { ans.a[c][0] = 0; } } LL out = 0; for (int i = 1; i <= m; i++) out += ans.a[i][0]; out %= MOD; cout << out << endl; return 0; }
#include <iostream> using namespace std; void Qsort(int a[],int low,int high) { if(low>=high) return; int first=low; int last=high; int k=a[first]; while (first<last) { while (first<last&&a[last]>=k) last--; a[first]=a[last]; while(first<last&&a[first]<=k) first++; a[last]=a[first]; } a[last]=k; Qsort(a,low,last-1); Qsort(a,last+1,high); } int main() { int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24}; Qsort(a,0,8); for(int k=0;k<9;k++) printf("%d ",a[k]); }
#include<bits/stdc++.h> using namespace std; struct SegmentTree{ int s,e; int val; int lazy = 0; SegmentTree *l,*r; int init(int *a, int start, int end){ s = start; e = end; if(s!=e){ l = new SegmentTree; r = new SegmentTree; return val = (l->init(a,s,(s+e)/2))^(r->init(a,(s+e)/2+1,e)); } else return val = a[s]; } void propagate(){ if(lazy==0ll) return; if(s==e) { val ^= lazy; } else { if((e-s+1)%2) val ^= lazy; l->lazy ^= lazy; r->lazy ^= lazy; } lazy=0ll; } int get(int tarS, int tarE){ propagate(); if(e<tarS||tarE<s) return 0; else if(tarS<=s&&e<=tarE) return val; else return (l->get(tarS,tarE))^(r->get(tarS,tarE)); } void update(int tarS, int tarE, int diff){ propagate(); if(e<tarS||tarE<s) return; else if(tarS<=s&&e<=tarE){ lazy ^= diff; propagate(); return; } else { l->update(tarS,tarE,diff); r->update(tarS,tarE,diff); val = l->val^r->val; } } }; int n,a[500010]; int main(){ scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); SegmentTree* st = new SegmentTree; st->init(a,0,n-1); int m; scanf("%d",&m); while(m--){ int t; scanf("%d",&t); if(t==1){ int s,e,diff; scanf("%d %d %d",&s,&e,&diff); st->update(s,e,diff); } else { int tar; scanf("%d",&tar); printf("%d\n",st->get(tar,tar)); } } }
// // Item.h // Boids // // Created by chenyanjie on 4/27/15. // // #ifndef __Boids__Item__ #define __Boids__Item__ #include "spine/spine-cocos2dx.h" typedef enum { ItemStateFly = 1, ItemStateReady = 2, ItemStateDisappear = 3 }eItemState; class Item : public cocos2d::Ref { private: int _item_id; cocos2d::ValueMap _item_data; public: Item(); virtual ~Item(); static Item* create( const cocos2d::ValueMap& item_data ); virtual bool init( const cocos2d::ValueMap& item_data ); int getItemId() { return _item_id; } void setItemId( int i ) { _item_id = i; } std::string getName(); std::string getResource(); void removeFromUnit( class UnitNode* owner ); }; class DropItem : public cocos2d::Node { private: std::string _item_id; int _count; eItemState _state; bool _should_recycle; spine::SkeletonAnimation* _effect; public: DropItem(); virtual ~DropItem(); static DropItem* create( const cocos2d::ValueMap& item_data ); virtual bool init( const cocos2d::ValueMap& item_data ); const std::string& getItemId() { return _item_id; } void setItemId( const std::string& item_id ) { _item_id = item_id; } int getCount() { return _count; } void setCount( int count ) { _count = count; } eItemState getItemState() { return _state; } void setItemState( eItemState state ) { _state = state; } bool shouldRecycle() { return _should_recycle; } void setShouldRecycle( bool b ) { _should_recycle = b; } void dropTo( const cocos2d::Point& pos ); void onDropCompleted(); }; #endif /* defined(__Boids__Item__) */