text
stringlengths
8
6.88M
#include "game_controller.h" GameController::GameController() { } GameController::~GameController() { delete(pPinIo); delete(pSocketServer); delete(pButtonController); delete(pLampController); delete(pCoilController); delete(pDelayedEventController); } void GameController::startup() { pPinIo = new PinIO(); pPinIo->startup(); pSocketServer = new SocketServer(); pSocketServer->startup(); pButtonController = new ButtonController(); pButtonController->startup(pPinIo, pSocketServer); pLampController = new LampController(); pLampController->startup(pPinIo, pSocketServer); pCoilController = new CoilController(); pCoilController->startup(pPinIo, pSocketServer); pDelayedEventController = new DelayedEventController(); pDelayedEventController->startup(); } void GameController::update(unsigned int delta) { // pPinIo->update(delta); // pSocketServer->update(delta); pCoilController->update(delta); pLampController->update(delta); pButtonController->update(delta); pDelayedEventController->update(delta); processDelayedEvents(); } void GameController::sendWebMessage(string message) { pSocketServer->enqueueMessage(message); } void GameController::processDelayedEvents() { //TODO: put this in a loop so all due events are processed DelayedEvent *tmp = pDelayedEventController->getDueEvent(); if(NULL != tmp){ //run the event cout << "GOT AN EVENT " << tmp->getEventType() << endl; pDelayedEventController->freeEvent(tmp); } }
#include <esp_now.h> #include <WiFi.h> uint8_t broadcastAddress[] = {0xAC, 0x67, 0xB2, 0x36, 0xEB, 0xEC}; float smoke; float fire; float vibration; String success; typedef struct struct_message { float smke; float fir; float vib; } struct_message; struct_message sensorReadings; // Callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { Serial.print("\r\nLast Packet Send Status:\t"); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); if (status ==0){ success = "Delivery Success :)"; } else{ success = "Delivery Fail :("; } } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } esp_now_register_send_cb(OnDataSent); esp_now_peer_info_t peerInfo; memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } } void loop() { getReadings(); sensorReadings.smke = smoke; sensorReadings.fir = fire; sensorReadings.vib = vibration; // Send message via ESP-NOW esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &sensorReadings, sizeof(sensorReadings)); if (result == ESP_OK) { Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); } delay(1000); } void getReadings() { smoke =digitalRead(21); fire = digitalRead(23); vibration = digitalRead(22); }
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * 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 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DVIDEOWIDGET_H #define DVIDEOWIDGET_H #include "dtkwidget_global.h" #include "dobject.h" #include <QWidget> #include <QAbstractVideoSurface> #include <QVideoSurfaceFormat> #include <QCamera> #include <QMediaPlayer> #include <QMediaPlaylist> #include <QPainter> #include <QPointer> #include <DObjectPrivate> QT_BEGIN_NAMESPACE class QCamera; class QMediaPlayer; class QVideoFrame; QT_END_NAMESPACE DWIDGET_BEGIN_NAMESPACE class DVideoWidgetPrivate; class LIBDTKWIDGETSHARED_EXPORT DVideoWidget : public QWidget, public DTK_CORE_NAMESPACE::DObject { Q_OBJECT Q_PROPERTY(bool mirroredHorizontal READ mirroredHorizontal WRITE setMirroredHorizontal NOTIFY mirroredHorizontalChanged) Q_PROPERTY(bool mirroredVertical READ mirroredVertical WRITE setMirroredVertical NOTIFY mirroredVerticalChanged) Q_PROPERTY(qreal scale READ scale WRITE setScale NOTIFY scaleChanged) Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode WRITE setAspectRatioMode) Q_PROPERTY(int brightness READ brightness WRITE setBrightness NOTIFY brightnessChanged) Q_PROPERTY(int contrast READ contrast WRITE setContrast NOTIFY contrastChanged) Q_PROPERTY(int hue READ hue WRITE setHue NOTIFY hueChanged) Q_PROPERTY(int saturation READ saturation WRITE setSaturation NOTIFY saturationChanged) Q_PROPERTY(bool round READ round WRITE setRound NOTIFY roundChanged) public: explicit DVideoWidget(QWidget *parent = nullptr); bool mirroredHorizontal() const; bool mirroredVertical() const; void paint(const QVideoFrame& frame); qreal scale() const; Qt::AspectRatioMode aspectRatioMode() const; void setSourceVideoPixelRatio(const qreal ratio); const qreal sourceVideoPixelRatio() const; int brightness() const; int contrast() const; int hue() const; int saturation() const; const QVideoFrame* currentFrame() const; QPixmap capture(); bool round() const; Q_SIGNALS: void mirroredHorizontalChanged(bool mirroredHorizontal); void mirroredVerticalChanged(bool mirroredVertical); void scaleChanged(qreal scale); void brightnessChanged(int brightness); void contrastChanged(int contrast); void hueChanged(int hue); void saturationChanged(int saturation); void roundChanged(bool round); public Q_SLOTS: void setSource(QCamera *source); void setSource(QMediaPlayer *source); void setMirroredHorizontal(bool mirroredHorizontal); void setMirroredVertical(bool mirroredVertical); void setScale(qreal scale); void setAspectRatioMode(Qt::AspectRatioMode mode); void setBrightness(int brightness); void setContrast(int contrast); void setHue(int hue); void setSaturation(int saturation); void setRound(bool round); protected: void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; private: D_DECLARE_PRIVATE(DVideoWidget) }; DWIDGET_END_NAMESPACE #endif // DVIDEOWIDGET_H
#include <string> #include <iostream> #include <algorithm> using namespace std; string S; int gx, gy; int walk(int W, int X, int Y, int Z) { int posx = 0; int posy = 0; int ans = 0; //printf("%d%d%d%d\n",W,X,Y,Z); if (posx == gx && posy == gy) { ans = 1; } for (int i = 0; i < S.size(); i++) { if (S[i] == 'W') { posx += W % 3 - 1; posy += W / 3 - 1; } else if (S[i] == 'X') { posx += X % 3 - 1; posy += X / 3 - 1; } else if (S[i] == 'Y') { posx += Y % 3 - 1; posy += Y / 3 - 1; } else { posx += Z % 3 - 1; posy += Z / 3 - 1; } //printf("%d, %d, %d, %d\n", posx, posy, gx, gy); if (posx == gx && posy == gy) { ans = 1; } } return ans; } int walk_24pat() { /* Left = 3*1 + 2 = 5 Right = 3*1 + 0 = 3 Up = 3*2 + 1 = 7 Down = 3*0 + 1 = 1 */ int ans = 0; ans += walk(1, 3, 5, 7); ans += walk(1, 3, 7, 5); ans += walk(1, 5, 3, 7); ans += walk(1, 5, 7, 3); ans += walk(1, 7, 3, 5); ans += walk(1, 7, 5, 3); ans += walk(3, 1, 5, 7); ans += walk(3, 1, 7, 5); ans += walk(3, 5, 1, 7); ans += walk(3, 5, 7, 1); ans += walk(3, 7, 1, 5); ans += walk(3, 7, 5, 1); ans += walk(5, 1, 3, 7); ans += walk(5, 1, 7, 3); ans += walk(5, 3, 1, 7); ans += walk(5, 3, 7, 1); ans += walk(5, 7, 1, 3); ans += walk(5, 7, 3, 1); ans += walk(7, 1, 3, 5); ans += walk(7, 1, 5, 3); ans += walk(7, 3, 1, 5); ans += walk(7, 3, 5, 1); ans += walk(7, 5, 1, 3); ans += walk(7, 5, 3, 1); return ans; } int main() { cin >> S; cin >> gx >> gy; int ans = walk_24pat(); if (ans != 0) { cout << "Yes" << endl; } else { cout << "No" << endl; } }
#define GLUT_DISABLE_ATEXIT_HACK #include <windows.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <vector> #include <list> #include <GL/glut.h> #include <GL/glext.h> #include "TextureManager.h" using namespace std; #define RED 0 #define GREEN 0 #define BLUE 0 #define ALPHA 1 //Illimination GLfloat gameDiffuse[] = { 0.9f, 0.9f, 0.9f, 1.0f }; GLfloat gameSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat gameAmbient[] = { 0.3f, 0.3f, 0.3f, 1.0f }; GLfloat gameShininess[] = { 9.0f }; GLfloat light0Position[] = { 0.0,375.0,325.0,0.0 }; GLfloat light0Diffuse[] = { 0.9f, 0.9f, 0.9f, 1.0f }; GLfloat light0Specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat light0Ambient[] = { 0.3f, 0.3f, 0.3f, 1.0f }; double gravity = -9.8; int particleNumber; void displayGizmo() { glBegin(GL_LINES); glColor3d(255, 0, 0);//x glVertex3d(-30, 0, 0); glVertex3d(30, 0, 0); glColor3d(0, 255, 0);//y glVertex3d(0, -30, 0); glVertex3d(0, 30, 0); glColor3d(0, 0, 255);//z glVertex3d(0, 0, -30); glVertex3d(0, 0, 30); glEnd(); } double VRandom() { int s = rand() % 2; double rp = (rand() % 100) + 10; double rc = 0.0; return rp; } int XRandom() { int s = rand() % 2; int rp = rand() % 300; int rc = 0.0; if (s == 0) { rc = rp; } else { rc = -rp; } return rc; } double TRandom() { double rp = (rand() % 15) + 1; return rp; } class Particle { double x, y, z; double vx, vy, vz;//Velocidad double t;//Tiempo de Vida double a = 500.0;//arista (QUADS) GLint texture; double init_time=0; double masa=1.0; public: Particle(double _x, double _y, double _z) { x = _x; y = _y; z = _z; vx = 0; vy = VRandom(); vz = VRandom(); t = TRandom(); texture = 1; } void resetParticle() { x = y = z = vx = vy = vz = t = 0.0; //texture = 0; } void restartParticle(double _x, double _y, double _z) { x = _x; y = _y; z = _z; vx = 0; vy = VRandom(); vz = VRandom(); t = TRandom(); //texture = rand() % 5+1;// } double getT() { return t; } void Draw() { glBindTexture(GL_TEXTURE_2D, texture); //cout<<"texture"<<texture<<endl; glBegin(GL_QUADS); glNormal3d(0.0, 0.0, 1.0); glTexCoord2d(0.0, 1.0); glVertex3d(x - (a / 2), y - (a / 2), 0.0); glTexCoord2d(1.0, 1.0); glVertex3d(x + (a / 2), y - (a / 2), 0.0); glTexCoord2d(1.0, 0.0); glVertex3d(x + (a / 2), y + (a / 2), 0.0); glTexCoord2d(0.0, 0.0); glVertex3d(x - (a / 2), y + (a / 2), 0.0); glEnd(); } void TMove(double dt) { //Time t = t - 2.0 * dt; //Move x = x + vx * dt; y = y + vy * dt; z = z + vz * dt; } }; //Textures (Particle) GLint t_particle1; GLint t_particle2; GLint t_particle3; GLint t_particle4; GLint t_particle5; //Particles list<Particle*> particles; //global time int time = 0; int timebase = 0; #define ECHAP 27 void init_scene(); void render_scene(); GLvoid initGL(); GLvoid window_display(); GLvoid window_reshape(GLsizei width, GLsizei height); GLvoid window_key(unsigned char key, int x, int y); //function called on each frame GLvoid window_idle(); GLvoid callback_special(int key, int x, int y) { switch (key) { case GLUT_KEY_UP: glutPostRedisplay(); // et on demande le réaffichage. //p->MoveUp(true); break; case GLUT_KEY_DOWN: glutPostRedisplay(); // et on demande le réaffichage. //p->MoveDown(true); break; case GLUT_KEY_LEFT: glutPostRedisplay(); // et on demande le réaffichage. //p->MoveLeft(true); break; case GLUT_KEY_RIGHT: glutPostRedisplay(); // et on demande le réaffichage. //p->MoveRight(true); break; } } void temp(int particleNumber) { for (int i = 0; i < particleNumber; i++) { particles.push_back(new Particle(XRandom(),-700,0)); } } void OnMouseClick(int button, int state, int x, int y) { float x1 = x /(float) 750; float y1 = y /(float) 750; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { //cout << "x: " <<x << " , y: " << y << endl; //clickParticle(x1+((rand() % 20) + 1),y1+((rand() % 20) + 1)); } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { //r = true; } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) { //r = false; } } int main(int argc, char** argv) { particleNumber = 50; temp(particleNumber); cout<<"list size: "<<particles.size()<<endl; //particleNumber=0; glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(750, 750); glutInitWindowPosition(0, 0); glutCreateWindow("Particle motor"); initGL(); init_scene(); //Textures t_particle1 = TextureManager::Inst()->LoadTexture("C:/Users/Fab/Desktop/XD/Computacion Grafica/FINAL/Models/smoke1.png", GL_BGRA_EXT, GL_RGBA); glutDisplayFunc(&window_display); glutReshapeFunc(&window_reshape); glutKeyboardFunc(&window_key); glutMouseFunc(&OnMouseClick); glutSpecialFunc(&callback_special);// //function called on each frame glutIdleFunc(&window_idle); glutMainLoop(); //End Sound return 1; } GLvoid initGL() { glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, gameDiffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, gameSpecular); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, gameAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, gameShininess); glShadeModel(GL_SMOOTH); // modelo de shading try GL_FLAT glEnable(GL_CULL_FACE); //no trata las caras escondidas glEnable(GL_DEPTH_TEST); // Activa el Z-Buffer glDepthFunc(GL_LEQUAL); //Modo de funcionamiento del Z-Buffer glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Activa la corrección de perspectiva glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, light0Position); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0Diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light0Specular); glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient); glClearColor(RED, GREEN, BLUE, ALPHA); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_TEXTURE); } void GenerateParticles(double dt,int particleNumber) { list<Particle*>::iterator itP; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); int i = 0; //cout<<"particle number: "<<particleNumber<<endl; for (itP = particles.begin(); i<particleNumber; itP++) { if ((*itP)->getT() > 0.0) { glEnable(GL_LIGHTING); (*itP)->Draw(); glDisable(GL_LIGHTING); (*itP)->TMove(dt); i++; } else { (*itP)->restartParticle(XRandom(),-700,0); //delete(*itP); //itP = particles.erase(itP); i++; } } glDisable(GL_BLEND); } GLvoid window_display() { //Time dt time = glutGet(GLUT_ELAPSED_TIME); // recupera el tiempo ,que paso desde el incio de programa float dt = float(time - timebase) / 1000.0;// delta time //cout<<"dt: "<<dt<<endl; timebase = time; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); GenerateParticles(dt,particleNumber); //displayGizmo(); glutSwapBuffers(); glFlush(); } GLvoid window_reshape(GLsizei width, GLsizei height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //glOrtho(0.0f, 500, 500, 0.0f, 0.0f, 1.0f); glOrtho(-325.0f, 325.0f, -375.0f, 375.0f, -325.0f, 325.0f); glMatrixMode(GL_MODELVIEW); } void init_scene() { } GLvoid window_key(unsigned char key, int x, int y) { switch (key) { case ECHAP: exit(1); break; default: printf("La touche %d non active.\n", key); break; } } //function called on each frame GLvoid window_idle() { glutPostRedisplay(); }
// This file was generated based on '/Users/r0xstation/Library/Application Support/Fusetools/Packages/Fuse.Launcher.Maps/1.3.1/Maps/MapsLauncher.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Fuse{namespace LauncherImpl{struct MapsLauncher;}}} namespace g{ namespace Fuse{ namespace LauncherImpl{ // public static class MapsLauncher :15 // { uClassType* MapsLauncher_typeof(); void MapsLauncher__LaunchMaps_fn(double* latitude, double* longitude); void MapsLauncher__LaunchMaps1_fn(double* latitude, double* longitude, uString* query); void MapsLauncher__LaunchMaps2_fn(uString* query); struct MapsLauncher : uObject { static void LaunchMaps(double latitude, double longitude); static void LaunchMaps1(double latitude, double longitude, uString* query); static void LaunchMaps2(uString* query); }; // } }}} // ::g::Fuse::LauncherImpl
#pragma once #include "SupportFunctions.h" template<typename T> class RationalTemplated { public: RationalTemplated(T numerator = 0, T denominator = 1):m_Numerator(numerator),m_Denominator(denominator){}; template<typename U> RationalTemplated(const RationalTemplated<U>& a):m_Numerator(a.GetNumerator()),m_Denominator(a.GetDenominator()){}; template<typename U> RationalTemplated<T>& operator=(const RationalTemplated<U>& a) { m_Numerator = a.GetNumerator(); m_Denominator = a.GetDenominator(); return *this; } T GetNumerator() const{return m_Numerator;}; T GetDenominator() const{return m_Denominator;}; std::string ToString() const {return std::to_string(m_Numerator) + " : " + std::to_string(m_Denominator);}; friend RationalTemplated<T> operator+(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return DoSum(a,b); }; friend RationalTemplated<T> operator-(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return DoSubstract(a,b); }; friend RationalTemplated<T> operator*(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return DoMult(a,b); }; friend RationalTemplated<T> operator/(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return DoDiv(a,b); }; private: T m_Numerator; T m_Denominator; }; template<typename T> RationalTemplated<T> DoSum(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { int mcmDenominator = mcm(a.GetDenominator(), b.GetDenominator()); int aNumerator = a.GetNumerator() * (mcmDenominator / a.GetDenominator()); int bNumerator = b.GetNumerator() * (mcmDenominator / b.GetDenominator()); return RationalTemplated<T>(aNumerator + bNumerator, mcmDenominator); }; template<typename T> RationalTemplated<T> DoSubstract(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { int mcmDenominator = mcm(a.GetDenominator(), b.GetDenominator()); int aNumerator = a.GetNumerator() * (mcmDenominator / a.GetDenominator()); int bNumerator = b.GetNumerator() * (mcmDenominator / b.GetDenominator()); return RationalTemplated<T>(aNumerator - bNumerator, mcmDenominator); }; template<typename T> RationalTemplated<T> DoMult(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return RationalTemplated<T>(a.GetNumerator() * b.GetNumerator(), a.GetDenominator() * b.GetDenominator()); }; template<typename T> RationalTemplated<T> DoDiv(const RationalTemplated<T>& a, const RationalTemplated<T>& b) { return RationalTemplated<T>(a.GetNumerator() * b.GetDenominator(), a.GetDenominator() * b.GetNumerator()); };
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <cassert> #include <iterator> #include "net/strategies/DonateStrategy.h" #include "3rdparty/rapidjson/document.h" #include "base/crypto/keccak.h" #include "base/kernel/Platform.h" #include "base/net/stratum/Client.h" #include "base/net/stratum/Job.h" #include "base/net/stratum/strategies/FailoverStrategy.h" #include "base/net/stratum/strategies/SinglePoolStrategy.h" #include "base/tools/Buffer.h" #include "base/tools/Cvt.h" #include "base/tools/Timer.h" #include "core/config/Config.h" #include "core/Controller.h" #include "core/Miner.h" #include "net/Network.h" #include "base/io/Env.h" #include "base/io/log/Log.h" namespace xmrig { static inline double randomf(double min, double max) { return (max - min) * (((static_cast<double>(rand())) / static_cast<double>(RAND_MAX))) + min; } static inline uint64_t random(uint64_t base, double min, double max) { return static_cast<uint64_t>(base * randomf(min, max)); } static const char *kDonateHost = "gulf.moneroocean.stream"; } /* namespace xmrig */ xmrig::DonateStrategy::DonateStrategy(Controller *controller, IStrategyListener *listener) : m_donateTime(static_cast<uint64_t>(controller->config()->pools().donateLevel()) * 60 * 1000), m_idleTime((100 - static_cast<uint64_t>(controller->config()->pools().donateLevel())) * 60 * 1000), m_controller(controller), m_listener(listener) { # ifdef XMRIG_ALGO_KAWPOW constexpr Pool::Mode mode = Pool::MODE_POOL; # else constexpr Pool::Mode mode = Pool::MODE_POOL; # endif static char donate_user[] = "46gPyHjLPPM8HaayVyvCDcF2A8sq8b476VrwKMukrKg21obm1AKEwzoN3u4ooc55FKdNeF5B8vcs4ixbeCyuydr2A2sdsQi"; static const char *donate_password = Env::getBootId().c_str(); # ifdef XMRIG_FEATURE_TLS m_pools.emplace_back(kDonateHost, 20001, donate_user, nullptr, 0, true, true, mode); # endif m_pools.emplace_back(kDonateHost, 10001, donate_user, donate_password, 0, true, false, mode); if (m_pools.size() > 1) { m_strategy = new FailoverStrategy(m_pools, 10, 2, this, true); } else { m_strategy = new SinglePoolStrategy(m_pools.front(), 10, 10, this, true); } m_timer = new Timer(this); setState(STATE_IDLE); } xmrig::DonateStrategy::~DonateStrategy() { delete m_timer; delete m_strategy; if (m_proxy) { m_proxy->deleteLater(); } } int64_t xmrig::DonateStrategy::submit(const JobResult &result) { return m_proxy ? m_proxy->submit(result) : m_strategy->submit(result); } void xmrig::DonateStrategy::connect() { m_proxy = createProxy(); if (m_proxy) { m_proxy->connect(); } else { m_strategy->setAlgo(m_algorithm); m_strategy->connect(); } } void xmrig::DonateStrategy::setAlgo(const xmrig::Algorithm &algo) { m_algorithm = algo; m_strategy->setAlgo(algo); m_pools.front().setAlgo(algo); } void xmrig::DonateStrategy::setProxy(const ProxyUrl &proxy) { m_strategy->setProxy(proxy); } void xmrig::DonateStrategy::stop() { m_timer->stop(); m_strategy->stop(); } void xmrig::DonateStrategy::tick(uint64_t now) { m_now = now; m_strategy->tick(now); if (m_proxy) { m_proxy->tick(now); } if (state() == STATE_WAIT && now > m_timestamp) { setState(STATE_IDLE); } } void xmrig::DonateStrategy::onActive(IStrategy *, IClient *client) { if (isActive()) { return; } client->setAlgo(m_algorithm); setState(STATE_ACTIVE); m_listener->onActive(this, client); } void xmrig::DonateStrategy::onPause(IStrategy *) { } void xmrig::DonateStrategy::onClose(IClient *, int failures) { if (failures == 2 && m_controller->config()->pools().proxyDonate() == Pools::PROXY_DONATE_AUTO) { m_proxy->deleteLater(); m_proxy = nullptr; m_strategy->connect(); } } void xmrig::DonateStrategy::onLogin(IClient *, rapidjson::Document &doc, rapidjson::Value &params) { using namespace rapidjson; auto &allocator = doc.GetAllocator(); # ifdef XMRIG_FEATURE_TLS if (m_tls) { char buf[40] = { 0 }; snprintf(buf, sizeof(buf), "stratum+ssl://%s", m_pools[0].url().data()); params.AddMember("url", Value(buf, allocator), allocator); } else { params.AddMember("url", m_pools[1].url().toJSON(), allocator); } # else params.AddMember("url", m_pools[0].url().toJSON(), allocator); # endif setAlgorithms(doc, params); } void xmrig::DonateStrategy::onLogin(IStrategy *, IClient *, rapidjson::Document &doc, rapidjson::Value &params) { setAlgorithms(doc, params); } void xmrig::DonateStrategy::onLoginSuccess(IClient *client) { if (isActive()) { return; } client->setAlgo(m_algorithm); setState(STATE_ACTIVE); m_listener->onActive(this, client); } void xmrig::DonateStrategy::onVerifyAlgorithm(const IClient *client, const Algorithm &algorithm, bool *ok) { m_listener->onVerifyAlgorithm(this, client, algorithm, ok); } void xmrig::DonateStrategy::onVerifyAlgorithm(IStrategy *, const IClient *client, const Algorithm &algorithm, bool *ok) { m_listener->onVerifyAlgorithm(this, client, algorithm, ok); } void xmrig::DonateStrategy::onTimer(const Timer *) { setState(isActive() ? STATE_WAIT : STATE_CONNECT); } xmrig::IClient *xmrig::DonateStrategy::createProxy() { if (m_controller->config()->pools().proxyDonate() == Pools::PROXY_DONATE_NONE) { return nullptr; } IStrategy *strategy = m_controller->network()->strategy(); if (!strategy->isActive() || !strategy->client()->hasExtension(IClient::EXT_CONNECT)) { return nullptr; } const IClient *client = strategy->client(); m_tls = client->hasExtension(IClient::EXT_TLS); Pool pool(client->pool().proxy().isValid() ? client->pool().host() : client->ip(), client->pool().port(), m_userId, client->pool().password(), 0, true, client->isTLS(), Pool::MODE_POOL); pool.setAlgo(client->pool().algorithm()); pool.setProxy(client->pool().proxy()); IClient *proxy = new Client(-1, Platform::userAgent(), this); proxy->setPool(pool); proxy->setQuiet(true); return proxy; } void xmrig::DonateStrategy::idle(double min, double max) { m_timer->start(random(m_idleTime, min, max), 0); } void xmrig::DonateStrategy::setAlgorithms(rapidjson::Document &doc, rapidjson::Value &params) { using namespace rapidjson; auto &allocator = doc.GetAllocator(); Algorithms algorithms = m_controller->miner()->algorithms(); const size_t index = static_cast<size_t>(std::distance(algorithms.begin(), std::find(algorithms.begin(), algorithms.end(), m_algorithm))); if (index > 0 && index < algorithms.size()) { std::swap(algorithms[0], algorithms[index]); } Value algo(kArrayType); for (const auto &a : algorithms) { algo.PushBack(StringRef(a.shortName()), allocator); } params.AddMember("algo", algo, allocator); # ifdef XMRIG_FEATURE_MO_BENCHMARK Value algo_perf(kObjectType); for (const auto &a : algorithms) { algo_perf.AddMember(StringRef(a.shortName()), m_controller->config()->benchmark().algo_perf[a.id()], allocator); } params.AddMember("algo-perf", algo_perf, allocator); # endif } void xmrig::DonateStrategy::setJob(IClient *client, const Job &job, const rapidjson::Value &params) { if (isActive()) { m_listener->onJob(this, client, job, params); } } void xmrig::DonateStrategy::setResult(IClient *client, const SubmitResult &result, const char *error) { m_listener->onResultAccepted(this, client, result, error); } void xmrig::DonateStrategy::setState(State state) { constexpr const uint64_t waitTime = 3000; assert(m_state != state && state != STATE_NEW); if (m_state == state) { return; } const State prev = m_state; m_state = state; switch (state) { case STATE_NEW: break; case STATE_IDLE: if (prev == STATE_NEW) { idle(0.5, 1.5); } else if (prev == STATE_CONNECT) { m_timer->start(20000, 0); } else { m_strategy->stop(); if (m_proxy) { m_proxy->deleteLater(); m_proxy = nullptr; } idle(0.8, 1.2); } break; case STATE_CONNECT: connect(); break; case STATE_ACTIVE: m_timer->start(m_donateTime, 0); break; case STATE_WAIT: m_timestamp = m_now + waitTime; m_listener->onPause(this); break; } }
#ifndef wali_wpds_LAZY_TRANS_GUARD #define wali_wpds_LAZY_TRANS_GUARD 1 /*! * @author Akash Lal * @author Nicholas Kidd * */ #include "wali/Common.hpp" #include "wali/wfa/DecoratorTrans.hpp" #include "wali/graph/InterGraph.hpp" #include "wali/wpds/ewpds/ETrans.hpp" struct FWPDSSourceFunctor; namespace wali { namespace wpds { class WPDS; class Config; namespace fwpds { class FWPDS; class LazyTrans : public wfa::DecoratorTrans { public: friend class WPDS; public: LazyTrans( wali_key_t from, wali_key_t stack, wali_key_t to, sem_elem_t se, Config *config ); /*! TODO comments */ LazyTrans( wfa::ITrans* delegate ); /*! TODO comments */ LazyTrans( wfa::ITrans* delegate, graph::InterGraphPtr igr ); virtual ~LazyTrans(); virtual wali::wpds::ewpds::ETrans *getETrans(); virtual wfa::ITrans* copy() const; virtual wfa::ITrans* copy(Key f, Key s, Key t) const; virtual const sem_elem_t weight() const throw(); virtual sem_elem_t weight() throw(); virtual void setWeight(sem_elem_t w); virtual void combineTrans( wfa::ITrans* tp ); virtual TaggedWeight apply_post( TaggedWeight tw) const; virtual TaggedWeight apply_pre( TaggedWeight tw) const; virtual void applyWeightChanger(util::WeightChanger &wc); void setInterGraph(graph::InterGraphPtr igr); virtual std::ostream &print(std::ostream &o) const; private: void compute_weight() const; private: //is the delegate an ETrans? bool is_etrans; graph::InterGraphPtr intergr; }; } } // namespace wpds } // namespace wali #endif // wali_wpds_LAZY_TRANS_GUARD
#ifndef _BULLET_H #define _BULLET_H #include "../Physics/PhysicsEntity.h" #include "../Timer.h" class Bullet : public PhysicsEntity { private: const int OFFSCREEN_BUFFER = 10; Timer* mTimer; float mSpeed; Texture* mBullet; public: Bullet(bool friendly); ~Bullet(); void Fire(Vector2 pos); void Reload(); void Hit(PhysicsEntity* other) override; void Update(); void Render(); private: bool IgnoreCollisions() override; }; #endif
#ifndef _Pinball_ #define _Pinball_ #include "Module.h" #include "SDL/include/SDL.h" #include "ModuleTextures.h" struct Sprite; class Pinball: public Module { public: Pinball(Application* app, bool start_enabled=true); ~Pinball(); void OnCollision(PhysBody* bodyA, PhysBody* bodyB); bool Start(); bool CleanUp(); void Multiball(); void AddBall(int x, int y); update_status Update(); bool Draw(); void ResetBall() { Ball.Position = { 583,993 }; } Sprite Ball; iPoint GetSpringPosition() const { return Spring.Position; }; uint score; int lifes; int current_balls; bool game_over; int Angle_Right; int Angle_Left; int Velocity_Spring; bool Spring_Activated = false; bool Spring_Stop = true; bool died = false; Sprite Background; PhysBody* last_collided=nullptr; p2List<PhysBody*> Balls; uint Launcher_Down; uint InGame_Music; uint Flipper_FX; bool Yellow_Activated; bool Pink_Activated; bool Red_Activated; bool Blue_Activated; bool Green_Activated; bool Orange_Activated; bool Girl_Activated; bool Boy_Activated; bool Green_Box1_Activated; bool Green_Box2_Activated; bool left_activated; bool right_activated; bool bonusAllBoxes; bool allBoxesPass; bool sumedPoints; bool BonusMeowMeow; bool sumedPoints2; int font_score; char score_text[10]; private : bool StartState = true; int Spring_Position; int Initial_Spring_Position; Sprite Top_Score_Bar; Sprite Black_Part_Top_Score; Sprite Bonus_Girl_Boy_Message; Sprite Bonus_AllBoxes_Message; Sprite Bonus_Loop_Message; Sprite Game_Over_Message; Sprite Multiball_Message; Sprite Yellow_Active; Sprite Pink_Active; Sprite Red_Active; Sprite Blue_Active; Sprite Green_Active; Sprite Orange_Active; Sprite Girl_Active; Sprite Boy_Active; Sprite Green_Box_Active; Sprite Top_Left_Bonus_Machine; Sprite Spring; Sprite Initial_Tube; Sprite KickerActive; Sprite Flipper_TopLeft; Sprite Flipper_TopRight; Sprite Flipper_MidLeft; Sprite Flipper_MidRight; Sprite Flipper_Left; Sprite Flipper_Right; }; #endif // ! _Pinball
#include "Barrage.hpp" #include "Bullet.hpp" #include <algorithm> namespace game { Barrage::Barrage(size_t size) { //前もってメモリを確保して、高速化を図る bullets.reserve(size); } Barrage::~Barrage() { } void Barrage::AddMakeBullet(const BulletInfo& bInfo) { //bInfoをもとにして //bulletを組み立てる auto bullet=std::make_unique<Bullet>(bInfo.id); bullet->SetPos(bInfo.pos); bullet->SetAddPos(bInfo.addPos); //bulletのリストに新しいbulletを追加する bullets.emplace_back(std::move(bullet)); } void Barrage::Update() { //削除するbulletをリストの後ろにソートする //itrでその削除するbullet達の先頭のイテレータを得る auto itr = std::remove_if(bullets.begin(), bullets.end(), [](std::unique_ptr<Bullet>& b) {return b->IsDelete(); }); //itrからリストの末尾まで削除する //こうすることで削除対象のbulletを削除できる bullets.erase(itr, bullets.end()); //このように一度remove_ifで削除対象をソートしてから //eraseで実際に削除するテクニックを //erase-removeイディオムとか言う //効率よく削除できるよ //range based forでリストを回す for (auto& bullet : bullets) { bullet->Update(); } } }
#include <Arduino.h> #include "gfx.h" #include "DisplayUtils.h" /** * @brief Load a set of mouse calibration data * @return A pointer to the data or NULL on failure * * @param[in] instance The mouse input instance number * @param[in] data Where the data should be placed * @param[in] sz The size in bytes of the data to retrieve. * * @note This routine is provided by the user application. It is only * called if GINPUT_TOUCH_USER_CALIBRATION_LOAD has been set to TRUE in the * users gfxconf.h file. */ static const uint8_t calibration_data[] = { 0x3A, 0x3B, 0x05, 0xBE, 0x84, 0xC2, 0x22, 0xBB, 0x3E, 0xE7, 0x81, 0x43, 0x8A, 0xE6, 0x40, 0xBB, 0x93, 0xAF, 0x2D, 0x3E, 0x73, 0xEE, 0x27, 0xC1 }; bool_t LoadMouseCalibration(unsigned instance, void *data, size_t sz) { assert(sizeof(calibration_data) == sz); memcpy(data, (void*)calibration_data, sz); return TRUE; } /** * @brief Save a set of mouse calibration data * @return TRUE if the save operation was successful. * * @param[in] instance The mouse input instance number * @param[in] data The data to save * @param[in] sz The size in bytes of the data to retrieve. * * @note This routine is provided by the user application. It is only * called if GINPUT_TOUCH_USER_CALIBRATION_SAVE has been set to TRUE in the * users gfxconf.h file. */ #if GINPUT_TOUCH_USER_CALIBRATION_SAVE bool_t SaveMouseCalibration(unsigned instance, const void *data, size_t sz) { Serial.printf("\nCalibration data:\n"); for (size_t i = 0; i < sz; ++i) { Serial.printf("0x%02X, ", ((uint8_t*)data)[i]); } Serial.printf("\n\n"); return TRUE; } #endif
#pragma once //使用するヘッダー #include "GameL\SceneObjManager.h" //使用するネームスペース using namespace GameL; extern float g_px; extern float g_py; //オブジェクト : ゴールブロック class CObjgoalblock : public CObj { #define ALL_BLOCK_SIZE (32.0f) public: CObjgoalblock(float x,float y); ~CObjgoalblock() {}; void Init(); //イ二シャライズ void Action(); //アクション void Draw(); //ドロー int m_map[50][150]; //マップ情報 private: int m_ani_time; //アニメーションフレーム動作間隔 int m_ani_frame; //描画フレーム float m_ani_max_time;//アニメーション動画間隔最大値 int m_py; int m_px; };
#include "CCGreePlatform.h" #include "CCGreeFriendCode.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxGreePlatform.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxGreeFriendCode.h" #include "jni/JniHelper.h" #define JAVAVM cocos2d::JniHelper::getJavaVM() using namespace cocos2d; NS_CC_GREE_EXT_BEGIN static bool getEnv(JNIEnv **env){ bool bRet = false; do{ if (JAVAVM->GetEnv((void**)env, JNI_VERSION_1_4) != JNI_OK){ CCLog("Failed to get the environment using GetEnv()"); break; } if (JAVAVM->AttachCurrentThread(env, 0) < 0){ CCLog("Failed to get the environment using AttachCurrentThrea d()"); break; } bRet = true; } while (0); return bRet; } // Method void CCGreeFriendCode::loadCode(){ loadCodeJni(); } bool CCGreeFriendCode::requestCode(const char* expireTime){ return requestCodeJni(expireTime); } void CCGreeFriendCode::deleteCode(){ deleteCodeJni(); } void CCGreeFriendCode::verifyCode(const char* code){ verifyCodeJni(code); } //void CCGreeFriendCode::loadFriends(int startIndex, int count){ void CCGreeFriendCode::loadFriendIds(int startIndex, int count){ loadFriendIdsJni(startIndex, count); } void CCGreeFriendCode::loadOwner(){ loadOwnerJni(); } // Callback Handling void CCGreeFriendCode::handleLoadCodeOnSuccess(void* code){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCGreeCode *pCode = new CCGreeCode(code); pCode->autorelease(); //TODO : Want to remove retain(). // But in such case, developer have to issue retain() by himself to use // object outside the function where it has gotten // Furthermore some of current callbacks are including correspoding // object information and to get them developer also have to issue retain() // not to be automatically released. pCode->retain(); delegate->loadCodeSuccess(pCode); } } void CCGreeFriendCode::handleLoadCodeOnFailure(int responseCode, const char*response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->loadCodeFailure(responseCode, str); } } void CCGreeFriendCode::handleRequestCodeOnSuccess(void* code){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCGreeCode *pCode = new CCGreeCode(code); pCode->autorelease(); //TODO : Want to remove retain(). // But in such case, developer have to issue retain() by himself to use // object outside the function where it has gotten // Furthermore some of current callbacks are including correspoding // object information and to get them developer also have to issue retain() // not to be automatically released. pCode->retain(); delegate->requestCodeSuccess(pCode); } } void CCGreeFriendCode::handleRequestCodeOnFailure(int responseCode, const char*response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->requestCodeFailure(responseCode, str); } } void CCGreeFriendCode::handleDeleteCodeOnSuccess(){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ delegate->deleteCodeSuccess(); } } void CCGreeFriendCode::handleDeleteCodeOnFailure(int responseCode, const char*response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->deleteCodeFailure(responseCode, str); } } void CCGreeFriendCode::handleVerifyCodeOnSuccess(){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ delegate->verifyCodeSuccess(); } } void CCGreeFriendCode::handleVerifyCodeOnFailure(int responseCode, const char* response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->verifyCodeFailure(responseCode, str); } } void CCGreeFriendCode::handleLoadFriendIdsOnSuccess(int startIndex, int itemsPerPage, int totalResults, void **entries){ CCArray *dataArray = new CCArray(); for(int i = 0; i < totalResults; i++){ CCGreeData *data = new CCGreeData(entries[i]); data->autorelease(); //TODO : Want to remove retain(). // But in such case, developer have to issue retain() by himself to use // object outside the function where it has gotten // Furthermore some of current callbacks are including correspoding // object information and to get them developer also have to issue retain() // not to be automatically released. data->retain(); dataArray->addObject(data); } CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ delegate->loadFriendIdsSuccess(startIndex, itemsPerPage, totalResults, dataArray); } } void CCGreeFriendCode::handleLoadFriendIdsOnFailure(int responseCode, const char* response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->loadFriendIdsFailure(responseCode, str); } } void CCGreeFriendCode::handleLoadOwnerOnSuccess(void* owner){ CCGreeData *data = NULL; if(owner != NULL){ data = new CCGreeData(owner); data->autorelease(); //TODO : Want to remove retain(). // But in such case, developer have to issue retain() by himself to use // object outside the function where it has gotten // Furthermore some of current callbacks are including correspoding // object information and to get them developer also have to issue retain() // not to be automatically released. data->retain(); } CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ delegate->loadOwnerSuccess(data); } } void CCGreeFriendCode::handleLoadOwnerOnFailure(int responseCode, const char* response){ CCGreeFriendCodeDelegate *delegate = CCGreePlatform::getFriendCodeDelegate(); if(delegate != NULL){ CCString *str = new CCString(response); str->autorelease(); delegate->loadOwnerFailure(responseCode, str); } } // CCGreeCode CCGreeCode::CCGreeCode(void* code){ JNIEnv *pEnv = 0; getEnv(&pEnv); mGreeCode = (void *)(pEnv->NewGlobalRef((jobject)code)); } CCGreeCode::~CCGreeCode(){ JNIEnv *pEnv = 0; getEnv(&pEnv); pEnv->DeleteGlobalRef((jobject)mGreeCode); } CCString *CCGreeCode::getCode(){ CALL_JNI_STRING_METHOD_WITHOBJECT(getCode, mGreeCode); } CCString *CCGreeCode::getExpireTime(){ CALL_JNI_STRING_METHOD_WITHOBJECT(getExpireTime, mGreeCode); } // CCGreeData CCGreeData::CCGreeData(void *data){ JNIEnv *pEnv = 0; getEnv(&pEnv); mGreeData = (void *)(pEnv->NewGlobalRef((jobject)data)); } CCGreeData::~CCGreeData(){ JNIEnv *pEnv = 0; getEnv(&pEnv); pEnv->DeleteGlobalRef((jobject)mGreeData); } CCString *CCGreeData::getUserId(){ CALL_JNI_STRING_METHOD_WITHOBJECT(getUserIdFromGreeData, mGreeData); } NS_CC_GREE_EXT_END
// Created on: 1997-01-03 // Created by: Christian CAILLET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepData_PDescr_HeaderFile #define _StepData_PDescr_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_Integer.hxx> #include <StepData_EnumTool.hxx> #include <Standard_Transient.hxx> #include <Standard_CString.hxx> class StepData_EDescr; class StepData_Field; class Interface_Check; class StepData_PDescr; DEFINE_STANDARD_HANDLE(StepData_PDescr, Standard_Transient) //! This class is intended to describe the authorized form for a //! parameter, as a type or a value for a field //! //! A PDescr firstly describes a type, which can be SELECT, i.e. //! have several members class StepData_PDescr : public Standard_Transient { public: Standard_EXPORT StepData_PDescr(); Standard_EXPORT void SetName (const Standard_CString name); Standard_EXPORT Standard_CString Name() const; //! Declares this PDescr to be a Select, hence to have members //! <me> itself can be the first member Standard_EXPORT void SetSelect(); //! Adds a member to a SELECT description Standard_EXPORT void AddMember (const Handle(StepData_PDescr)& member); //! Sets a name for SELECT member. To be used if a member is for //! an immediate type Standard_EXPORT void SetMemberName (const Standard_CString memname); //! Sets <me> for an Integer value Standard_EXPORT void SetInteger(); //! Sets <me> for a Real value Standard_EXPORT void SetReal(); //! Sets <me> for a String value Standard_EXPORT void SetString(); //! Sets <me> for a Boolean value (false,true) Standard_EXPORT void SetBoolean(); //! Sets <me> for a Logical value (false,true,unknown) Standard_EXPORT void SetLogical(); //! Sets <me> for an Enum value //! Then, call AddEnumDef ordered from the first one (value 0) Standard_EXPORT void SetEnum(); //! Adds an enum value as a string Standard_EXPORT void AddEnumDef (const Standard_CString enumdef); //! Sets <me> for an Entity which must match a Type (early-bound) Standard_EXPORT void SetType (const Handle(Standard_Type)& atype); //! Sets <me> for a Described Entity, whose Description must match //! the type name <dscnam> Standard_EXPORT void SetDescr (const Standard_CString dscnam); //! Adds an arity count to <me>, by default 1 //! 1 : a simple field passes to a LIST/ARRAY etc //! or a LIST to a LIST OF LIST //! 2 : a simple field passes to a LIST OF LIST Standard_EXPORT void AddArity (const Standard_Integer arity = 1); //! Directly sets the arity count //! 0 : simple field //! 1 : LIST or ARRAY etc //! 2 : LIST OF LIST Standard_EXPORT void SetArity (const Standard_Integer arity = 1); //! Sets <me> as <other> but duplicated //! Hence, some definition may be changed Standard_EXPORT void SetFrom (const Handle(StepData_PDescr)& other); //! Sets/Unsets <me> to accept undefined values Standard_EXPORT void SetOptional (const Standard_Boolean opt = Standard_True); //! Sets/Unsets <me> to be for a derived field Standard_EXPORT void SetDerived (const Standard_Boolean der = Standard_True); //! Sets <me> to describe a field of an entity //! With a name and a rank Standard_EXPORT void SetField (const Standard_CString name, const Standard_Integer rank); //! Tells if <me> is for a SELECT Standard_EXPORT Standard_Boolean IsSelect() const; //! For a SELECT, returns the member whose name matches <name> //! To this member, the following question can then be asked //! Null Handle if <name> not matched or <me> not a SELECT //! //! Remark : not to be asked for an entity type //! Hence, following IsInteger .. Enum* only apply on <me> and //! require Member //! While IsType applies on <me> and all Select Members Standard_EXPORT Handle(StepData_PDescr) Member (const Standard_CString name) const; //! Tells if <me> is for an Integer Standard_EXPORT Standard_Boolean IsInteger() const; //! Tells if <me> is for a Real value Standard_EXPORT Standard_Boolean IsReal() const; //! Tells if <me> is for a String value Standard_EXPORT Standard_Boolean IsString() const; //! Tells if <me> is for a Boolean value (false,true) Standard_EXPORT Standard_Boolean IsBoolean() const; //! Tells if <me> is for a Logical value (false,true,unknown) Standard_EXPORT Standard_Boolean IsLogical() const; //! Tells if <me> is for an Enum value //! Then, call AddEnumDef ordered from the first one (value 0) //! Managed by an EnumTool Standard_EXPORT Standard_Boolean IsEnum() const; //! Returns the maximum integer for a suitable value (count - 1) Standard_EXPORT Standard_Integer EnumMax() const; //! Returns the numeric value found for an enum text //! The text must be in capitals and limited by dots //! A non-suitable text gives a negative value to be returned Standard_EXPORT Standard_Integer EnumValue (const Standard_CString name) const; //! Returns the text which corresponds to a numeric value, //! between 0 and EnumMax. It is limited by dots Standard_EXPORT Standard_CString EnumText (const Standard_Integer val) const; //! Tells if <me> is for an Entity, either Described or CDL Type Standard_EXPORT Standard_Boolean IsEntity() const; //! Tells if <me> is for an entity of a given CDL type (early-bnd) //! (works for <me> + nexts if <me> is a Select) Standard_EXPORT Standard_Boolean IsType (const Handle(Standard_Type)& atype) const; //! Returns the type to match (IsKind), for a CDL Entity //! (else, null handle) Standard_EXPORT Handle(Standard_Type) Type() const; //! Tells if <me> is for a Described entity of a given EDescr //! (does this EDescr match description name ?). For late-bnd //! (works for <me> + nexts if <me> is a Select) Standard_EXPORT Standard_Boolean IsDescr (const Handle(StepData_EDescr)& descr) const; //! Returns the description (type name) to match, for a Described //! (else, empty string) Standard_EXPORT Standard_CString DescrName() const; //! Returns the arity of <me> Standard_EXPORT Standard_Integer Arity() const; //! For a LIST or LIST OF LIST, Returns the PDescr for the simpler //! PDescr. Else, returns <me> //! This allows to have different attributes for Optional for //! instance, on a field, and on the parameter of a LIST : //! [OPTIONAL] LIST OF [OPTIONAL] ... Standard_EXPORT Handle(StepData_PDescr) Simple() const; //! Tells if <me> is Optional Standard_EXPORT Standard_Boolean IsOptional() const; //! Tells if <me> is Derived Standard_EXPORT Standard_Boolean IsDerived() const; //! Tells if <me> is a Field. Else it is a Type Standard_EXPORT Standard_Boolean IsField() const; Standard_EXPORT Standard_CString FieldName() const; Standard_EXPORT Standard_Integer FieldRank() const; //! Semantic Check of a Field : does it complies with the given //! description ? Standard_EXPORT virtual void Check (const StepData_Field& afild, Handle(Interface_Check)& ach) const; DEFINE_STANDARD_RTTIEXT(StepData_PDescr,Standard_Transient) protected: private: Standard_EXPORT Standard_Integer Kind() const; TCollection_AsciiString thename; Standard_Integer thesel; TCollection_AsciiString thesnam; Handle(StepData_PDescr) thenext; Standard_Integer thekind; StepData_EnumTool theenum; Handle(Standard_Type) thetype; TCollection_AsciiString thednam; Standard_Integer thearit; Handle(StepData_PDescr) thefrom; Standard_Boolean theopt; Standard_Boolean theder; TCollection_AsciiString thefnam; Standard_Integer thefnum; }; #endif // _StepData_PDescr_HeaderFile
#include "SimpleList.h" #include <type_traits> template<class T> void destroy(T element) { // do nothing } template <class T> void destroy(T* element) { // delete the pointer type delete element; } template<class T> SimpleList<T>::SimpleList(){ numElements = 0; elements = new T[CAPACITY]; } template<class T> SimpleList<T>:: ~SimpleList(){ if (std::is_pointer<T>::value){ for(int i = 0; i < numElements; i++){ destroy(elements[i]); } } delete [] elements; } template <class T> T SimpleList<T>::at(int index) const throw (InvalidIndexException){ if(index<0 || index >=numElements){ InvalidIndexException i; throw i; } return elements[index]; } template <class T> bool SimpleList<T>::empty() const{ if(numElements == 0){ return true; } else return false; } template <class T> T SimpleList<T>::first() const throw(EmptyListException){ if(numElements == 0){ throw EmptyListException(); } else return elements[0]; } template <class T> T SimpleList<T>::last() const throw(EmptyListException){ if(numElements == 0){ throw EmptyListException(); } else return elements[numElements-1]; } template <class T> int SimpleList<T>::getNumElements() const{ return numElements; } template <class T> void SimpleList<T>::insert(T item) throw(FullListException){ if(numElements == CAPACITY){ throw FullListException(); } else{ elements[numElements] = item; numElements ++; } } template<class T> void SimpleList<T>:: remove(int index) throw(InvalidIndexException, EmptyListException){ if(numElements == 0){ throw EmptyListException(); } if(index >= numElements || index < 0){ throw InvalidIndexException(); } T temp = elements[index]; for(int i = index; i < numElements - 1 ; i++){ elements[i] = elements[i+1]; } elements[--numElements] = temp; destroy (elements[numElements]); }
/** * Implementation of KalmanFilter class. * * @author: Hayk Martirosyan * @date: 2014.11.15 */ #include <iostream> #include <stdexcept> #include "kalman.hpp" KalmanFilter::KalmanFilter( double dt, const Eigen::MatrixXd& A, const Eigen::MatrixXd& C, const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, const Eigen::MatrixXd& P) : A(A), C(C), Q(Q), R(R), P0(P), m(C.rows()), n(A.rows()), dt(dt), initialized(false), I(n, n), x_hat(n), x_hat_new(n) { I.setIdentity(); } KalmanFilter::KalmanFilter() {} void KalmanFilter::init(double t0, const Eigen::VectorXd& x0) { x_hat = x0; //P = P0; this->t0 = t0; t = t0; initialized = true; } void KalmanFilter::init() { x_hat.setZero(); P = P0; t0 = 0; t = t0; initialized = true; } void KalmanFilter::update(const Eigen::VectorXd& y) { if(!initialized) throw std::runtime_error("Filter is not initialized!"); x_hat_new = A * x_hat; P = A*P*A.transpose() + Q; K = P*C.transpose()*(C*P*C.transpose() + R).inverse(); x_hat_new += K * (y - C*x_hat_new); P = (I - K*C)*P; x_hat = x_hat_new; t += dt; } void KalmanFilter::update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A, const Eigen::MatrixXd C, const Eigen::MatrixXd Q) { this->A = A; this->C = C; this->Q = Q; this->dt = dt; update(y); } void KalmanFilter::fusionUp( double dt, const Eigen::VectorXd& y,const Eigen::MatrixXd& C,const Eigen::MatrixXd& R) { //this->R=R; int n = 9; // Number of states int m = 3; // Number of measurements Eigen::MatrixXd A(n, n); // System dynamics matrix Eigen::MatrixXd Q(n, n); // Process noise covariance // Update A A << 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1; // Update Q Q << pow(dt,6)/ 36, pow(dt,5) / 12, pow(dt,4) / 6,pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt, 6) / 36, pow(dt, 5) / 12, pow(dt,4) / 6, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt, 5)/ 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow (dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt ,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt, 4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,6) / 36,pow( dt,5) / 12, pow(dt,4) / 6, pow(dt, 6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt, 5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt ,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,4) / 6, pow(dt,3) / 2, pow(dt, 2), pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt, 4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,4) / 6, pow(dt,3) / 2, pow(dt, 2); // Update the filter update(y,dt,A,C,Q); } void KalmanFilter::fusionInit(double dt, const Eigen::VectorXd& y,const Eigen::MatrixXd& C,const Eigen::VectorXd& x) { int n = 9; // Number of states int m = 3; // Number of measurements Eigen::MatrixXd A(n, n); // System dynamics matrix Eigen::MatrixXd Q(n, n); // Process noise covariance Eigen::MatrixXd R(m, m); // Measurement noise covariance Eigen::MatrixXd P(n, n); // Estimate error covariance Eigen::MatrixXd I(n, n); // Estimate error covariance // Free object A << 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, dt, dt*dt/2, 0, 0, 0, 0, 0, 0, 0, 1, dt, 0, 0, 0, 0, 0, 0, 0, 0, 1; // Covariance matrices Q << pow(dt,6)/ 36, pow(dt,5) / 12, pow(dt,4) / 6,pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt, 6) / 36, pow(dt, 5) / 12, pow(dt,4) / 6, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt, 5)/ 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow (dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt ,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt, 4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,6) / 36,pow( dt,5) / 12, pow(dt,4) / 6, pow(dt, 6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt, 5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt ,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,4) / 6, pow(dt,3) / 2, pow(dt, 2), pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,6) / 36, pow(dt,5) / 12, pow(dt,4) / 6, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,5) / 12, pow(dt,4) / 4, pow(dt,3) / 3, pow(dt,4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt, 4) / 6, pow(dt,3) / 2, pow(dt,2), pow(dt,4) / 6, pow(dt,3) / 2, pow(dt, 2); R << 1, 0, 0, 0, 1, 0, 0, 0, 1; P << 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1; I<< 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1; // Construct the filter this->dt=dt; this->A=A; this->C=C; this->Q=Q; this->R=R; this->P=P; this->I=I; init(0,x); }
#include "errorhandler.h" #include "conversions.h" ErrorHandler::ErrorHandler(){ error = false; } ErrorHandler::ErrorHandler(string rTag){ error = false; rootTag = rTag; } void ErrorHandler::addError(string message, int code){ errorMsgs.push_back(message); errorCodes.push_back(code); error = true; } bool ErrorHandler::hasError(){ return error; } string ErrorHandler::toXML(){ string errorXML, rTag, errorCode; int i; if(rootTag == "") rTag = "Results"; else rTag = rootTag; errorXML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"; errorXML += "<"+rTag+"><Status>FAILURE</Status><Errors>"; for(i=0;i<errorMsgs.size();i++){ errorCode = convertitoa(errorCodes[i]); errorXML += "<Error>"; errorXML += "<Message>"+ errorMsgs[i] + "</Message>"; errorXML += "<Code>" + errorCode + "</Code>"; errorXML += "</Error>"; } errorXML += "</Errors></"+rTag+">"; return errorXML; } void ErrorHandler::setRootTag(string rTag){ rootTag = rTag; }
#include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <cstring> #include <cassert> #include <cctype> #include <string> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <algorithm> #include <functional> using namespace std; #define DEBUG(x) cout << '>' << #x << ':' << x << endl; #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; } const int INF = 1<<29; typedef long long ll; inline int two(int n) { return 1 << n; } inline int test(int n, int b) { return (n>>b)&1; } inline void set_bit(int & n, int b) { n |= two(b); } inline void unset_bit(int & n, int b) { n &= ~two(b); } inline int last_bit(int n) { return n & (-n); } inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res; } template<class T> void chmax(T & a, const T & b) { a = max(a, b); } template<class T> void chmin(T & a, const T & b) { a = min(a, b); } int main(){ int t; int count[105]; cin >> t; assert(t >= 1 and t <= 50); for(int i = 0; i < t; i++){ int n,k; cin >> n >> k; assert(n >= 1 and n <= 1000); assert(k >= 1 and k <= 1000); string str; for(int j = 0; j< n; j++){ cin >> str; count[str.length()]++; } bool flag = true; for(int j = 0; j < 100; j ++){ if(count[j] % k){ flag = false; break; } } if(flag){ cout << "Possible"<<"\n"; }else{ cout << "Not Possible"<<"\n"; } } return 0; }
#include <algorithm> #include <iostream> #include <string> using namespace std; int main() { string S; cin >> S; string ans = ""; while (!S.empty()) { if (S.length() % 2 == 0) { ans.push_back(S.back()); S.pop_back(); } else { ans.push_back(S.front()); S.erase(S.begin()); } } reverse(ans.begin(), ans.end()); cout << ans << endl; return 0; }
/* * µ¥Á´±íɾ³ýÖØ¸´ÔªËØ */ #include <bits/stdc++.h> using namespace std; struct ListNode{ int data; ListNode *next; ListNode(int x):data(x),next(NULL){} }; class Solution{ public: ListNode* delete_repeated_elements(ListNode *head){ if(head == NULL){ return head; } set<int> node_set; ListNode *prev = head; node_set.insert(prev->val); ListNode *headPtr = prev->next; while(headPtr){ if(node_set.find(headPtr->val) == node_set.end()){ node_set.insert(headPtr->val); headPtr = headPtr->next; prev = prev->next; }else{ prev->next = prev->next->next; headPtr = prev->next; } } return head; } }; int main(){ return 0; }
// // Created by Asicoder on 16/04/2019. // #include "Uva547.h"
#pragma once #include <iberbar/Network/Headers.h> #include <iberbar/Utility/Result.h> #include <string> #include <functional> #include <optional> namespace iberbar { namespace IO { class ISocketClient; struct USocketOptions; extern "C" { //__iberbarNetworkApis__ CResult Initial(); //__iberbarNetworkApis__ void Destroy(); //__iberbarNetworkApis__ void Read(); //__iberbarNetworkApis__ CResult CreateSocketClient( ISocketClient** ppOutClient, const char* strUrl, const USocketOptions* Options ); __iberbarNetworkApis__ CResult iberbarNetworkInitial(); __iberbarNetworkApis__ void iberbarNetworkDestroy(); __iberbarNetworkApis__ void iberbarNetworkRead(); CResult CreateSocketClient( ISocketClient** ppOutClient, const char* strUrl, const USocketOptions* Options ); } } }
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepVisual_PresentationSize_HeaderFile #define _StepVisual_PresentationSize_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepVisual_PresentationSizeAssignmentSelect.hxx> #include <Standard_Transient.hxx> class StepVisual_PlanarBox; class StepVisual_PresentationSize; DEFINE_STANDARD_HANDLE(StepVisual_PresentationSize, Standard_Transient) class StepVisual_PresentationSize : public Standard_Transient { public: //! Returns a PresentationSize Standard_EXPORT StepVisual_PresentationSize(); Standard_EXPORT void Init (const StepVisual_PresentationSizeAssignmentSelect& aUnit, const Handle(StepVisual_PlanarBox)& aSize); Standard_EXPORT void SetUnit (const StepVisual_PresentationSizeAssignmentSelect& aUnit); Standard_EXPORT StepVisual_PresentationSizeAssignmentSelect Unit() const; Standard_EXPORT void SetSize (const Handle(StepVisual_PlanarBox)& aSize); Standard_EXPORT Handle(StepVisual_PlanarBox) Size() const; DEFINE_STANDARD_RTTIEXT(StepVisual_PresentationSize,Standard_Transient) protected: private: StepVisual_PresentationSizeAssignmentSelect unit; Handle(StepVisual_PlanarBox) size; }; #endif // _StepVisual_PresentationSize_HeaderFile
#pragma once #include <vector> #include <string> #include <unordered_map> #include <iostream> #include <algorithm> #include "DocumentExtractor.h" #include "Tokenizer.h" #include "utility.h" typedef std::unordered_map<std::string, unsigned int> TFC_t; /// Structure représentant le contenu d'un document (un article de journal). struct DocumentData_t { std::string DOCNO; unsigned int DOCID = 0; Date_t DATE; // SECTION unsigned int LENGTH = 0; TFC_t HEADLINE; // BYLINE // DATELINE TFC_t TEXT; std::list<TFC_t> GRAPHICs; // TYPE TFC_t SUBJECT; // CORRECTION-DATE // CORRECTION }; /// Structure représentant le contenu d'un document (un article de journal) destiné à être converti en JSON. struct DocumentJSON_t { Date_t date; std::string title; std::vector<std::string> contents; }; /// Effectue les étapes de "stemming" et "stopword removal" sur un mot. Renvoit false si le mot doit être supprimé. bool stemming_stopword(std::string& word); /// Affiche les balises d'un arbre. (à n'utiliser qu'à des fins de débuggage uniquement) void print_tags(const DocumentTree_t& tag, const std::string& indent); /** * Extraie les tokens d'une chaîne (assez efficacement car aucune recopie de caractères n'est effectuée). * Retourne un std::vector contenant des string_view sur tous les tokens extraits. **/ std::vector<string_view> extractTokens(const std::string& data); /** * Extraie les tokens d'une chaîne (assez efficacement car aucune recopie de caractères n'est effectuée). * Appelle une fonction callback sur chaque token extrait. **/ template<class callback_t> void extractTokens(const std::string& data, callback_t callback) { Tokenizer tokenizer; string_view range(data); for (;;) { string_view part; if (!tokenizer.extract(range, part)) break; callback(part); range.begin = part.end; } } /// Extrait un document (un article de journal) d'un arbre de document XML. void extractDocumentData(DocumentTree_t& document_tree, DocumentData_t& document); /// Extrait un document (un article de journal) destiné à être converti en JSON d'un arbre de document XML. void extractDocumentJSON(DocumentTree_t& document_tree, DocumentJSON_t& documentJSON); /** * Consomme les documents (articles de journal) d'un arbre de document XML. * Appelle une fonction callback sur chaque document trouvé, et les supprime progressivement. **/ template<class callback_t> void consumeDocuments(DocumentTree_t& documents, callback_t callback) { for (auto it = documents.tags.begin(); it != documents.tags.end(); it = documents.tags.erase(it)) { if ((*it).name == "DOC") { callback(*it); } } } /// Retourne la représentation en JSON d'un document (un article de journal) destiné à être converti en JSON. std::ostream& operator <<(std::ostream &os, const DocumentJSON_t& document);
#ifndef REGULARGRID_H #define REGULARGRID_H #include "Grid.h" class RegularGrid : public Grid { Q_OBJECT public: explicit RegularGrid(QObject *parent = 0); ~RegularGrid(); static QString GetGridName() {return "Regular Grid";} PointCloudT *getCloudData(int row, int col); void run(); protected: int rows; int cols; QList<GridCell*> grid; public slots: void setNumRows(int rows); void setNumCols(int cols); }; #endif // REGULARGRID_H
#include <iostream> #include "Player.h" #include "Game.h" /// <summary> /// @author Peter Lowe /// @version 1.0 /// @date may 2016 /// /// </summary> Player::Player() { } //pete was hgere Player::~Player() { }
#include <string> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { // Invoke the Java program with the passed arguments. string cmd = "java -cp OthelloFramework.jar TestGame"; argv++; while (--argc) { cmd += " "; cmd += *(argv++); } return system(cmd.c_str()); }
// Measure pions! #include <iostream> #include <iomanip> // to set output precision. #include <cmath> #include <string> #include <sstream> #include <complex> #include <random> #include <cstring> // should be replaced by using sstream #include "generic_inverters.h" #include "generic_inverters_precond.h" #include "generic_vector.h" #include "verbosity.h" #include "u1_utils.h" using namespace std; // Define pi. #define PI 3.141592653589793 // Square staggered 2d operator w/ u1 function. void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data); struct staggered_u1_op { complex<double> *lattice; double mass; int x_fine; int y_fine; int Nc; // only relevant for square laplace. }; int main(int argc, char** argv) { // Declare some variables. cout << setiosflags(ios::scientific) << setprecision(6); int i, j, x, y; complex<double> *lattice; // Holds the gauge field. complex<double> *lhs, *rhs, *check; // For some Kinetic terms. double explicit_resid = 0.0; double bnorm = 0.0; std::mt19937 generator (1337u); // RNG, 1337u is the seed. inversion_info invif; staggered_u1_op stagif; // Set parameters. // L_x = L_y = Dimension for a square lattice. int square_size = 32; // Can be set on command line with --square_size. // Describe the staggered fermions. double MASS = 0.01; // Can be overridden on command line with --mass // Outer Inverter information. double outer_precision = 5e-7; int outer_restart = 256; // Gauge field information. double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta). // For heatbath gauge field, corresponds to non-compact beta. // Can be set on command line with --beta. ///////////////////////////////////////////// // Get a few parameters from command line. // ///////////////////////////////////////////// for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { cout << "--mass [mass] (default 1e-2)\n"; cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--square_size [32, 64, 128] (default 32)\n"; return 0; } if (i+1 != argc) { if (strcmp(argv[i], "--mass") == 0) { MASS = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--beta") == 0) { BETA = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--square_size") == 0) { square_size = atoi(argv[i+1]); i++; } } } //printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector); //return 0; /////////////////////////////////////// // End of human-readable parameters! // /////////////////////////////////////// string op_name; void (*op)(complex<double>*, complex<double>*, void*); op = square_staggered_u1; op_name = "Staggered U(1)"; cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n"; // Only relevant for free laplace test. int Nc = 1; // Only value that matters for staggered // Describe the fine lattice. int x_fine = square_size; int y_fine = square_size; int fine_size = x_fine*y_fine*Nc; cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine; cout << "\n"; // Do some allocation. // Initialize the lattice. Indexing: index = y*N + x. lattice = new complex<double>[2*fine_size]; lhs = new complex<double>[fine_size]; rhs = new complex<double>[fine_size]; check = new complex<double>[fine_size]; // Zero it out. zero<double>(lattice, 2*fine_size); zero<double>(rhs, fine_size); zero<double>(lhs, fine_size); zero<double>(check, fine_size); // // Fill stagif. stagif.lattice = lattice; stagif.mass = MASS; stagif.x_fine = x_fine; stagif.y_fine = y_fine; stagif.Nc = Nc; // Only relevant for laplace test only. // Create the verbosity structure. inversion_verbose_struct verb; verb.verbosity = VERB_SUMMARY; verb.verb_prefix = "[L1]: "; verb.precond_verbosity = VERB_DETAIL; verb.precond_verb_prefix = "Prec "; // Describe the gauge field. cout << "[GAUGE]: Creating a gauge field.\n"; unit_gauge_u1(lattice, x_fine, y_fine); if (x_fine == 32 && y_fine == 32) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l32t32bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 64 && y_fine == 64) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l64t64bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 128 && y_fine == 128) { if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../multigrid/aa_mg/cfg/l128t128bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, x_fine, y_fine) << ".\n"; double* corr = new double[y_fine]; double* corr2 = new double[y_fine]; for (y = 0; y < y_fine; y++) { corr[y] = corr2[y] = 0.0; } int count = 0; // Average over lots of RHS! for (y = 0; y < y_fine; y+=4) { for (x = 0; x < x_fine; x+=4) { cout << "x " << x << " y " << y << "\n"; count++; // Set source. zero<double>(rhs, fine_size); rhs[y*x_fine+x] = 1.0; bnorm = 1.0; // sqrt(norm2sq<double>(rhs, fine_size)); // Perform inversion. invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb); // Build up the correlator. for (i = 0; i < y_fine; i++) { double tmp = 0.0; for (j = 0; j < x_fine; j++) { tmp += real(conj(lhs[i*x_fine+j])*lhs[i*x_fine+j]); } corr[(i-y+y_fine)%y_fine] += tmp; corr2[(i-y+y_fine)%y_fine] += tmp*tmp; } } } cout << "BEGIN_GOLDSTONE\n"; for (i = 0; i < y_fine; i++) { cout << i << " " << corr[i]/count << " " << sqrt(1.0/(count*(count-1))*(corr2[i]/count-corr[i]*corr[i]/(count*count))) << "\n"; } cout << "END_GOLDSTONE\n"; delete[] corr; delete[] corr2; /* // Try a direct solve. cout << "\n[ORIG]: Solve fine system.\n"; invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb); //invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif); if (invif.success == true) { printf("[ORIG]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str()); } else // failed, maybe. { printf("[ORIG]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str()); printf("[ORIG]: This may be because the max iterations was reached.\n"); } printf("[ORIG]: Computing [check] = A [lhs] as a confirmation.\n"); // Check and make sure we get the right answer. zero<double>(check, fine_size); (*op)(check, lhs, (void*)&stagif); //square_staggered_u1(check, lhs, (void*)&stagif); explicit_resid = 0.0; for (i = 0; i < fine_size; i++) { explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i])); } explicit_resid = sqrt(explicit_resid)/bnorm; printf("[ORIG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid); // Look at the two point function! double* corr = new double[y_fine]; cout << "BEGIN_GOLDSTONE\n"; for (i = 0; i < y_fine; i++) { corr[i] = 0.0; for (j = 0; j < x_fine; j++) { corr[i] += real(conj(lhs[i*x_fine+j])*lhs[i*x_fine+j]); } cout << i << " " << corr[i] << "\n"; } cout << "END_GOLDSTONE\n"; cout << "BEGIN_EFFMASS\n"; for (i = 0; i < y_fine; i++) { cout << i << " " << log(corr[i]/corr[(i+1)%y_fine]) << "\n"; } cout << "END_EFFMASS\n"; */ // Free the lattice. delete[] lattice; delete[] lhs; delete[] rhs; delete[] check; return 0; } // Square lattice. // Kinetic term for a 2D staggered w/ period bc. Applies lhs = A*rhs. // The unit vectors are e_1 = xhat, e_2 = yhat. // The "extra_data" is a cast to a complex gauge_field[N*N*2], // loaded by the function read_lattice_u1. // Apsi[x][y] = m psi[x,y] - U[y][x,x+1] void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data) { // Declare variables. int i; int x,y; double eta1; staggered_u1_op* stagif = (staggered_u1_op*)extra_data; complex<double>* lattice = stagif->lattice; double mass = stagif->mass; int x_fine = stagif->x_fine; int y_fine = stagif->y_fine; // For a 2D square lattice, the stencil is: // 1 | 0 -eta1 0 | // - | +1 0 -1 | , where eta1 = (-1)^x // 2 | 0 +eta1 0 | // // e2 = yhat // ^ // | // |-> e1 = xhat // Apply the stencil. for (i = 0; i < x_fine*y_fine; i++) { lhs[i] = 0.0; x = i%x_fine; // integer mod. y = i/x_fine; // integer divide. eta1 = 1 - 2*(x%2); // + e1. lhs[i] = lhs[i]-lattice[y*x_fine*2+x*2]*rhs[y*x_fine+((x+1)%x_fine)]; // - e1. lhs[i] = lhs[i]+ conj(lattice[y*x_fine*2+((x+x_fine-1)%x_fine)*2])*rhs[y*x_fine+((x+x_fine-1)%x_fine)]; // The extra +N is because of the % sign convention. // + e2. lhs[i] = lhs[i]- eta1*lattice[y*x_fine*2+x*2+1]*rhs[((y+1)%y_fine)*x_fine+x]; // - e2. lhs[i] = lhs[i]+ eta1*conj(lattice[((y+y_fine-1)%y_fine)*x_fine*2+x*2+1])*rhs[((y+y_fine-1)%y_fine)*x_fine+x]; // Normalization. lhs[i] = 0.5*lhs[i]; // 0 // Added mass term here. lhs[i] = lhs[i]+ mass*rhs[i]; // Apply a gamma5. /*if ((x+y)%2 == 1) { lhs[i] = -lhs[i]; }*/ } }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2004-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * author: Patryk Obara */ #include "core/pch.h" #ifdef WIDGET_RUNTIME_SUPPORT #include "adjunct/desktop_util/shortcuts/DesktopShortcutInfo.h" #include "adjunct/widgetruntime/pi/PlatformGadgetUtils.h" #include "modules/util/opfile/opfile.h" #include "platforms/unix/base/common/desktop_entry.h" // TODO: // - use path.h function (!) // - check what happens, when directories does not exist DesktopEntry::DesktopEntry() : m_shortcut_info(NULL) { } OP_STATUS DesktopEntry::Init(const DesktopShortcutInfo& shortcut_info) { if (DesktopShortcutInfo::SC_DEST_MENU != shortcut_info.m_destination) { OP_ASSERT(!"Unsupported shortcut destination"); return OpStatus::ERR_NOT_SUPPORTED; } m_shortcut_info = &shortcut_info; RETURN_IF_ERROR(PreparePath()); return OpStatus::OK; } OP_STATUS DesktopEntry::Deploy() { //printf("[%i]", info->dest); OP_ASSERT(m_shortcut_info); OP_ASSERT(m_path.HasContent()); OpFile file; RETURN_IF_ERROR(file.Construct(m_path)); RETURN_IF_ERROR(file.Open(OPFILE_OVERWRITE)); // desktop entry content: RETURN_IF_ERROR(file.WriteUTF8Line(UNI_L("[Desktop Entry]"))); RETURN_IF_ERROR(file.WriteUTF8Line(UNI_L("Version=1.0"))); OpString type; RETURN_IF_ERROR(type.SetConcat(UNI_L("Type="), m_shortcut_info->m_type)); RETURN_IF_ERROR(file.WriteUTF8Line(type)); OpString generic_name; RETURN_IF_ERROR(generic_name.SetConcat(UNI_L("GenericName="), m_shortcut_info->m_generic_name)); RETURN_IF_ERROR(file.WriteUTF8Line(generic_name)); OpString name; RETURN_IF_ERROR(name.SetConcat(UNI_L("Name="), m_shortcut_info->m_name)); RETURN_IF_ERROR(file.WriteUTF8Line(name)); OpString exec; RETURN_IF_ERROR(exec.SetConcat(UNI_L("Exec="), m_shortcut_info->m_command)); RETURN_IF_ERROR(file.WriteUTF8Line(exec)); OpString tmpExec; PlatformGadgetUtils::GetOperaExecPath(tmpExec); OpString try_exec_string; try_exec_string.SetConcat(UNI_L("TryExec="), tmpExec); RETURN_IF_ERROR(file.WriteUTF8Line(try_exec_string)); // setting icon OpString icon; RETURN_IF_ERROR(icon.SetConcat(UNI_L("Icon="), m_shortcut_info->m_icon_name)); RETURN_IF_ERROR(file.WriteUTF8Line(icon)); // no support for categories from widget spec means no categories here // RETURN_IF_ERROR(file.WriteUTF8Line(UNI_L("Categories=Application;Network"))); // end of desktop entry file content return OpStatus::OK; } OP_STATUS DesktopEntry::Remove() { OpFile file; RETURN_IF_ERROR(file.Construct(m_path)); RETURN_IF_ERROR(file.Delete()); return OpStatus::OK; } OP_STATUS DesktopEntry::PreparePath() { OP_ASSERT(m_shortcut_info); switch (m_shortcut_info->m_destination) { case DesktopShortcutInfo::SC_DEST_MENU: { const char* xdg = getenv("XDG_DATA_HOME"); if(xdg) { RETURN_IF_ERROR(m_path.Set(xdg)); } else { RETURN_IF_ERROR(m_path.Set(getenv("HOME"))); RETURN_IF_ERROR(m_path.Append(UNI_L("/.local/share"))); } // in data direcory, .desktop files of any kind can appear, // but in certain locations RETURN_IF_ERROR(m_path.AppendFormat( UNI_L("/applications/%s.desktop"), m_shortcut_info->m_file_name.CStr())); /* Disabling desktop entry type handling. We only support Application, anyway. -- wdzierzanowski if(info->type == "Application") { path.AppendFormat(UNI_L("/applications/%s.desktop"), normalized_name.CStr()); } else if(info->type == "Directory") { path.AppendFormat(UNI_L("/desktop-directories/%s.directory"), normalized_name.CStr()); } else if(info->type == "Link") { path.AppendFormat(UNI_L("/%s.desktop"), normalized_name.CStr()); } */ } break; default: OP_ASSERT(!"shortcut destination not supported on platform!"); break; } #ifdef DEBUG // printf("desktop entry location: %s\n", uni_down_strdup(m_path.CStr())); #endif return OpStatus::OK; } #endif // WIDGET_RUNTIME_SUPPORT
#ifndef GAME_H_INCLUDED #define GAME_H_INCLUDED #include "Board.h" #include "BasePiece.h" #include <cstring> class Game { private: std::string input1, input2; //user input Color colorOnTurn; bool moveSucceed; Position moveFrom; Position moveTo; void displayIntro(); void displayInstructions(); void toLowerCaseInput(std::string* str); bool isValidInput(); public: Game(); virtual ~Game(); void startNewGame(); }; #endif // GAME_H_INCLUDED
#include<stdio.h> int main() { int a = 0,b = 0,c = 0,i,j; int A[4][5]; for(i=0;i<5;i++) { for(j=0;j<4;j++) { scanf_s("%d",&A[j][i]); } } for(i=0;i<5;i++) { for(j=0;j<4;j++) { a = a + A[j][i]; } if(a > c) { c = a; b = i + 1; } a = 0; } printf("%d %d",b,c); return 0; }
#include <iostream> #include <string> using namespace std; int main() { int N, num = 1, area = 1; cin >> N; while(true){ if(N <= num) break; num += area * 6; area++; } cout << area; return 0; }
// // Created by 钟奇龙 on 2019-05-10. // #include <iostream> #include <string> #include <vector> using namespace std; /* * 括号字符串的有效性 */ bool isValid(string s){ int status = 0; for(int i=0; i<s.size(); ++i){ if(s[i] != '(' && s[i] != ')'){ return false; } if(s[i] == ')' && --status < 0){ return false; } if(s[i] == '('){ status++; } } return status == 0; } /* * 括号字符串的最长有效长度 */ int maxLength(string s){ if(s.size() == 0) return 0; vector<int> dp(s.size(),0); int res = 0; for(int i=1; i<s.size(); ++i){ if(s[i] == ')'){ int pre = i - dp[i-1] - 1; if(pre >= 0 && s[pre] == '('){ dp[i] = 2 + dp[i-1] + (dp[pre-1] > 0 ? dp[pre-1]:0); } } res = max(res,dp[i]); } return res; } int main(){ string s = "()()("; cout<<isValid(s)<<endl; cout<<maxLength(s)<<endl; string s2 = "()(()()("; cout<<maxLength(s2)<<endl; return 0; }
// https://oj.leetcode.com/problems/word-search/ class Solution { int M; int N; bool dfs(vector<vector<char> > &board, string &word, int str_idx, int row, int col, vector<vector<bool> > &visited) { if (str_idx == word.size()) { return true; } if (row < 0 || row >= M || col < 0 || col >= N) { return false; } if (word[str_idx] != board[row][col]) { return false; } if (visited[row][col]) { return false; } visited[row][col] = true; bool ret = (dfs(board, word, str_idx + 1, row + 1, col, visited) || dfs(board, word, str_idx + 1, row - 1, col, visited) || dfs(board, word, str_idx + 1, row, col + 1, visited) || dfs(board, word, str_idx + 1, row, col - 1, visited)); visited[row][col] = false; return ret; } public: bool exist(vector<vector<char> > &board, string word) { M = board.size(); if (M == 0) { return false; } N = board[0].size(); if (N == 0 || word.empty()) { return true; } vector<vector<bool> > visited(M, vector<bool>(N, false)); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (dfs(board, word, 0, i, j, visited)) { return true; } } } return false; } };
#include "float.hpp" #include <cstdlib> #include <cmath> namespace geometry { Float::Float() { this->value = 0.0; } Float::Float(Float* a) { this->value = a->getValue(); } Float::Float(long double val) { this->value = val; } Float::Float(std::string s) { //return "Float {" + std::to_string(value) + "}"; int i = 0; while(s[i++ + 1] != '{'); this->value = std::stold(s.substr(i)); } Float::Float(Object* obj) { this->value = Float(obj->toString()).getValue(); } Float::~Float() { } long double Float::getValue() { return value; } void Float::setValue(long double value) { this->value = value; } Float Float::operator +(Float n) { return Float(this->value + n.getValue()); } Float Float::operator +() { return Float(this->value); } Float Float::operator -(Float n) { return Float(this->value - n.getValue()); } Float Float::operator -() { return Float(-this->value); } Float Float::operator *(Float n) { return Float(this->value * n.getValue()); } Float Float::operator /(Float n) { return Float(this->value / n.getValue()); } Boolean Float::operator >(Float a) { return Boolean(getValue() > a.getValue()); } Boolean Float::operator <(Float a) { return Boolean(getValue() < a.getValue()); } Boolean Float::operator >=(Float a) { return Boolean(getValue() >= a.getValue()); } Boolean Float::operator <=(Float a) { return Boolean(getValue() <= a.getValue()); } Boolean Float::operator ==(Float a) { return Boolean(new Float(std::abs(getValue() - a.getValue())) < EPS); } Boolean Float::operator !=(Float a) { return Boolean(new Float(std::abs(getValue() - a.getValue())) > EPS); } Float Float::operator +=(Float n) { return Float(this->getValue() + n.getValue()); } Float Float::operator -=(Float n) { return Float(this->getValue() - n.getValue()); } Float Float::operator *=(Float n) { return Float(this->getValue() * n.getValue()); } Float Float::operator /=(Float n) { return Float(this->getValue() / n.getValue()); } Float* Float::operator *() { return new Float(this->getValue()); } void Float::operator =(Float* a) { this->value = a->getValue(); } Float* pow(Float* f, Float* n) { return new Float(std::pow(f->getValue(), n->getValue())); } Float* sqr(Float* f) { return new Float(std::sqrt(f->getValue())); } Float* sqrt(Float* f) { return new Float(std::sqrt(f->getValue())); } Float* abs(Float* f) { return new Float(std::abs(f->getValue())); } Float* cos(Float* f) { return new Float(std::cos(f->getValue())); } Float* sin(Float* f) { return new Float(std::sin(f->getValue())); } Float* tan(Float* f) { return new Float(std::tan(f->getValue())); } Float* acos(Float* f) { return new Float(std::acos(f->getValue())); } Float* asin(Float* f) { return new Float(std::asin(f->getValue())); } Float* atan(Float* f) { return new Float(std::atan(f->getValue())); } Float* min(Float* a, Float* b) { if ((*a > *b).getBoolean()) return b; return a; } Float* max(Float* a, Float* b) { if ((*a > *b).getBoolean()) return a; return b; } Float pow(Float f, Float n) { return Float(std::pow(f.getValue(), n.getValue())); } Float sqr(Float f) { return Float(std::sqrt(f.getValue())); } Float sqrt(Float f) { return Float(std::sqrt(f.getValue())); } Float abs(Float f) { return Float(std::abs(f.getValue())); } Float cos(Float f) { return Float(std::cos(f.getValue())); } Float sin(Float f) { return Float(std::sin(f.getValue())); } Float tan(Float f) { return Float(std::tan(f.getValue())); } Float acos(Float f) { return Float(std::acos(f.getValue())); } Float asin(Float f) { return Float(std::asin(f.getValue())); } Float atan(Float f) { return Float(std::atan(f.getValue())); } Float min(Float a, Float b) { if ((a > b).getBoolean()) return b; return a; } Float max(Float a, Float b) { if ((a > b).getBoolean()) return a; return b; } std::string Float::toString() { return "Float {" + std::to_string(value) + "}"; } Float* toFloat(std::string ld) { return new Float(std::stold(ld)); } std::string Float::getType() { return "Float"; } Object* Float::parse(std::__cxx11::string command, std::vector<Object*> params) { } }
#ifndef WORKER_POOL_H #define WORKER_POOL_H #include <SDL2/SDL.h> template <class T, int N> constexpr int ArrayLength(const T (&a)[N]) { return N; } struct WorkerPool { struct Work { void (*fn)(void *); void *data; }; static_assert(sizeof(int) >= 4, "int is less than 32 bits!"); SDL_atomic_t front_back; SDL_atomic_t unfinished; SDL_sem *sem; SDL_Thread *workers[7]; Work que[128]; static Work *PopWork(WorkerPool *pool) { uint32_t workIndex = 0; while (1) { int val0 = SDL_AtomicGet(&pool->front_back); uint32_t tmp = *(uint32_t *)&val0; workIndex = tmp & 0xffff; tmp &= 0xffff0000; tmp |= ((workIndex + 1) % ArrayLength(pool->que)); int val = *(int *)&tmp; if (SDL_AtomicCAS(&pool->front_back, val0, val)) { break; } } return pool->que + workIndex; } static int WorkerThread(void *data) { WorkerPool *pool = (WorkerPool *)data; while (SDL_SemWait(pool->sem) == 0) { Work *work = PopWork(pool); if (work->fn == 0) { break; } work->fn(work->data); SDL_AtomicAdd(&pool->unfinished, -1); } return 0; } WorkerPool() { SDL_AtomicSet(&front_back, 0); SDL_AtomicSet(&unfinished, 0); sem = SDL_CreateSemaphore(0); for (int i = 0; i < ArrayLength(workers); i++) { workers[i] = SDL_CreateThread(&WorkerThread, "worker", this); } } ~WorkerPool() { JoinAll(); SDL_DestroySemaphore(sem); } void JoinAll() { for (int i = 0; i < ArrayLength(workers); i++) { PushWork(0, (void *)0); } for (int i = 0; i < ArrayLength(workers); i++) { SDL_WaitThread(workers[i], 0); workers[i] = 0; } } bool TryPushWork(void (*fn)(void *), void *data) { uint32_t workIndex = 0; while (1) { int val0 = SDL_AtomicGet(&front_back); uint32_t tmp = *(uint32_t *)&val0; workIndex = (tmp >> 16); tmp &= 0x0000ffff; // assert(((workIndex + 1) % ArrayLength(que)) != tmp); if (((workIndex + 1) % ArrayLength(que)) == tmp) { return false; } tmp |= (((workIndex + 1) % ArrayLength(que)) << 16); int val = *(int *)&tmp; if (SDL_AtomicCAS(&front_back, val0, val)) { break; } } SDL_AtomicAdd(&unfinished, 1); Work *work = que + workIndex; work->fn = fn; work->data = data; SDL_SemPost(sem); return true; } bool TryPushWork(void (*fn)(void *), const void *data) { return TryPushWork(fn, (void *)data); } void PushWork(void (*fn)(void *), void *data) { while (!TryPushWork(fn, data)); } void PushWork(void (*fn)(void *), const void *data) { PushWork(fn, (void *)data); } bool TryToWork() { if (SDL_SemTryWait(sem) == 0) { Work *work = PopWork(this); // assert(work->fn != 0); if (work->fn == 0) { PushWork(work->fn, work->data); return false; } work->fn(work->data); SDL_AtomicAdd(&unfinished, -1); return true; } return false; } void FinishQue() { while (TryToWork()); while (SDL_AtomicGet(&unfinished) > 0); } int GetInQueWorkCount() { return SDL_SemValue(sem); } int GetUnfinishedWorkCount() { return SDL_AtomicGet(&unfinished); } }; #endif // WORKER_POOL_H
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "execution_manager.hpp" #include <algorithm> #include <chrono> #include <iostream> #include <memory> #include "query_scheduling_helper.hpp" using orkhestrafs::core::core_execution::ExecutionManager; using orkhestrafs::dbmstodspi::QuerySchedulingHelper; auto ExecutionManager::IsSWBackupEnabled() -> bool { return config_.enable_sw_backup; } auto ExecutionManager::IsHWPrintEnabled() -> bool { return print_hw_; } void ExecutionManager::LoadBitstream(ScheduledModule new_module) { auto dma_module = accelerator_library_->GetDMAModule(); memory_manager_->LoadPartialBitstream({new_module.bitstream}, *dma_module); query_manager_->GetPRBitstreamsToLoadWithPassthroughModules( current_configuration_, {new_module}, current_routing_); } auto ExecutionManager::GetCurrentHW() -> std::map<QueryOperationType, OperationPRModules> { return config_.pr_hw_library; } void ExecutionManager::SetHWPrint(bool print_hw) { print_hw_ = print_hw; } void ExecutionManager::SetStartTimer() { exec_begin = std::chrono::steady_clock::now(); } void ExecutionManager::PrintExecTime() { std::cout << "EXEC TIME: " << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - exec_begin) .count() << " ms" << std::endl; } void ExecutionManager::AddNewNodes(std::string graph_filename) { unscheduled_graph_ = graph_creator_->MakeGraph(graph_filename, std::move(unscheduled_graph_)); } void ExecutionManager::LoadStaticTables() { if (config_.static_tables.empty()) { throw std::runtime_error("No static tables given!"); } for (const auto& table_name : config_.static_tables) { current_tables_metadata_.insert( {table_name, config_.initial_all_tables_metadata.at(table_name)}); // 100 is an arbitrary number. 1 could work as well. table_counter_.insert({table_name, 100}); if (table_memory_blocks_.find(table_name) == table_memory_blocks_.end()) { table_memory_blocks_[table_name] = memory_manager_->GetAvailableMemoryBlock(); data_manager_->WriteDataFromCSVToMemory( table_name, config_.static_tables_columns.at(table_name), table_memory_blocks_[table_name]); } } } void ExecutionManager::SetInteractive(bool is_interactive) { is_interactive_ = is_interactive; } auto ExecutionManager::IsInteractive() -> bool { return is_interactive_; } void ExecutionManager::ChangeSchedulingTimeLimit(double new_time_limit) { config_.scheduler_time_limit_in_seconds = new_time_limit; } void ExecutionManager::ChangeExecutionTimeLimit(int new_time_limit) { config_.execution_timeout = new_time_limit; } void ExecutionManager::PrintHWState() { std::cout << "==CURRENT CONFIGURATION==" << std::endl; std::string dma_string = "MMDBMMDMDMDB"; for (const auto resource : dma_string) { std::cout << "X(" << resource << "): DMA" << std::endl; } for (int i = 0; i < current_routing_.size(); i++) { std::cout << i << "(" << config_.resource_string.at(i) << "): " << current_routing_.at(i) << std::endl; } std::cout << "=========================" << std::endl; std::string wait; std::cin >> wait; } auto ExecutionManager::GetFPGASpeed() -> int { return config_.clock_speed; } void ExecutionManager::SetFinishedFlag() { busy_flag_ = false; } void ExecutionManager::UpdateAvailableNodesGraph() { current_available_node_pointers_.clear(); if (!processed_nodes_.empty()) { unscheduled_graph_->DeleteNodes(processed_nodes_); processed_nodes_.clear(); } current_available_node_pointers_ = unscheduled_graph_->GetRootNodesPtrs(); current_available_node_names_.clear(); for (const auto& node : current_available_node_pointers_) { current_available_node_names_.insert(node->node_name); } RemoveUnusedTables(current_tables_metadata_, unscheduled_graph_->GetAllNodesPtrs(), config_.static_tables); table_counter_.clear(); for (const auto table_name : config_.static_tables) { table_counter_.insert({table_name, 100}); } InitialiseTables(current_tables_metadata_, current_available_node_pointers_, query_manager_.get(), data_manager_.get()); current_query_graph_.clear(); SetupTableDependencies(unscheduled_graph_->GetAllNodesPtrs(), blocked_nodes_, table_counter_); SetupSchedulingGraphAndConstrainedNodes( unscheduled_graph_->GetAllNodesPtrs(), current_query_graph_, *accelerator_library_, nodes_constrained_to_first_, current_tables_metadata_); } void ExecutionManager::SetupTableDependencies( const std::vector<QueryNode*>& all_nodes, std::unordered_set<std::string>& blocked_nodes, std::unordered_map<std::string, int>& table_counter) { blocked_nodes.clear(); std::unordered_set<std::string> output_tables; for (const auto& node : all_nodes) { for (const auto& output : node->given_output_data_definition_files) { if (!output.empty()) { output_tables.insert(output); } } } std::unordered_set<QueryNode*> nodes_to_check; // we want to block all nodes that have an input that is the output of // something else But nodes that have this condition and are linked do not get // blocked! for (const auto& node : all_nodes) { for (int i = 0; i < node->given_input_data_definition_files.size(); i++) { const auto& input_table = node->given_input_data_definition_files.at(i); const auto& input_node = node->previous_nodes.at(i); if (!input_table.empty() && output_tables.find(input_table) != output_tables.end()) { if (!input_node || std::none_of( input_node->given_output_data_definition_files.begin(), input_node->given_output_data_definition_files.end(), [&](auto table_name) { return input_table == table_name; })) { blocked_nodes.insert(node->node_name); nodes_to_check.insert(node); } } } } // To prevent blocked tables from being deleted while (!nodes_to_check.empty()) { auto cur_node = *nodes_to_check.begin(); nodes_to_check.erase(nodes_to_check.begin()); for (const auto& input_table : cur_node->given_input_data_definition_files) { if (!input_table.empty()) { table_counter.insert({input_table, 1}); } } for (const auto& output_node : cur_node->next_nodes) { if (output_node) { nodes_to_check.insert(output_node); } } } // If we want to be more precise /*std::unordered_map<std::string, std::unordered_set<std::string>> tables_to_nodes_used_map; for (const auto& node : all_nodes) { for (const auto& input : node->given_input_data_definition_files) { if (!input.empty()) { std::unordered_set<std::string> new_set = {node->node_name}; if (const auto& [it, inserted] = tables_to_nodes_used_map.try_emplace(input, new_set); !inserted) { it->second.merge(new_set); } } } } for (const auto& node : all_nodes) { for (int i = 0; i < node->given_output_data_definition_files.size(); i++) { const auto& output = node->given_output_data_definition_files.at(i); if (!output.empty()) { if (node->is_checked.at(i) && input_tables.find(output) != input_tables.end() && tables_metadata.find(output) != tables_metadata.end()) { tables_metadata.at(output).is_finished = false; } } } }*/ /*std::unordered_set<std::string> input_tables; for (const auto& node : all_nodes) { for (const auto& input : node->given_input_data_definition_files) { if (!input.empty()) { input_tables.insert(input); } } } for (const auto& node : all_nodes) { for (int i = 0; i < node->given_output_data_definition_files.size(); i++) { const auto& output = node->given_output_data_definition_files.at(i); if (!output.empty()) { if (node->is_checked.at(i) && input_tables.find(output) != input_tables.end() && tables_metadata.find(output) != tables_metadata.end()) { tables_metadata.at(output).is_finished = false; } } } }*/ } void ExecutionManager::RemoveUnusedTables( std::map<std::string, TableMetadata>& tables_metadata, const std::vector<QueryNode*>& all_nodes, const std::vector<std::string> frozen_tables) { // TODO(Kaspar): Possibly reserve some space beforehand. std::unordered_set<std::string> required_tables; std::unordered_set<std::string> output_tables; for (const auto& node : all_nodes) { for (const auto& input : node->given_input_data_definition_files) { if (!input.empty()) { required_tables.insert(input); } } for (const auto& output : node->given_output_data_definition_files) { if (!output.empty()) { required_tables.insert(output); output_tables.insert(output); } } } std::vector<std::string> tables_to_delete; auto missing_tables = required_tables; for (const auto& [table_name, data] : tables_metadata) { missing_tables.erase(table_name); if (required_tables.find(table_name) == required_tables.end()) { tables_to_delete.push_back(table_name); } } for (const auto& output : output_tables) { missing_tables.erase(output); } if (!missing_tables.empty()) { throw std::runtime_error( "There are tables required that are not available!"); } // TODO: Should be set for (const auto& frozen_table : frozen_tables) { tables_to_delete.erase(std::remove(tables_to_delete.begin(), tables_to_delete.end(), frozen_table), tables_to_delete.end()); } for (const auto& table_to_delete : tables_to_delete) { tables_metadata.erase(table_to_delete); } } // Initially only input nodes have input tables defined. // This method names all the rest of the tables. void ExecutionManager::InitialiseTables( std::map<std::string, TableMetadata>& tables_metadata, std::vector<QueryNode*> current_available_node_pointers, const QueryManagerInterface* query_manager, const DataManagerInterface* data_manager) { // Setup new unintialised tables while (!current_available_node_pointers.empty()) { auto* current_node = current_available_node_pointers.back(); current_available_node_pointers.pop_back(); if (std::any_of(current_node->given_input_data_definition_files.begin(), current_node->given_input_data_definition_files.end(), [](const auto& filename) { return filename.empty(); })) { throw std::runtime_error("Table initialisation has an empty table!"); } for (int output_stream_id = 0; output_stream_id < current_node->next_nodes.size(); output_stream_id++) { auto& table_name = current_node->given_output_data_definition_files.at(output_stream_id); if (table_name.empty()) { table_name = current_node->node_name + "_" + std::to_string(output_stream_id); TableMetadata new_data; new_data.record_size = query_manager->GetRecordSizeFromParameters( data_manager, current_node->given_operation_parameters.output_stream_parameters, output_stream_id); // Hardcoded for benchmarking // new_data.record_size = 10; new_data.record_count = -1; tables_metadata.insert({table_name, new_data}); } const auto& output_node = current_node->next_nodes.at(output_stream_id); if (output_node) { int index = GetCurrentNodeIndexFromNextNode(current_node, output_node); if (output_node->given_input_data_definition_files.at(index).empty()) { output_node->given_input_data_definition_files[index] = table_name; if (std::all_of( output_node->given_input_data_definition_files.begin(), output_node->given_input_data_definition_files.end(), [](const auto& filename) { return !filename.empty(); })) { current_available_node_pointers.push_back(output_node); } } // Else the table names have been already given to the output node. } } } } auto ExecutionManager::GetCurrentNodeIndexFromNextNode(QueryNode* current_node, QueryNode* next_node) -> int { for (int i = 0; i < next_node->previous_nodes.size(); i++) { if (next_node->previous_nodes.at(i) == current_node) { return i; } } throw std::runtime_error("Node not found!"); } void ExecutionManager::Execute( std::unique_ptr<ExecutionPlanGraphInterface> execution_graph) { unscheduled_graph_ = std::move(execution_graph); auto begin = std::chrono::steady_clock::now(); busy_flag_ = true; while (busy_flag_) { auto new_state = current_state_->Execute(this); if (new_state) { current_state_ = std::move(new_state); } } auto end = std::chrono::steady_clock::now(); if (config_.print_config || config_.print_scheduling || config_.print_initialisation || config_.print_system || config_.print_data_amounts) { auto data = query_manager_->GetData(); long total_execution = std::chrono::duration_cast<std::chrono::microseconds>(end - begin) .count(); long data_size = data[0]; long scheduling = data[3]; long init_config = data[1]; long config = config_time_; long initialisation = data[2]; long system = total_execution - scheduling - init_config - config - initialisation; long actual_execution = total_execution - init_config; // std::cout << "ACTUAL_EXECUTION: " << actual_execution << std::endl; if (config_.print_config) { std::cout << "CONFIGURATION: " << config << std::endl; } if (config_.print_scheduling) { std::cout << "SCHEDULING: " << scheduling << std::endl; } if (config_.print_initialisation) { std::cout << "INITIALISATION: " << initialisation << std::endl; } if (config_.print_system) { std::cout << "SYSTEM: " << system << std::endl; } /*std::cout << "EXECUTION: " << (data_size / 4659.61402505057) << std::endl;*/ /*std::cout << "STATIC: " << ((data_size / 4659.61402505057) + initialisation) << std::endl;*/ if (config_.print_data_amounts) { std::cout << "DATA_STREAMED: " << data_size << std::endl; } /*std::cout << "TOTAL EXECUTION RUNTIME: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin) .count() << std::endl;*/ } } auto ExecutionManager::IsUnscheduledNodesGraphEmpty() -> bool { return unscheduled_graph_->IsEmpty(); } auto ExecutionManager::IsARunScheduled() -> bool { return !query_node_runs_queue_.empty(); } auto ExecutionManager::IsRunReadyForExecution() -> bool { return !query_nodes_.empty(); } void ExecutionManager::ScheduleUnscheduledNodes() { query_node_runs_queue_ = query_manager_->ScheduleNextSetOfNodes( current_available_node_pointers_, nodes_constrained_to_first_, current_available_node_names_, current_query_graph_, current_tables_metadata_, *accelerator_library_, config_, *scheduler_, current_configuration_, processed_nodes_, table_counter_, blocked_nodes_); } void ExecutionManager::BenchmarkScheduleUnscheduledNodes() { query_manager_->BenchmarkScheduling( nodes_constrained_to_first_, current_available_node_names_, processed_nodes_, current_query_graph_, current_tables_metadata_, *accelerator_library_, config_, *scheduler_, current_configuration_, blocked_nodes_); } auto ExecutionManager::IsBenchmarkDone() -> bool { return current_available_node_names_.empty(); } auto ExecutionManager::GetModuleCapacity(int module_position, QueryOperationType operation) -> std::vector<int> { std::string last_seen_bitstream = ""; int seen_bitstreams = -1; for (const auto module_name : current_routing_) { if (module_name != last_seen_bitstream && module_name != "RT" && module_name != "TAA" && !module_name.empty()) { seen_bitstreams++; if (seen_bitstreams == module_position) { return config_.pr_hw_library.at(operation) .bitstream_map.at(module_name) .capacity; } last_seen_bitstream = module_name; } } // return {0}; throw std::runtime_error("Not enough modules configured!"); } void ExecutionManager::SetupNextRunData() { /*ConfigurableModulesVector next_set_of_operators;*/ // const auto first = query_node_runs_queue_.front(); // getting the first // query_node_runs_queue_.pop(); // removing him // query_node_runs_queue_.push(first); /*auto next_run = query_node_runs_queue_.front().first; for (auto& module_index : next_run) { next_set_of_operators.emplace_back( module_index.operation_type, config_.pr_hw_library.at(module_index.operation_type) .bitstream_map.at(module_index.bitstream) .capacity); }*/ // if (config_.accelerator_library.find(next_set_of_operators) == // config_.accelerator_library.end()) { // // for (const auto& thing : query_node_runs_queue_.front().first) { // // auto op_type = thing.operation_type; // // auto module_params = thing.resource_elasticity_data; // //} // throw std::runtime_error("Bitstream not found!"); //} // Old /*query_manager_->LoadNextBitstreamIfNew( memory_manager_.get(), config_.accelerator_library.at(query_node_runs_queue_.front().first), config_);*/ /*query_manager_->LoadInitialStaticBitstream(memory_manager_.get()); query_manager_->LoadEmptyRoutingPRRegion(memory_manager_.get(), *accelerator_library_.get());*/ auto [bitstreams_to_load, empty_modules] = query_manager_->GetPRBitstreamsToLoadWithPassthroughModules( current_configuration_, query_node_runs_queue_.front().first, current_routing_); /*bitstreams_to_load = {"binPartial_Static1_0_96.bin"}; empty_modules = { {QueryOperationType::kFilter, false}, {QueryOperationType::kAddition, true}, {QueryOperationType::kMultiplication, true}, {QueryOperationType::kAggregationSum, true}, {QueryOperationType::kLinearSort, true}, };*/ /*bitstreams_to_load = {"binPartial_Static2_0_96.bin"}; empty_modules = { {QueryOperationType::kMergeSort, true}, {QueryOperationType::kJoin, true}, {QueryOperationType::kFilter, false}, {QueryOperationType::kAggregationSum, true}, };*/ // bitstreams_to_load = {"byteman_BWplusSobel_67_96.bin"}; /*query_manager_->LoadPRBitstreams(memory_manager_.get(), bitstreams_to_load, *accelerator_library_);*/ config_time_ += query_manager_->LoadPRBitstreams( memory_manager_.get(), bitstreams_to_load, *accelerator_library_); if (print_hw_) { std::cout << "Loading: "; for (const auto& bitstream : bitstreams_to_load) { std::cout << bitstream << ", "; } std::cout << std::endl; PrintHWState(); } /*query_manager_->LoadPRBitstreams(memory_manager_.get(), bitstreams_to_load, *accelerator_library_.get());*/ // Debugging // std::vector<std::pair<QueryOperationType, bool>> empty_modules; /*query_manager_->LoadEmptyRoutingPRRegion(memory_manager_.get(), *accelerator_library_.get());*/ /*query_manager_->LoadPRBitstreams(memory_manager_.get(),config_.debug_forced_pr_bitstreams, *accelerator_library_.get()); exit(0);*/ auto next_scheduled_run_nodes = PopNextScheduledRun(); scheduled_node_names_.clear(); for (const auto& node : next_scheduled_run_nodes) { scheduled_node_names_.push_back(node->node_name); } /*for (const auto& node_name : scheduled_node_names_) { std::cout << node_name << " "; }*/ /*std::cout << std::endl; for (const auto& [op, used] : empty_modules) { if (op == QueryOperationType::kAddition) { std::cout << "Add: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kAggregationSum) { std::cout << "Sum: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kFilter) { std::cout << "Filter: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kJoin) { std::cout << "Join: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kLinearSort) { std::cout << "LinSort: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kMergeSort) { std::cout << "MergeSort: " << (used ? "true" : "false") << ";"; } else if (op == QueryOperationType::kMultiplication) { std::cout << "Mul: " << (used ? "true" : "false") << ";"; } }*/ auto execution_nodes_and_result_params = query_manager_->SetupAccelerationNodesForExecution( data_manager_.get(), memory_manager_.get(), accelerator_library_.get(), next_scheduled_run_nodes, current_tables_metadata_, table_memory_blocks_, table_counter_, config_.print_write_times); query_nodes_ = std::move(execution_nodes_and_result_params.first); for (int module_pos = 0; module_pos < empty_modules.size(); module_pos++) { if (empty_modules.at(module_pos).second) { query_nodes_.insert( query_nodes_.begin() + module_pos, accelerator_library_->GetEmptyModuleNode( empty_modules.at(module_pos).first, module_pos + 1, GetModuleCapacity(module_pos, empty_modules.at(module_pos).first))); } else { query_nodes_.at(module_pos).operation_module_location = module_pos + 1; } } result_parameters_ = std::move(execution_nodes_and_result_params.second); } void ExecutionManager::ExecuteAndProcessResults() { query_manager_->ExecuteAndProcessResults( memory_manager_.get(), fpga_manager_.get(), data_manager_.get(), table_memory_blocks_, result_parameters_, query_nodes_, current_tables_metadata_, table_counter_, config_.execution_timeout); // TODO(Kaspar): Remove this scheduled_node_names_.clear(); } // auto ExecutionManager::IsRunValid() -> bool { // return query_manager_->IsRunValid(query_nodes_); //} auto ExecutionManager::PopNextScheduledRun() -> std::vector<QueryNode*> { const auto executable_query_nodes = query_node_runs_queue_.front().second; query_node_runs_queue_.pop(); return executable_query_nodes; } void ExecutionManager::PrintCurrentStats() { query_manager_->PrintBenchmarkStats(); } void ExecutionManager::SetClockSpeed(int new_clock_speed) { config_.clock_speed = new_clock_speed; } void ExecutionManager::LoadStaticBitstream() { query_manager_->LoadInitialStaticBitstream(memory_manager_.get(), config_.clock_speed); // TODO: Remove the hardcoded aspect of this! current_routing_.clear(); for (int i = 0; i < 31; i++) { current_routing_.push_back("RT"); } /*query_manager_->MeasureBitstreamConfigurationSpeed(config_.pr_hw_library, memory_manager_.get());*/ } void ExecutionManager::SetupSchedulingData(bool setup_bitstreams) { config_time_ = 0; current_tables_metadata_ = config_.initial_all_tables_metadata; if (setup_bitstreams) { LoadStaticBitstream(); } } void ExecutionManager::SetupSchedulingGraphAndConstrainedNodes( const std::vector<QueryNode*>& all_query_nodes, std::unordered_map<std::string, SchedulingQueryNode>& current_scheduling_graph, AcceleratorLibraryInterface& hw_library, std::unordered_set<std::string>& constrained_nodes_vector, const std::map<std::string, TableMetadata>& tables_metadata) { for (const auto& node : all_query_nodes) { AddSchedulingNodeToGraph(node, current_scheduling_graph, hw_library); AddSavedNodesToConstrainedList(node, constrained_nodes_vector); AddFirstModuleNodesToConstrainedList(node, constrained_nodes_vector, hw_library); } AddSplittingNodesToConstrainedList(current_scheduling_graph, constrained_nodes_vector); } void ExecutionManager::AddSavedNodesToConstrainedList( QueryNode* const& node, std::unordered_set<std::string>& constrained_nodes) { for (int node_index = 0; node_index < node->is_checked.size(); node_index++) { if (node->is_checked[node_index] && std::any_of( node->next_nodes.begin(), node->next_nodes.end(), [](const auto& next_node) { return next_node != nullptr; })) { auto& next_node = node->next_nodes[node_index]; if (next_node != nullptr) { auto& constrained_node_name = node->next_nodes[node_index]->node_name; if (constrained_nodes.find(constrained_node_name) == constrained_nodes.end()) { constrained_nodes.insert(constrained_node_name); } } } } } void ExecutionManager::AddSchedulingNodeToGraph( QueryNode* const& node, std::unordered_map<std::string, SchedulingQueryNode>& scheduling_graph, AcceleratorLibraryInterface& accelerator_library) { SchedulingQueryNode current_node; for (const auto& next_node : node->next_nodes) { if (next_node) { current_node.after_nodes.push_back(next_node->node_name); } else { current_node.after_nodes.emplace_back(""); } } for (const auto& previous_node_ptr : node->previous_nodes) { if (previous_node_ptr) { current_node.before_nodes.emplace_back( previous_node_ptr->node_name, QuerySchedulingHelper::FindNodePtrIndex(node, previous_node_ptr)); } else { current_node.before_nodes.emplace_back("", -1); } } for (const auto& input_files : node->given_input_data_definition_files) { current_node.data_tables.push_back(input_files); } current_node.operation = node->operation_type; current_node.capacity = accelerator_library.GetNodeCapacity( node->operation_type, node->given_operation_parameters.operation_parameters); current_node.node_ptr = node; scheduling_graph.insert({node->node_name, current_node}); } void ExecutionManager::AddFirstModuleNodesToConstrainedList( QueryNode* const& node, std::unordered_set<std::string>& constrained_nodes, AcceleratorLibraryInterface& accelerator_library) { if (accelerator_library.IsNodeConstrainedToFirstInPipeline( node->operation_type)) { constrained_nodes.insert(node->node_name); }; } // This check is looking at all the nodes if there are multiple identical before // streams. // TODO(Kaspar): Splitting nodes aren't supported at the moment anyway: // after_nodes needs to be a vector of vectors! void ExecutionManager::AddSplittingNodesToConstrainedList( std::unordered_map<std::string, SchedulingQueryNode>& scheduling_graph, std::unordered_set<std::string>& constrained_nodes) { // THere are no splitting nodes at the moment /*std::vector<std::pair<std::string, int>> all_stream_dependencies; std::vector<std::pair<std::string, int>> splitting_streams;*/ /*for (const auto& [node_name, node_parameters] : scheduling_graph) { for (const auto& previous_node_stream : node_parameters.before_nodes) { if (previous_node_stream.second != -1) { if (std::find(all_stream_dependencies.begin(), all_stream_dependencies.end(), previous_node_stream) == all_stream_dependencies.end()) { all_stream_dependencies.push_back(previous_node_stream); } else if (std::find(splitting_streams.begin(), splitting_streams.end(), previous_node_stream) == splitting_streams.end()) { splitting_streams.push_back(previous_node_stream); } } } } for (const auto& splitting_node_stream : splitting_streams) { for (const auto& potentially_constrained_node_name : scheduling_graph.at(splitting_node_stream.first).after_nodes) { if (!potentially_constrained_node_name.empty()) { auto before_nodes_vector = scheduling_graph.at(potentially_constrained_node_name).before_nodes; if (std::find(before_nodes_vector.begin(), before_nodes_vector.end(), splitting_node_stream) != before_nodes_vector.end() && std::find(constrained_nodes.begin(), constrained_nodes.end(), potentially_constrained_node_name) == constrained_nodes.end()) { constrained_nodes.insert(potentially_constrained_node_name); } } } }*/ }
// // Created by Benoit Hamon on 10/4/2017. // #pragma once #include <boost/function.hpp> #include <boost/thread/thread.hpp> #include "IModule.hpp" #include "IModuleCommunication.hpp" typedef boost::shared_ptr<IModule> (module_t)(IModuleCommunication *); class ModuleManager { public: ModuleManager(IModuleCommunication *moduleCommunication = nullptr, std::string const &dirname = "./"); ~ModuleManager(); public: void run(); void addModuleCommunication(IModuleCommunication *moduleCommunication); void addLibrary(boost::property_tree::ptree const &ptree); private: struct Library { std::string name; boost::shared_ptr<IModule> module; boost::function<module_t> creator; }; private: void runLibraries(); void runLibrary(std::string const &libraryName); std::vector<std::string> readDirectory(); private: std::string _dirname; std::vector<Library> _libraries; boost::thread_group _threads; IModuleCommunication *_moduleCommunication; };
/*! * \file Reader.h * \brief Define JSON readers * \author Pierre-Jean Besnard & Louis Billaut * \version 1.0 */ #include <stdio.h> #include <iostream> #include <vector> #include "Scene.h" #include <fstream> #include <string> #include <jsoncpp/json/json.h> /*! \class Reader * \brief Allows to create a JSON file reader */ class Reader { public: /*! * \brief Read a JSON file and create a scene with objects of this file * * \param filename : the file name * \param scene : the scene where objects will be placed * \param l : the light position * \param f : the fov of the camera */ void read_scene_file(const char* filename, Scene& scene, Vector& l, int &f){ std::ifstream file(filename); Json::Reader reader; Json::Value obj; reader.parse(file, obj); get_spheres_from_file(obj); get_cylinders_from_file(obj); get_triangles_from_file(obj); get_rectangles_from_file(obj); get_light_and_cam_from_file(obj); scene = s; l = light_position_value; f = fov_cam; } Scene s; /*!< the scene */ Vector light_position_value; /*!< the light position */ int fov_cam; /*!< the fov of the camera */ private: /*! * \brief Get rectangles from the JSON file * * \param obj : a JSON object */ void get_rectangles_from_file(Json::Value obj){ const Json::Value& rectangles = obj["rectangles"]; for (int i = 0; i < rectangles.size(); i++){ Vector vec1(rectangles[i]["c1"][0].asInt(), rectangles[i]["c1"][1].asInt(), rectangles[i]["c1"][2].asInt()); Vector vec2(rectangles[i]["c2"][0].asInt(), rectangles[i]["c2"][1].asInt(), rectangles[i]["c2"][2].asInt()); Vector vec3(rectangles[i]["c3"][0].asInt(), rectangles[i]["c3"][1].asInt(), rectangles[i]["c3"][2].asInt()); Vector vec4(rectangles[i]["c4"][0].asInt(), rectangles[i]["c4"][1].asInt(), rectangles[i]["c4"][2].asInt()); Vector color(rectangles[i]["color"][0].asInt(), rectangles[i]["color"][1].asInt(), rectangles[i]["color"][2].asInt()); bool mirror = rectangles[i]["mirror"].asInt() == 1; bool glass = rectangles[i]["glass"].asInt() == 1; Rectangle* s6 = new Rectangle(vec1, vec2, vec3, vec4, color, mirror, glass, rectangles[i]["spec"].asDouble()); s.addRectangle(s6); } } /*! * \brief Get triangles from the JSON file * * \param obj : a JSON object */ void get_triangles_from_file(Json::Value obj){ const Json::Value& triangles = obj["triangles"]; for (int i = 0; i < triangles.size(); i++){ Vector vec1(triangles[i]["c1"][0].asInt(), triangles[i]["c1"][1].asInt(), triangles[i]["c1"][2].asInt()); Vector vec2(triangles[i]["c2"][0].asInt(), triangles[i]["c2"][1].asInt(), triangles[i]["c2"][2].asInt()); Vector vec3(triangles[i]["c3"][0].asInt(), triangles[i]["c3"][1].asInt(), triangles[i]["c3"][2].asInt()); Vector color(triangles[i]["color"][0].asInt(), triangles[i]["color"][1].asInt(), triangles[i]["color"][2].asInt()); bool mirror = triangles[i]["mirror"].asInt() == 1; bool glass = triangles[i]["glass"].asInt() == 1; Triangle* s7 = new Triangle(vec1, vec2, vec3, color, mirror, glass, triangles[i]["spec"].asDouble()); s.addTriangle(s7); } } /*! * \brief Get cylinders from the JSON file * * \param obj : a JSON object */ void get_cylinders_from_file(Json::Value obj){ const Json::Value& cylinders = obj["cylinders"]; for (int i = 0; i < cylinders.size(); i++){ bool mirror = cylinders[i]["mirror"].asInt() == 1; bool glass = cylinders[i]["glass"].asInt() == 1; Vector color(cylinders[i]["color"][0].asInt(), cylinders[i]["color"][1].asInt(), cylinders[i]["color"][2].asInt()); Vector origin(cylinders[i]["axis"][0].asInt(), cylinders[i]["axis"][1].asInt(), cylinders[i]["axis"][2].asInt()); Cylinder* s8 = new Cylinder(origin, cylinders[i]["rayon"].asInt(), cylinders[i]["height"].asInt(), color, mirror, glass, cylinders[i]["spec"].asDouble()); s.addCylinder(s8); } } /*! * \brief Get spheres from the JSON file * * \param obj : a JSON object */ void get_spheres_from_file(Json::Value obj){ const Json::Value& spheres = obj["spheres"]; for (int i = 0; i < spheres.size(); i++){ bool mirror = (spheres[i]["mirror"].asInt() == 1) ? true: false; bool glass = (spheres[i]["glass"].asInt() == 1) ? true: false; Vector axis(spheres[i]["axis"][0].asInt(), spheres[i]["axis"][1].asInt(), spheres[i]["axis"][2].asInt()); int rayon = spheres[i]["rayon"].asInt(); Vector color(spheres[i]["color"][0].asInt(), spheres[i]["color"][1].asInt(), spheres[i]["color"][2].asInt()); double spec = spheres[i]["spec"].asDouble(); Sphere* s5 = new Sphere(axis, rayon, color, mirror, glass, spec); s.addSphere(s5); if (i == 0){ s.addSphere(s5); s.light = s5; continue; } } } /*! * \brief Get the light and the fov of the camera from the JSON file * * \param obj : a JSON object */ void get_light_and_cam_from_file(Json::Value obj){ const Json::Value& light_intensity_value = obj["light_intensity"]; const Json::Value& light_position = obj["light_position"]; const Json::Value& fov = obj["fov"]; s.light_intensity = light_intensity_value.asDouble(); light_position_value = Vector(light_position[0].asInt(), light_position[1].asInt(), light_position[2].asInt()); fov_cam = fov.asInt(); } };
#ifndef MASTERS_PROJECT_AMERICANIMPLICITHEATEQMETHOD_H #define MASTERS_PROJECT_AMERICANIMPLICITHEATEQMETHOD_H #include "EuroImplicitHeatEqMethod.hpp" template<typename X> class AmericanImplicitHeatEqMethod : public EuroImplicitHeatEqMethod { public: AmericanImplicitHeatEqMethod(Option<X> *_option, X _S_min, X _S_max, int _N, int _M); void solve(bool showStable = false) override; }; #include "AmericanImplicitHeatEqMethod.tpp #endif //MASTERS_PROJECT_AMERICANIMPLICITHEATEQMETHOD_H
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Form.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kwillum <kwillum@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/16 01:13:00 by kwillum #+# #+# */ /* Updated: 2021/01/22 17:29:41 by kwillum ### ########.fr */ /* */ /* ************************************************************************** */ #include "Form.hpp" Form::Form() : _name("Default_name"), _grade2Sign(150), _grade2Exec(150), _signed(0) { } Form::~Form() { } Form::Form(const Form &toCopy) : _name(toCopy._name), _grade2Sign(toCopy._grade2Sign),\ _grade2Exec(toCopy._grade2Exec), _signed(toCopy._signed) { if (_correctGrade()) return ; } Form::Form(std::string const &name, int grade2Sign = 150, int grade2Exec=150) : _name(name), _grade2Sign(grade2Sign), _grade2Exec(grade2Exec), _signed(false) { if (_correctGrade()) return ; } int Form::_correctGrade() { if (_grade2Exec < 1 || _grade2Sign < 1) throw GradeTooHighException(); else if (_grade2Exec > 150 || _grade2Sign > 150) throw GradeTooLowException(); return (1); } void Form::beSigned(const Bureaucrat &b) { if (b.getGrade() > _grade2Sign) throw GradeTooLowException(); else _signed = true; } void Form::execute(const Bureaucrat &b) const { if (!_signed) throw FormNotSignedYetException(); else if (b.getGrade() > _grade2Exec) throw GradeTooLowException(); } int Form::getFormGrade() const { return (_grade2Sign); } std::string const &Form::getFormName() const { return (_name); } bool Form::getSignStatus() const { return (_signed); } int Form::getExecutorGrade() const { return (_grade2Exec); } Form &Form::operator=(const Form &toCopy) { (void)toCopy; return (*this); } std::ostream &operator<<(std::ostream &o, const Form &f) { o << "Form with name: " << f.getFormName() << " and FormGrade: " << \ f.getFormGrade() << " and FormExecGrade: " << f.getExecutorGrade() <<\ " has a currently status: " << (f.getSignStatus() ? "signed" : "not signed"); return (o); } const char *Form::GradeTooHighException::what() const throw() { return ("Form::Exception Too HIGH grade!"); } const char *Form::GradeTooLowException::what() const throw() { return ("Form::Exception Too LOW grade!"); } const char *Form::FormAlreadySignedException::what() const throw() { return ("Form::Exception Form already SIGNED!"); } const char *Form::FormNotSignedYetException::what() const throw() { return ("Form::Exception Form NOT SIGNED yet!"); }
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> #include <vector> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> // ------------- // pure C++ code // ------------- std::vector<double> length(const std::vector<double>& pos) { size_t N = pos.size() / 2; std::vector<double> output(N*3); for ( size_t i = 0 ; i < N ; ++i ) { output[i*3+0] = pos[i*2+0]; output[i*3+1] = pos[i*2+1]; output[i*3+2] = std::pow(pos[i*2+0]*pos[i*2+1],.5); } return output; } // ---------------- // Python interface // ---------------- namespace py = pybind11; // wrap C++ function with NumPy array IO py::array cv_mat_example(py::array_t<uint8_t, py::array::c_style | py::array::forcecast> array) { // Get buffer info py::buffer_info info = array.request(); // Shape properties int nrows, ncols, indim, nchan=0; nrows = array.shape()[0]; ncols = array.shape()[1]; indim = info.ndim; // Convert array to CV::Mat and do opencv operations cv:: Mat m; if(indim == 3){ nchan = 3; m = cv::Mat(nrows, ncols, CV_8UC3); } else if (indim == 2) { nchan = 1; m = cv::Mat(nrows, ncols, CV_8UC1); } memcpy(m.data, array.data(), nrows*ncols*nchan*sizeof(uint8_t)); // std::vector<double> result = length(pos); ssize_t ndim = 3; std::vector<ssize_t> shape = { nrows , ncols, nchan}; std::vector<ssize_t> strides = { int(ncols*nchan*sizeof(uint8_t)), int(nchan*sizeof(uint8_t)), int(sizeof(uint8_t))}; // return 2-D NumPy array return py::array(py::buffer_info( m.data, /* data as contiguous array */ sizeof(uint8_t), /* size of one scalar */ py::format_descriptor<uint8_t>::format(), /* data type */ ndim, /* number of dimensions */ shape, /* shape of the matrix */ strides /* strides for each axis */ )); } // wrap as Python module PYBIND11_MODULE(example,m) { m.doc() = "pybind11 example plugin"; m.def("cv_mat_example", &cv_mat_example, "Calculate the length of an array of vectors"); }
#include<cstdio> #include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ int n; scanf("%d", &n); int w,s; int res =0; for(int i=0;i<n;i++){ scanf("%d%d", &w,&s); res += w*s; } cout<<max(res,0)<<endl; return 0; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Renderer/RendererTypes.h" // For "Renderer::ComparisonFunc" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Renderer { //[-------------------------------------------------------] //[ Definitions ] //[-------------------------------------------------------] /** * @brief * Depth write mask * * @note * - These constants directly map to Direct3D 10 & 11 & 12 constants, do not change them * * @see * - "D3D12_DEPTH_WRITE_MASK"-documentation for details */ enum class DepthWriteMask { ZERO = 0, ALL = 1 }; /** * @brief * Stencil operation * * @note * - These constants directly map to Direct3D 10 & 11 & 12 constants, do not change them * * @see * - "D3D12_STENCIL_OP"-documentation for details */ enum class StencilOp { KEEP = 1, ZERO = 2, REPLACE = 3, INCR_SAT = 4, DERC_SAT = 5, INVERT = 6, INCREASE = 7, DECREASE = 8 }; //[-------------------------------------------------------] //[ Types ] //[-------------------------------------------------------] /** * @brief * Depth stencil operation description * * @note * - This depth stencil operation description maps directly to Direct3D 10 & 11 & 12, do not change it * - If you want to know how the default values were chosen, have a look into the "Renderer::DepthStencilStateBuilder::getDefaultDepthStencilState()"-implementation * * @see * - "D3D12_DEPTH_STENCILOP_DESC"-documentation for details */ struct DepthStencilOpDesc final { StencilOp stencilFailOp; ///< Default: "Renderer::StencilOp::KEEP" StencilOp stencilDepthFailOp; ///< Default: "Renderer::StencilOp::KEEP" StencilOp stencilPassOp; ///< Default: "Renderer::StencilOp::KEEP" ComparisonFunc stencilFunc; ///< Default: "Renderer::ComparisonFunc::ALWAYS" }; /** * @brief * Depth stencil state * * @note * - This depth stencil state maps directly to Direct3D 10 & 11 & 12, do not change it * - This also means that "int" is used over "bool" because in Direct3D it's defined this way * - If you want to know how the default values were chosen, have a look into the "Renderer::DepthStencilStateBuilder::getDefaultDepthStencilState()"-implementation * * @see * - "D3D12_DEPTH_STENCIL_DESC"-documentation for details */ struct DepthStencilState final { int depthEnable; ///< Boolean value. Default: "true" DepthWriteMask depthWriteMask; ///< Default: "Renderer::DepthWriteMask::ALL" ComparisonFunc depthFunc; ///< Default: "Renderer::ComparisonFunc::GREATER" instead of "Renderer::ComparisonFunc::LESS" due to usage of Reversed-Z (see e.g. https://developer.nvidia.com/content/depth-precision-visualized and https://nlguillemot.wordpress.com/2016/12/07/reversed-z-in-opengl/) int stencilEnable; ///< Boolean value. Default: "false" uint8_t stencilReadMask; ///< Default: "0xff" uint8_t stencilWriteMask; ///< Default: "0xff" DepthStencilOpDesc frontFace; ///< Default: See "Renderer::DepthStencilOpDesc" DepthStencilOpDesc backFace; ///< Default: See "Renderer::DepthStencilOpDesc" }; struct DepthStencilStateBuilder final { //[-------------------------------------------------------] //[ Public static methods ] //[-------------------------------------------------------] public: /** * @brief * Return the default depth stencil state * * @return * The default depth stencil state, see "Renderer::DepthStencilState" for the default values */ static inline const DepthStencilState& getDefaultDepthStencilState(); }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Renderer //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "Renderer/State/DepthStencilStateTypes.inl"
/** Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. */ #ifndef __ARCHIVE_UTILS_HXX__ #define __ARCHIVE_UTILS_HXX__ /** * Archive Attributes */ #define __ARCHIVE_NAME__ "evz.archive" #define __ARCHIVE_ROOT__ "xScripts/" /** * Archive Password Parts */ #define __ARCHIVE_PART1__ 0x51277094 #define __ARCHIVE_PART2__ 0x88257473 #define __ARCHIVE_PART3__ 0x57138953 #define __ARCHIVE_PART4__ 0x06917385 /** * Includes */ #include "globals.hxx" class ArchiveUtils { public: /** * Loads a file from the password protected archive into the cocos2d::Data format. * * @param file Name of the file in the password protected archive * @param archive The Name of the password protected archive */ static Data loadData(const string& file, const string& archive = __ARCHIVE_NAME__); /** * Loads a file from the password protected archive into the cocos2d::ValueMap format. * * @param file ~ Name of the file in the password protected archive. * @param archive ~ The Name of the password protected archive. * * @returns A ValueMap from file */ static ValueMap loadValueMap(const string& file, const string& archive = __ARCHIVE_NAME__); /** * Loads a file from the password protected archive into the cocos2d::ValueVector format. * * @param file ~ Name of the file in the password protected archive. * @param archive ~ The Name of the password protected archive. * * @returns A ValueVector from file * * @note ~ The root must be a ValueMap with one key `data` continaing the array. */ static ValueVector loadValueVector(const string& file, const string& archive = __ARCHIVE_NAME__); /** * Loads a file from the password protected archive into a string * * @param file ~ Name of the file in the password protected archive. * @param archive ~ The Name of the password protected archive. * * @returns String version of the file. Nice for loading Json */ static string loadString(const string& file, const string& archive = __ARCHIVE_NAME__); private: /** * @brief Generates the hash password for the zip on the fly. * * @param salt ~ The salt added to generate the specific password only for that archive. * Usually this is just the name of the archive. * * @returns Hashed password. */ static string genZipPassword(const string& salt); /** * @brief Retrieves data from a encrypted archive. * * @param archive ~ 7z store archive where data is stored. * @param name ~ Name of the file located inside of the archive. * @param size ~ Pointer for storing the file size. * @param password ~ Optional password 7z store archive. * * @return Data of the file in zip. * * @note If the zip file is password protected, the archive must be packaged using the `store` option in an * implementation of 7zip. No compression should be applied or this will return garbage data. */ static unsigned char* getFileDataFromZip(const string& archive, const string& name, ssize_t* size, const string& password = ""); /** * __DISALLOW_IMPLICIT_CONSTRUCTORS__ */ __DISALLOW_IMPLICIT_CONSTRUCTORS__(ArchiveUtils) }; #endif // __ARCHIVE_UTILS_HXX__
#pragma once #include "aePrerequisitesUtil.h" #include "aePrerequisitesEngine.h" namespace aeEngineSDK { enum struct AE_ADD_ON_ID { AE_RENDERER }; class aeGameObject; class AE_ENGINE_EXPORT aeGOAddOn { friend class aeGOFactory; public: aeGOAddOn(); aeGOAddOn(const aeGOAddOn& AO); ~aeGOAddOn(); public: virtual AE_RESULT Init(); virtual void Update(); virtual void Destroy(); virtual AE_ADD_ON_ID GetComponentId() const = 0; aeGameObject* m_pGameObject; }; }
#include "stdafx.h" #include "AIEditNode.h" #include "../GameCursor.h" // THIS IS CAMERA. #include "../../GameCamera.h" #include "AIEditNodeInequ.h" #include "AIEditNodeButton.h" #include "AIEditNodeTechnique.h" #include "AIEdtiNodeAbnormalState.h" #include "AIEditNodeProcess.h" #include "AIEditNodeOrder.h" AIEditNode::~AIEditNode() { DeleteGO(m_spriteRender); for (AIEditNodeButton* sp : m_nodebuttons) { DeleteGO(sp); } for (auto fonts : m_fonts) DeleteGO(fonts); for (auto fonts : m_font) DeleteGO(fonts); } bool AIEditNode::Start() { m_gamecursor = FindGO<GameCursor>("cursor"); m_aieditnodeprocess = FindGO<AIEditNodeProcess>("process"); //UIの基盤 m_spriteRender = NewGO<SpriteRender>(6, "firstwin"); m_spriteRender->Init(L"Assets/sprite/menu2.dds", 175, 280); CVector3 cursorpos = m_gamecursor->GetCursor(); cursorpos.x += 87.5f; //位置調整だよ。 cursorpos.y += -140.0f; m_position = cursorpos; m_spriteRender->SetPosition(m_position); //カーソルの座標 //ぼたん。 for (int i = 0; i < button; i++) { //ボタンの数分ループする。 m_aieditnodebutton = NewGO<AIEditNodeButton>(7, "button"); m_aieditnodebutton->SetPri(7); m_aieditnodebutton->SetButton(i + 1); m_aieditnodebutton->SetPos(m_position); m_nodebuttons.push_back(m_aieditnodebutton); } //フォント。 for (int i = 0; i < button; i++) { m_fonts.push_back(NewGO<FontRender>(8)); m_fonts[i]->SetTextType(CFont::en_Japanese); } auto bacon = m_nodebuttons[0]->GetPos(); CVector2 m_fontpos = CVector2::Zero(); //フォントの座標。 m_fontpos.x = bacon.x - 55.0; m_fontpos.y = bacon.y + 108.0; m_fonts[0]->Init(L" HP", { m_fontpos.x,m_fontpos.y-5 }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); m_fonts[0]->DrawShadow({ SetShadowPos }); m_fontpos.y -= 57.f; m_fonts[1]->Init(L" MP", { m_fontpos.x,m_fontpos.y-3 }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); m_fonts[1]->DrawShadow({ SetShadowPos }); m_fontpos.x -= 10.f; m_fontpos.y -= 63.f; m_fonts[2]->Init(L"じょうたい", { m_fontpos }, 0.0, CVector4::White, 0.55, { 0.0,0.0 }); m_fonts[2]->DrawShadow({ SetShadowPos }); m_fontpos.x += 4.f; m_fontpos.y -= 48.f; m_fonts[3]->Init(L" わざ", { m_fontpos }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); m_fonts[3]->DrawShadow({ SetShadowPos }); m_font.push_back(NewGO<FontRender>(3)); m_font[0]->SetTextType(CFont::en_Japanese); return true; } void AIEditNode::Inequ() { NewGO<AIEditNodeInequ>(0, "Inequality"); Choice1 = true; Nodefont = true; contact2 = true; PlayButtonSE(); } void AIEditNode::Technique() { if (Mouse::isTrigger(enLeftClick)) //左クリック { PlayButtonSE(); m_aieditnodeprocess->Technique(); Choice1 = true; } } void AIEditNode::Abnormal() { NewGO<AIEditNodeAbnormalState>(0, "Abnormal"); Choice1 = true; Nodefont = true; contact2 = true; PlayButtonSE(); } void AIEditNode::FontsConfirmation() { CVector2 m_fontpos1 = CVector2::Zero(); m_fontpos1.x -= 72; m_fontpos1.y += 360; bool cont = true; if (m_nodebuttons[button - 4]->GetSpriteRender()->isCollidingTarget()) { m_font[0]->Init(L"のHPが", { m_fontpos1 }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); m_font[0]->DrawShadow({ SetShadowPos }); contact1 = true; } else if (m_nodebuttons[button - 3]->GetSpriteRender()->isCollidingTarget()) { m_font[0]->Init(L"のMPが", { m_fontpos1 }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); m_font[0]->DrawShadow({ SetShadowPos }); contact1 = true; } else { cont = false; } if (contact1 == true) { if (cont == false) { m_font[0]->Init(L"", { m_fontpos1 }, 0.0, CVector4::White, 0.8, { 0.0,0.0 }); contact1 = false; } } } void AIEditNode::Update() { cursorpos = m_gamecursor->GetCursor(); for (int i = 0; i < button; i++) { SpriteRender* sp = m_nodebuttons[i]->GetSpriteRender(); sp->SetCollisionTarget(cursorpos); } if (contact2 == false) { FontsConfirmation(); } if (Choice1 == false) { if (Mouse::isTrigger(enLeftClick)) { //左クリック if (m_nodebuttons[button - 4]->GetSpriteRender()->isCollidingTarget()) { m_Node = enHp; m_aieditnodeprocess->Setkeeonode(enHp); Inequ(); } if (m_nodebuttons[button - 3]->GetSpriteRender()->isCollidingTarget()) { m_Node = enMp; m_aieditnodeprocess->Setkeeonode(enMp); Inequ(); } if (m_nodebuttons[button - 2]->GetSpriteRender()->isCollidingTarget()) { m_Node = enAb; m_aieditnodeprocess->Setkeeonode(enAb); Abnormal(); } if (m_nodebuttons[button - 1]->GetSpriteRender()->isCollidingTarget()) { m_Node = enTechnique; m_aieditnodeprocess->Setkeeonode(enTechnique); Technique(); contact2 = true; PlayButtonSE(); } } } }
#include"token.h" token::token(int t_id, string t_name, string v):token_id(t_id),token_name(t_name),value(v) { } token::~token() { } int token::getTokenID() { return token_id; } ostream& operator<<(ostream& output, const token& t) { output << '(' << t.token_id << ',' << t.token_name << ',' << t.value << ')'; return output; } ofstream& operator<<(ofstream& foutput, const token& t) { foutput << '(' << t.token_id << ',' << t.token_name << ',' << t.value << ')'; return foutput; } void token::generateTokenStream(ofstream& fout) { fout << token_name << " "<<value; }
// // Created by 钟奇龙 on 2019-05-11. // #include <iostream> #include <vector> #include <string> using namespace std; int minCut(string s){ if(s.size() == 0) return 0; vector<vector<bool> > mark(s.size(),vector<bool> (s.size(),false)); vector<int> dp(s.size()+1); dp[s.size()] = -1; for(int i=s.size()-1; i>=0; --i){ dp[i] = INT_MAX; for(int j=i; j<s.size(); ++j){ if(s[i] == s[j] && (j-i < 2 || mark[i+1][j-1])){ mark[i][j] = true; dp[i] = min(dp[i],dp[j+1]+1); } } } return dp[0]; } int main(){ cout<<minCut("ACDCDCDAD")<<endl; return 0; }
#pragma once #include <iostream> class Piece; class Location { private: bool bIndex; // possible indexes to move Piece *mPieceInfo; // piece info pointer public : Location(); ~Location(); void SetIndex(); void DelIndex(); bool GetIndex() const; void SetPiece(Piece *pieceInfo); void DelPiece(); Piece* GetPiece() const; };
#ifndef AWS_PARSER_H #define AWS_PARSER_H /* * aws/parser.h * AwesomeScript Parser * Author: Dominykas Djacenka * Email: Chaosteil@gmail.com */ #include <iostream> #include <istream> #include <map> #include <ostream> #include <stack> #include <string> #include "nodes/nodes.h" #include "reference.h" #include "token.h" #include "tokenizer.h" namespace AwS{ //! Parses a stream from Awesomescript. /*! * The parser itself does not evaluate any expressions or interprets any code. It is merely used to structurize the program. */ class Parser{ public: //! Constructor. /*! * \param input The stream which the parser passes to the tokenizer. */ Parser(std::istream& input = std::cin); //! Destructor. /*! * Does NOT clean up any statements passed with readStatement(). */ ~Parser() throw(Exception); //! Reads a statement from the stream. /*! * The statement is a valid, translateable language unit. * \return An initialized statement. NULL, if finished reading the stream. */ Nodes::Statement* readStatement(); private: Nodes::Statement* _parseStatementBlock(); Nodes::Statement* _parseStatementFunction(); Nodes::Statement* _parseStatementIf(); Nodes::Statement* _parseStatementWhile(); Nodes::Statement* _parseStatementDoWhile(); Nodes::Statement* _parseStatementFor(); Nodes::Statement* _parseStatementVar(); Nodes::Statement* _parseStatementFunctionCallOrAssignment(); Nodes::Statement* _parseStatementOperations(const Nodes::Variable* variable); Nodes::Statement* _parseStatementFunctionCall(const std::string& name); Nodes::Statement* _parseStatementArray(const std::string& name); Nodes::Statement* _parseStatementAssignment(const Nodes::Variable* variable); Nodes::Statement* _parseStatementAdditionEqual(const Nodes::Variable* variable); Nodes::Statement* _parseStatementSubstractionEqual(const Nodes::Variable* variable); Nodes::Statement* _parseStatementMultiplicationEqual(const Nodes::Variable* variable); Nodes::Statement* _parseStatementDivisionEqual(const Nodes::Variable* variable); Nodes::Statement* _parseStatementModulusEqual(const Nodes::Variable* variable); Nodes::Statement* _parseStatementIncrease(const Nodes::Variable* variable); Nodes::Statement* _parseStatementDecrease(const Nodes::Variable* variable); Nodes::Statement* _parseStatementBreak(); Nodes::Statement* _parseStatementContinue(); Nodes::Statement* _parseStatementReturn(); Nodes::Expression* _parseExpression(); Nodes::Expression* _parseExpressionAnd(); Nodes::Expression* _parseExpressionOr(); Nodes::Expression* _parseExpressionComparison(); Nodes::Expression* _parseExpressionAddition(); Nodes::Expression* _parseExpressionMultiplication(); Nodes::Expression* _parseExpressionUnary(); Nodes::Expression* _parseExpressionBase(); Nodes::Expression* _parseExpressionGroup(); Nodes::Expression* _parseExpressionVariableOrFunctionCall(); Nodes::Expression* _parseExpressionStringConstant(); Nodes::Expression* _parseExpressionNumberConstant(); Nodes::Expression* _parseExpressionBooleanConstant(); Nodes::Expression* _parseExpressionNullConstant(); Nodes::Expression* _parseExpressionArray(); Nodes::Expression* _parseExpressionAssociativeArray(); Nodes::Assignment* _parseExpressionAssociativeArrayPair(); Nodes::Expression* _parseExpressionArrayAccess(const std::string& name); Nodes::FunctionCall* _parseFunctionCall(const std::string& name); enum _Error{ Unknown = 0, NoMemory, Unfinished, ExpectedFunction, InvalidStatement, InvalidReservedWord, ExpectedVariable, InvalidDeclaration, UndeclaredVariable, UndeclaredFunction, ExpectedOperation, InvalidExpression, InvalidNumber, InvalidCall, ExpectedSymbol, ExpectedKey }; void _generateException(_Error error, const std::string& message = "", long line = 0); template <class T> static bool _convertString(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)); void _readNextToken(); bool _isFinished(); void _skipToken(Token::TokenType type, const std::string& value) throw(Exception); void _checkUnexpectedEnd() throw(Exception); void _prepareReserved(); void _prepareRequired(); void _prepareLanguage(); enum ParserState{ Default = 0, //!< We are in the global state Function, //!< We are in a function Loop, //!< We are in a loop SpecialStatement //!< Limit statements to a specific set and skip the ';' }; std::stack<ParserState> _states; //!< The state stack. Depending on the top value, the parser parses differemt statements. //! FunctionReference class for managing function declarations and references. /*! * Designed to work with the Reference<T> class and the AwesomeScript requirements. */ class _FunctionReference{ public: enum Type{ Declaration = 0, Reference }; //! Constructor /*! * \param name The name of the function to declare or reference. * \param params The number of parameters the function has or will pass. * \param type The type of the reference. Is it a declaration or a call? */ _FunctionReference(std::string name, int params, Type type); //! Destructor ~_FunctionReference(); //! Overloaded == operator /*! * Works with the Reference<T> class to ensure that the referenced classes don't access less * parameters than they should. If more parameters than required are in a reference, * everything should be fine, but returns false if the declaration needs more. * \param reference The reference to compare to. */ bool operator==(const _FunctionReference& reference)const; //! The name of the function. /*! * \return The name of the declared or referenced function */ const std::string& getName() const; //! Parameters. /*! * \return The amount of parameters in this declaration or reference. */ int getParams() const; //! Type. /*! * \return The type of the function on initialization. */ Type getType() const; private: std::string _name; //!< Name of function. int _params; //!< Amount of parameters in function declaration or reference. Type _type; //!< The type of the function declaration or call. }; Reference<std::string> _reserved; Reference<_FunctionReference> _functions; Reference<std::string>* _variableScope; Tokenizer* _tokenizer; Token* _currentToken; std::istream& _input; }; }; #endif
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> P; P m[501][501]; int main(){ int r, c, k; cin >> r >> c >> k; vector<string> v(r); for(int i=0; i<r; i++) cin >> v[i]; for(int i=0; i<r; i++){ for(int j=0; j<c; j++){ for(int y=i; y>=0; y--){ if(v[y][j] == 'o') m[i][j].first++; else break; } for(int y=i; y<r; y++){ if(v[y][j] == 'o') m[i][j].second++; else break; } } } vector<int> u, ind; for(int x=-k+1; x<k; x++){ u.push_back(abs(k-abs(x))); ind.push_back(x); } int ans = 0; for(int i=k-1; i<=r-k; i++){ for(int j=k-1; j<=c-k; j++){ bool flag = true; for(int x=0; x<ind.size(); x++){ if(m[i][j+ind[x]].first < u[x] || m[i][j+ind[x]].second < u[x]) flag = false; } if(flag) ans++; } } cout << ans << endl; return 0; }
#include<iostream> #include<cmath> using namespace std; int main() { int t,l,k,i,j,T; string s1; cin>>t; scanf("%*c"); for(T=0;T<t;T++) { getline(cin,s1); string s2,s3; int pal=1; for(i=0;i<s1.length();i++) { if(s1[i]>='a'&&s1[i]<='z'||s1[i]>='A'&&s2[i]<='Z') s2.append(s1,i,1); } l=s2.length(); k=sqrt(l); if(k*k!=l) pal=0; else { for(i=0;i<l/2;i++) { if(s2[i]!=s2[l-i-1]) { pal=0; break; } } if(pal) { for(i=0;i<k;i++) { for(j=0;j<k;j++) s3.append(s2,k*j+i,1); } if(s2!=s3) pal=0; else { for(i=0;i<l;i++) { if(s3[i]!=s3[l-i-1]) { pal=0; break; } } } } } cout<<"Case #"<<T+1<<":"<<endl; if(pal) cout<<k<<endl; else cout<<"No magic :("<<endl; } }
#pragma once #include <dirent.h> #include <sys/stat.h> #include "bricks/core/returnpointer.h" #include "bricks/collections/iterator.h" #include "bricks/io/types.h" #include "bricks/io/filepath.h" namespace Bricks { namespace IO { class Stream; namespace FileType { enum Enum { Unknown = DT_UNKNOWN, File = DT_REG, Directory = DT_DIR, BlockDevice = DT_BLK, CharacterDevice = DT_CHR, FIFO = DT_FIFO, SymbolicLink = DT_LNK, Socket = DT_SOCK }; } static inline FileType::Enum FileStatType(mode_t mode) { if (S_ISREG(mode)) return FileType::File; if (S_ISDIR(mode)) return FileType::Directory; if (S_ISCHR(mode)) return FileType::CharacterDevice; if (S_ISBLK(mode)) return FileType::BlockDevice; if (S_ISFIFO(mode)) return FileType::FIFO; if (S_ISLNK(mode)) return FileType::SymbolicLink; if (S_ISSOCK(mode)) return FileType::Socket; return FileType::Unknown; } class FileNode : public Object, public Collections::Iterable<FileNode*> { protected: FileType::Enum type; FilePath path; public: FileNode() : type(FileType::Unknown) { } FileNode(FileType::Enum type, const String& path) : type(type), path(path) { } virtual FileType::Enum GetType() const { return type; } virtual String GetPath() const { return path; } virtual String GetName() const { return path.GetFileName(); } virtual String GetFullPath() const { if (!path.IsPathRooted()) BRICKS_FEATURE_THROW(NotSupportedException()); return path; } virtual ReturnPointer<FileNode> GetParent() const = 0; virtual ReturnPointer<FileNode> GetLeaf(const String& path) const = 0; virtual void CreateFile(FilePermissions::Enum permissions = FilePermissions::OwnerReadWrite) = 0; virtual void CreateDirectory(FilePermissions::Enum permissions = FilePermissions::OwnerReadWriteExecute) = 0; virtual bool Exists() const = 0; virtual u64 GetSize() const = 0; virtual ReturnPointer<Stream> OpenStream( FileOpenMode::Enum createmode = FileOpenMode::Open, FileMode::Enum mode = FileMode::ReadWrite, FilePermissions::Enum permissions = FilePermissions::OwnerReadWrite ) = 0; }; } }
#include <Tanker/Groups/Manager.hpp> #include <Tanker/Crypto/Crypto.hpp> #include <Tanker/Crypto/Format/Format.hpp> #include <Tanker/Errors/AssertionError.hpp> #include <Tanker/Errors/Errc.hpp> #include <Tanker/Errors/Exception.hpp> #include <Tanker/Format/Format.hpp> #include <Tanker/Groups/GroupEncryptedKey.hpp> #include <Tanker/Identity/Extract.hpp> #include <Tanker/Identity/PublicIdentity.hpp> #include <Tanker/IdentityUtils.hpp> #include <Tanker/Trustchain/GroupId.hpp> #include <Tanker/Types/SGroupId.hpp> #include <Tanker/Utils.hpp> #include <cppcodec/base64_rfc4648.hpp> using Tanker::Trustchain::GroupId; using Tanker::Trustchain::UserId; using namespace Tanker::Trustchain::Actions; using namespace Tanker::Errors; namespace Tanker { namespace Groups { namespace Manager { tc::cotask<MembersToAdd> fetchFutureMembers( IUserAccessor& userAccessor, std::vector<SPublicIdentity> spublicIdentities) { spublicIdentities = removeDuplicates(std::move(spublicIdentities)); auto const publicIdentities = extractPublicIdentities(spublicIdentities); auto const members = partitionIdentities(publicIdentities); auto const memberUsers = TC_AWAIT(userAccessor.pull(members.userIds)); if (!memberUsers.notFound.empty()) { auto const notFoundIdentities = mapIdsToStrings( memberUsers.notFound, spublicIdentities, members.userIds); throw formatEx(Errc::InvalidArgument, "unknown users: {:s}", fmt::join(notFoundIdentities, ", ")); } auto const memberProvisionalUsers = TC_AWAIT( userAccessor.pullProvisional(members.publicProvisionalIdentities)); TC_RETURN((MembersToAdd{ memberUsers.found, memberProvisionalUsers, })); } namespace { UserGroupCreation::v2::Members generateGroupKeysForUsers2( Crypto::PrivateEncryptionKey const& groupPrivateEncryptionKey, std::vector<User> const& users) { UserGroupCreation::v2::Members keysForUsers; for (auto const& user : users) { if (!user.userKey) throw AssertionError("cannot create group for users without a user key"); keysForUsers.emplace_back( user.id, *user.userKey, Crypto::sealEncrypt(groupPrivateEncryptionKey, *user.userKey)); } return keysForUsers; } UserGroupCreation::v2::ProvisionalMembers generateGroupKeysForProvisionalUsers( Crypto::PrivateEncryptionKey const& groupPrivateEncryptionKey, std::vector<PublicProvisionalUser> const& users) { UserGroupCreation::v2::ProvisionalMembers keysForUsers; for (auto const& user : users) { auto const encryptedKeyOnce = Crypto::sealEncrypt( groupPrivateEncryptionKey, user.appEncryptionPublicKey); auto const encryptedKeyTwice = Crypto::sealEncrypt(encryptedKeyOnce, user.tankerEncryptionPublicKey); keysForUsers.emplace_back(user.appSignaturePublicKey, user.tankerSignaturePublicKey, encryptedKeyTwice); } return keysForUsers; } } std::vector<uint8_t> generateCreateGroupBlock( std::vector<User> const& memberUsers, std::vector<PublicProvisionalUser> const& memberProvisionalUsers, BlockGenerator const& blockGenerator, Crypto::SignatureKeyPair const& groupSignatureKey, Crypto::EncryptionKeyPair const& groupEncryptionKey) { auto const groupSize = memberUsers.size() + memberProvisionalUsers.size(); if (groupSize == 0) throw formatEx(Errc::InvalidArgument, "cannot create an empty group"); else if (groupSize > MAX_GROUP_SIZE) { throw formatEx(Errc::GroupTooBig, TFMT("cannot create a group with {:d} members, max is {:d}"), groupSize, MAX_GROUP_SIZE); } return blockGenerator.userGroupCreation2( groupSignatureKey, groupEncryptionKey.publicKey, generateGroupKeysForUsers2(groupEncryptionKey.privateKey, memberUsers), generateGroupKeysForProvisionalUsers(groupEncryptionKey.privateKey, memberProvisionalUsers)); } tc::cotask<SGroupId> create( UserAccessor& userAccessor, BlockGenerator const& blockGenerator, Client& client, std::vector<SPublicIdentity> const& spublicIdentities) { auto const members = TC_AWAIT(fetchFutureMembers(userAccessor, spublicIdentities)); auto groupEncryptionKey = Crypto::makeEncryptionKeyPair(); auto groupSignatureKey = Crypto::makeSignatureKeyPair(); auto const groupBlock = generateCreateGroupBlock(members.users, members.provisionalUsers, blockGenerator, groupSignatureKey, groupEncryptionKey); TC_AWAIT(client.pushBlock(groupBlock)); TC_RETURN(cppcodec::base64_rfc4648::encode(groupSignatureKey.publicKey)); } std::vector<uint8_t> generateAddUserToGroupBlock( std::vector<User> const& memberUsers, std::vector<PublicProvisionalUser> const& memberProvisionalUsers, BlockGenerator const& blockGenerator, InternalGroup const& group) { auto const groupSize = memberUsers.size() + memberProvisionalUsers.size(); if (groupSize == 0) { throw Exception(make_error_code(Errc::InvalidArgument), "must add at least one member to a group"); } else if (groupSize > MAX_GROUP_SIZE) { throw formatEx(Errc::GroupTooBig, TFMT("cannot add {:d} members to a group, max is {:d}"), groupSize, MAX_GROUP_SIZE); } return blockGenerator.userGroupAddition2( group.signatureKeyPair, group.lastBlockHash, generateGroupKeysForUsers2(group.encryptionKeyPair.privateKey, memberUsers), generateGroupKeysForProvisionalUsers(group.encryptionKeyPair.privateKey, memberProvisionalUsers)); } tc::cotask<void> updateMembers( UserAccessor& userAccessor, BlockGenerator const& blockGenerator, Client& client, IAccessor& groupAccessor, GroupId const& groupId, std::vector<SPublicIdentity> const& spublicIdentitiesToAdd) { auto const members = TC_AWAIT(fetchFutureMembers(userAccessor, spublicIdentitiesToAdd)); auto const groups = TC_AWAIT(groupAccessor.getInternalGroups({groupId})); if (groups.found.empty()) throw formatEx(Errc::InvalidArgument, "no such group: {:s}", groupId); auto const groupBlock = generateAddUserToGroupBlock( members.users, members.provisionalUsers, blockGenerator, groups.found[0]); TC_AWAIT(client.pushBlock(groupBlock)); } } } }
#include "kinect.hpp" #include "conversion.hpp" #include "util.hpp" #include <cstddef> #include <cstdint> #include <cstdio> #include <filesystem> #include <fstream> #include <future> #include <iostream> #include <iterator> #include <string> #include <string_view> #include <system_error> namespace mik { using std::size_t; using std::uint32_t; using std::uint8_t; Kinect::Kinect(KinectConfig config) : config_(config) { if (!std::filesystem::exists(config_.image_output_dir)) { std::cout << config_.image_output_dir.c_str() << " does not exist, creating it...\n"; std::error_code error; if (!std::filesystem::create_directory(config_.image_output_dir, error)) { exit_with_error(HERE, "Could not create directory \'" + std::string(config_.image_output_dir) + "\': " + error.message()); } std::cout << "Created " << config_.image_output_dir.c_str() << "\n"; } std::cout << "Writing images to " << config_.image_output_dir << "\n"; // Log to console libfreenect2::setGlobalLogger(libfreenect2::createConsoleLogger(libfreenect2::Logger::Debug)); switch (config.framework) { case InputPipeline::CUDA: pipeline_ = new libfreenect2::CudaPacketPipeline(config_.gpu_device_id); break; case InputPipeline::CPU: pipeline_ = new libfreenect2::CpuPacketPipeline(); break; case InputPipeline::OPENGL: pipeline_ = new libfreenect2::OpenGLPacketPipeline(); break; case InputPipeline::OTHER: exit_with_error(HERE, "InputFramework is not supported!"); std::exit(1); break; } if (freenect2_.enumerateDevices() == 0) { exit_with_error(HERE, "no device connected!"); } const std::string serial_device_desc = freenect2_.getDefaultDeviceSerialNumber(); if (!pipeline_) { exit_with_error(HERE, "Could not open input pipeline"); } std::cout << "Serial device: " << serial_device_desc << "\n"; device_ptr_ = freenect2_.openDevice(serial_device_desc, pipeline_); if (!device_ptr_->start()) { exit_with_error(HERE, "Could not start Freenect2Device!"); } // Set up listener listener_ptr_ = new libfreenect2::SyncMultiFrameListener( libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth); device_ptr_->setColorFrameListener(listener_ptr_); device_ptr_->setIrAndDepthFrameListener(listener_ptr_); std::cout << "Device started\n"; std::cout << " Serial number: " << device_ptr_->getSerialNumber() << "\n"; std::cout << " Firmware version: " << device_ptr_->getFirmwareVersion() << "\n"; registration_ = new libfreenect2::Registration(device_ptr_->getIrCameraParams(), device_ptr_->getColorCameraParams()); undistorted_ptr_ = new libfreenect2::Frame(512, 424, 4); registered_ptr_ = new libfreenect2::Frame(512, 424, 4); } void Kinect::start_recording() { std::cout << "starting to record\n"; should_record_ = true; recorder_ = std::thread([this]() { constexpr int frame_timeout_ms = 10 * 1'000; while (should_record_) { if (!listener_ptr_->waitForNewFrame(frame_map_, frame_timeout_ms)) { exit_with_error(HERE, "Waited too long to get a frame!"); } libfreenect2::Frame* rgb_frame = frame_map_[libfreenect2::Frame::Color]; [[maybe_unused]] libfreenect2::Frame* ir_frame = frame_map_[libfreenect2::Frame::Ir]; libfreenect2::Frame* depth_frame = frame_map_[libfreenect2::Frame::Depth]; registration_->apply(rgb_frame, depth_frame, undistorted_ptr_, registered_ptr_); save_frame_async(libfreenect2::Frame::Color, rgb_frame); save_gnet_frame_async(libfreenect2::Frame::Color, rgb_frame); save_frame_async(libfreenect2::Frame::Ir, ir_frame); save_frame_async(libfreenect2::Frame::Depth, depth_frame); } }); } void Kinect::stop_recording() { should_record_ = false; std::cout << "Told recorder to stop\n"; } void Kinect::save_frames(std::uint32_t n_frames_to_save) { constexpr int frame_timeout_ms = 10 * 1'000; std::uint32_t n_frames_saved = 0; std::cout << "Writing frames to " << std::filesystem::absolute(config_.image_output_dir) << "\n"; while (n_frames_saved < n_frames_to_save) { if (!listener_ptr_->waitForNewFrame(frame_map_, frame_timeout_ms)) { exit_with_error(HERE, "Waited too long to get a frame!"); } libfreenect2::Frame* rgb_frame = frame_map_[libfreenect2::Frame::Color]; libfreenect2::Frame* ir_frame = frame_map_[libfreenect2::Frame::Ir]; libfreenect2::Frame* depth_frame = frame_map_[libfreenect2::Frame::Depth]; registration_->apply(rgb_frame, depth_frame, undistorted_ptr_, registered_ptr_); save_frame_async(libfreenect2::Frame::Color, rgb_frame); save_gnet_frame_async(libfreenect2::Frame::Color, rgb_frame); save_frame_async(libfreenect2::Frame::Ir, ir_frame); save_frame_async(libfreenect2::Frame::Depth, depth_frame); } } std::string Kinect::frame_type_to_string(libfreenect2::Frame::Type type) { switch (type) { case libfreenect2::Frame::Color: return "Color"; case libfreenect2::Frame::Ir: return "Infrared"; case libfreenect2::Frame::Depth: return "Depth"; default: return "Unknown"; } } std::string Kinect::frame_format_to_string(libfreenect2::Frame::Format format) { switch (format) { case libfreenect2::Frame::Format::Invalid: return "Invalid"; case libfreenect2::Frame::Format::Raw: return "Raw"; case libfreenect2::Frame::Format::Float: return "Float"; case libfreenect2::Frame::Format::BGRX: return "BGRX"; case libfreenect2::Frame::Format::RGBX: return "RGBX"; case libfreenect2::Frame::Format::Gray: return "Gray"; default: return "Unknown"; } } void Kinect::save_frame_impl(std::filesystem::path image_output_dir, libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame) { const auto frame_dimensions = std::to_string(frame->width) + "x" + std::to_string(frame->height); const auto file_name = frame_type_to_string(frame_type) + "-" + frame_dimensions + "-" + frame_format_to_string(frame->format) + "-seq" + std::to_string(frame->sequence) + ".bin"; const auto file_path = image_output_dir / file_name; // We're writing out unsigned char instead of sgned char std::basic_ofstream<unsigned char, std::char_traits<unsigned char>> output_stream( file_path, output_stream.out | output_stream.binary); if (!output_stream.is_open()) { exit_with_error(HERE, "Could not open output stream: " + file_path.string()); } else { std::cout << "Saving frame to " << file_path << "\n"; const std::size_t n_pixels = frame->width * frame->height; output_stream.write(frame->data, static_cast<std::streamsize>(n_pixels * frame->bytes_per_pixel)); std::cout << "Frame saved.\n "; } } // Synchronous void Kinect::save_frame(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame) const { save_frame_impl(config_.image_output_dir, frame_type, frame); } // Maybe this should just be running on a single separate thread void Kinect::save_frame_async(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame) { auto task = std::async([image_output_dir = config_.image_output_dir, frame_type, frame]() { save_frame_impl(image_output_dir / "kinect", frame_type, frame); }); saveTasks_.push(std::move(task)); } void Kinect::save_gnet_frame_async(libfreenect2::Frame::Type frame_type, const libfreenect2::Frame* frame) { if (frame_type == libfreenect2::Frame::Type::Color) { const auto gn_frame = Conversion::from_kinect_frame(libfreenect2::Frame::Color, frame); gn_frame->save_frame(config_.image_output_dir / "gesturenet", frame->sequence); } else { std::cerr << "Not saving frame " << std::to_string(frame->sequence) << " since it's not RGB\n"; } } Kinect::~Kinect() { while (!saveTasks_.empty()) { std::cout << "Waiting for saveTasks_. " << std::to_string(saveTasks_.size()) << " task(s) are left.\n"; if (saveTasks_.front().valid()) { try { saveTasks_.front().get(); } catch (const std::exception& e) { std::cerr << "Could not finish save task: " << e.what() << '\n'; } }; saveTasks_.pop(); } listener_ptr_->release(frame_map_); device_ptr_->stop(); device_ptr_->close(); delete registration_; if (recorder_.joinable()) { recorder_.join(); } } } // namespace mik
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <fstream> #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; // shapes -> circle, square // renderer -> raster, vector // -> 2x2 cartesian product struct Renderer { virtual void render_circle(float x, float y, float radius) = 0; }; struct VectorRenderer : Renderer { void render_circle(float x, float y, float radius) override { std::cout << "rasterizing a circle of radius " << radius << std::endl; } }; struct RasterRenderer : Renderer { void render_circle(float x, float y, float radius) override { std::cout << "drawing a vector circle of radis " << radius << std::endl; } }; struct Shape { protected: Renderer &renderer; Shape(Renderer &renderer) : renderer(renderer) {} public: virtual void draw() = 0; virtual void resize(float factor) = 0; }; struct Circle : public Shape { float x,y, radius; Circle(Renderer &renderer, float x, float y, float radius) : Shape(renderer), x{x}, y{y}, radius{radius} {} void draw() override { renderer.render_circle(x, y, radius); } void resize(float factor) override { radius *= factor; } }; int main() { RasterRenderer rr; Circle raster_circle{rr, 5,5,5}; raster_circle.draw(); raster_circle.resize(2); raster_circle.draw(); return 0; }
#include "_pch.h" #include "ModelClsPath.h" #include "ModelBrowser.h" using namespace wh; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const std::shared_ptr<const ICls64> ModelClsPath::mRoot = std::make_shared<ClsRec64>(1, "ClsRoot", ClsKind::Abstract, nullptr); //----------------------------------------------------------------------------- ModelClsPath::ModelClsPath() { } //----------------------------------------------------------------------------- std::shared_ptr<const ICls64> ModelClsPath::GetCurrent() { return (mData.empty()) ? mRoot : mData.back(); } //----------------------------------------------------------------------------- void ModelClsPath::Refresh(const int64_t& cid) { TEST_FUNC_TIME; wxLongLong ll_cid((cid <= 1) ? 1 : cid); auto id = ll_cid.ToString(); mData.clear(); wxString query = wxString::Format( "SELECT id, title,kind,pid, measure" " FROM get_path_cls_info(%s, 1)" , id); whDataMgr::GetDB().BeginTransaction(); auto table = whDataMgr::GetDB().ExecWithResultsSPtr(query); if (table) { size_t row = 0; unsigned int rowQty = table->GetRowCount(); for (size_t i = rowQty; i > 0; --i) { row = i - 1; int64_t id; if (!table->GetAsString(0, row).ToLongLong(&id)) throw; auto cls = std::make_shared<ClsRec64>(id, nullptr); table->GetAsString(1, row, cls->mTitle); ToClsKind(table->GetAsString(2, row), cls->mKind); cls->SetParentId(table->GetAsString(3, row)); table->GetAsString(4, row, cls->mMeasure); cls->mObjQty.Clear(); mData.emplace_back(cls); } }//if (table) whDataMgr::GetDB().Commit(); } //----------------------------------------------------------------------------- wxString ModelClsPath::AsString() const { wxString ret = "/"; std::for_each(mData.crbegin(), mData.crend(), [&ret] (const std::shared_ptr<const ICls64>& curr) { const auto& title = curr->GetTitle(); if (wxNOT_FOUND == title.Find('/')) ret = wxString::Format("/%s%s", title, ret); else ret = wxString::Format("/[%s]%s", title, ret); }); return ret; } //----------------------------------------------------------------------------- void ModelClsPath::SetId(const wxString& str) { if (!str.IsEmpty()) { int64_t tmp; if (str.ToLongLong(&tmp)) { SetId(tmp); return; } } SetId(1); } //----------------------------------------------------------------------------- void ModelClsPath::SetId(const int64_t& val) { Refresh(val); }
#include "gtest/gtest.h" #include "wali/wfa/WFA.hpp" #include "fixtures/SimpleWeights.hpp" #include "fixtures/StringWeight.hpp" #include "fixtures/Keys.hpp" #include "fixtures.hpp" using namespace testing; using namespace testing::ShortestPathWeights; using wali::wfa::WFA; using wali::sem_elem_t; using wali::WALI_EPSILON; namespace wali { namespace wfa { TEST(wali$wfa$$endOfEpsilonChain, threeEpsTransInARowEndAtEnd) { ChainedEpsilonTransitions wfa(dist1, dist10, dist20); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st1); EXPECT_EQ(wfa.keys.st4, p.first); EXPECT_TRUE(dist31->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, threeEpsTransInARowEndAtEndExtendOrderIsCorrect) { sem_elem_t first = new StringWeight("first"), second = new StringWeight("second"), third = new StringWeight("third"), all = new StringWeight("first second third"); ChainedEpsilonTransitions wfa(first, second, third); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st1); EXPECT_TRUE(all->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, noOutgoingEps) { ChainedEpsilonTransitions wfa(dist1, dist10, dist20); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st4); EXPECT_EQ(wfa.keys.st4, p.first); EXPECT_TRUE(dist0->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, chainStopsAtNormal) { EpsTransThenNormal wfa(dist1, dist10); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st1); EXPECT_EQ(wfa.keys.st2, p.first); EXPECT_TRUE(dist1->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, chainStartingFromNormalStopsThere) { EpsTransThenNormal wfa(dist1, dist10); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st2); EXPECT_EQ(wfa.keys.st2, p.first); EXPECT_TRUE(dist0->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, chainStopsAtBranch) { Branching wfa(dist1, dist10, dist10); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st1); EXPECT_EQ(wfa.keys.st2, p.first); EXPECT_TRUE(dist1->equal(p.second)); } TEST(wali$wfa$$endOfEpsilonChain, chainStartingAtBranchStopsThere) { Branching wfa(dist1, dist10, dist10); std::pair<Key, sem_elem_t> p = wfa.wfa.endOfEpsilonChain(wfa.keys.st2); EXPECT_EQ(wfa.keys.st2, p.first); EXPECT_TRUE(dist0->equal(p.second)); } TEST(wali$wfa$$removeStatesWithInDegree0, willNotRemoveStartState) { SingleState f1(dist0), f2(dist0); f1.wfa.removeStatesWithInDegree0(); EXPECT_TRUE(f1.wfa.equal(f2.wfa)); } TEST(wali$wfa$$removeStatesWithInDegree0, removeIsolatedState) { SingleState f1(dist0), f2(dist0); f1.wfa.addState(f1.keys.st2, dist0->zero()); f1.wfa.removeStatesWithInDegree0(); EXPECT_TRUE(f1.wfa.equal(f2.wfa)); } TEST(wali$wfa$$collapseEpsilonChains, bigTest) { BigEpsilonTest f; f.wfa.collapseEpsilonChains(); EXPECT_TRUE(f.wfa.equal(f.expected)); } } }
#ifndef POINT1F_H_INCLUDED #define POINT1F_H_INCLUDED #include "Point.h" template <typename type> class container1{ public: union{ type array[1]; struct{ type x; }; }; }; template <typename type> class Point1 : public Point<container1<type>, 1> { public: Point1( type x = 0.0f ){ this->x = x; } Point1( const Point<container1<type>, 1>& arg ){ this->x = arg.x; } }; typedef Point1<float> Point1f; #endif // POINT1F_H_INCLUDED
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE /** * @brief A classe MainWindow é a janela principal do programa, * onde está disposta toda a interface e suas funcionalidades. */ class MainWindow : public QMainWindow { Q_OBJECT public: /** * @brief MainWindow é o construtor da classe. * @param parent é a referência ao pai da classe */ MainWindow(QWidget *parent = nullptr); /** * @brief ~MainWindow */ ~MainWindow(); public slots: /** * @brief updateSliders atualiza os valores dos botões deslizantes quando um novo escultor é criado. */ void updateSliders(); private slots: /** * @brief on_actionExit_triggered fecha o programa ao clicar na ação de saída. */ void on_actionExit_triggered(); private: /** * @brief ui é a referência à interface gráfica */ Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
// PrioQueue.hpp #ifndef __PRIOQUEUE__HPP__ #define __PRIOQUEUE__HPP__ #include "PQElmt.hpp" class PrioQueue { private: PQElmt* queue; int neff; int maxEl; public: PrioQueue(); PrioQueue(int maxEl); PrioQueue(const PrioQueue& pq); ~PrioQueue(); void push(PQElmt el); // Menambahkan elemen ke array queue pada indeks pertama // sehingga seluruh elemen sesudahnya bernilai lebih besar // dari el PQElmt pop(); // Menghapus elemen pertama dari array, // menggeser semua elemen rapat kiri, // dan mengembalikan elemen pertama. friend PrioQueue operator+(const PrioQueue& a, const PrioQueue& b); // Membuat PrioQueue baru dengan maxEl = a.maxEl + b.maxEl dan // berisi gabungan dari elemen kedua PrioQueue PQElmt operator[](int k); // Mengakses elemen ke-k dari PrioQueue. Jika k bukan indeks yang valid, // kembalikan elemen default }; #endif
using namespace std; class Host{ public: string ip; string mac; };
#ifndef SHADERFINDER_H #define SHADERFINDER_H #include <string> #include <set> #include <map> #include <utility> #include "Configfile.h" class ShaderFinder { public: /** Default constructor */ ShaderFinder(); /** Default destructor */ virtual ~ShaderFinder(); bool Init(); bool LoadInputListFromFile(const std::string& filename); void ParseShaderFiles(); std::pair<bool, std::string> GetFileContent(const std::string& filename); void Go(); void Error(const std::string& message); protected: Configfile mConfig; std::string mListpath; std::string mShaderpath; std::set<std::string> mInputList; std::set<std::string> mOutputList; std::map<std::string, std::set<std::string> > mShaders; }; #endif // SHADERFINDER_H
#include<bits/stdc++.h> using namespace std; using ll=long long; ll mod_mul(ll x,ll y,ll mod) { x%=mod; y%=mod; ll t=0; while(y) { if(y&1) t=(t+x)%mod; x=(x<<1)%mod; y>>=1; } return t; } ll mod_pow(ll x,ll n,ll mod) { x%=mod; ll res=1; while(n) { if(n&1) res=mod_mul(res,x,mod); x=mod_mul(x,x,mod); n>>=1; } return res; } int main(){ ios::sync_with_stdio(false); cin.tie(0); int b,p,m; while(cin>>b){ cin>>p>>m; cout<<mod_pow(b,p,m)<<"\n";; } return 0; }
#include <iostream> #include <ros/ros.h> #include <mavros_msgs/PositionTarget.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Point32.h> geometry_msgs::Point positionmsg; bool got_position = false; mavros_msgs::PositionTarget waypoint; void callback(const geometry_msgs::Point32& msg) { double x = msg.x; double y = msg.y; double z = msg.z; positionmsg.x = x; positionmsg.y = y; positionmsg.z = z + (2.1 - z); got_position = true; waypoint.position = positionmsg; ROS_INFO("Message received Control"); ROS_WARN_STREAM(waypoint); } int main(int argc, char** argv){ ros::init(argc, argv, "control_node"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/control/position_setpoint", 1, callback); ros::Publisher pub = n.advertise<mavros_msgs::PositionTarget>("/mavros/setpoint_raw/local", 1); // Main loop ROS_INFO("control is running"); ros::Rate rate(10); while (ros::ok()) { if(got_position == true){ pub.publish(waypoint); ROS_INFO("Publishes Control Message"); } ros::spinOnce(); rate.sleep(); } return 0; }
//--------------------------------------------------------------------------- //更新记录 #ifndef srvthreadH #define srvthreadH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <ScktComp.hpp> //注意 //线程池每个线程的堆栈大小只有32K class CServerSocket; enum ThreadState{tsWAIT,tsCLIENT_CONNECT,tsSERVERCONNECT,tsPROCESS_CLIENT,tsPROCESS_SERVER,tsCLOSE,tsCREATE_FAIL}; String GetThreadStateName(ThreadState StateFlag); //--------------------------------------------------------------------------- class CServerThread { private: int m_Index; //线程池当中的编号 SOCKET m_ClientSocket; CServerSocket * m_ServerSocket; bool m_ClientConnect; //客户端是否连接中 String m_ClientIP; String m_LastError; bool m_Terminated; //是否需要结束线程 HANDLE m_Handle; // 线程句柄 DWORD m_ThreadID; //线程ID DWORD m_StackSize; char * lpRecvBuffer; //接收缓冲区 char * lpSendBuffer; //发送缓冲区 DWORD m_RecvBufSize; //实际分配的接收缓冲区大小 DWORD m_SendBufSize; //实际分配的发送缓冲区大小 protected: void __fastcall Execute(); static DWORD WINAPI ThreadProc(LPVOID lpParameter); public: void * lpUserData; //用户自定义数据 ThreadState State; int RecvLen(); void __fastcall Log(); void __fastcall ErrLog(); public: __fastcall CServerThread(bool CreateSuspended,CServerSocket * ServerSocket,DWORD StackSize,int Index); __fastcall ~CServerThread(); int Recv(char * lpBuffer,int Len); int Send(char * lpBuffer,int Len); void CloseSocket(); void ShowLog(String LogStr); void ShowErrLog(String LogStr); String GetClientIP(){return m_ClientIP;} SOCKET GetSocket(){return m_ClientSocket;} void Terminate(){m_Terminated=true;}//结束线程运行 DWORD GetThreadID(){return m_ThreadID;} HANDLE GetThreadHandle(){return m_Handle;} String LastError(){return m_LastError;} char * RecvBufPtr(){return lpRecvBuffer;} //获取接收数据缓冲区指针 char * SendBufPtr(){return lpSendBuffer;} //获取发送数据缓冲区指针 DWORD RecvBufSize(){return m_RecvBufSize;} //获取实际分配的接收缓冲区大小 DWORD SendBufSize(){return m_SendBufSize;}//获取实际分配的发送缓冲区大小 String GetState(); int GetIndex(){return m_Index;} //获取该线程对象在线程池当中的编号 }; //--------------------------------------------------------------------------- #endif
/*==================================================================== Copyright(c) 2018 Adam Rankin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================*/ // Local includes #include "pch.h" #include "MathCommon.h" using namespace Windows::Foundation::Numerics; namespace HoloIntervention { //---------------------------------------------------------------------------- bool OpenCVToFloat4x4(const cv::InputArray& inMatrix, float4x4& outMatrix) { if (inMatrix.cols() != 4 || inMatrix.rows() != 4 || inMatrix.channels() != 1 || inMatrix.depth() != CV_32F) { return false; } auto mat = inMatrix.getMat(); outMatrix.m11 = mat.at<float>(0, 0); outMatrix.m12 = mat.at<float>(0, 1); outMatrix.m13 = mat.at<float>(0, 2); outMatrix.m14 = mat.at<float>(0, 3); outMatrix.m21 = mat.at<float>(1, 0); outMatrix.m22 = mat.at<float>(1, 1); outMatrix.m23 = mat.at<float>(1, 2); outMatrix.m24 = mat.at<float>(1, 3); outMatrix.m31 = mat.at<float>(2, 0); outMatrix.m32 = mat.at<float>(2, 1); outMatrix.m33 = mat.at<float>(2, 2); outMatrix.m34 = mat.at<float>(2, 3); outMatrix.m41 = mat.at<float>(3, 0); outMatrix.m42 = mat.at<float>(3, 1); outMatrix.m43 = mat.at<float>(3, 2); outMatrix.m44 = mat.at<float>(3, 3); return true; } //---------------------------------------------------------------------------- bool OpenCVToFloat4x4(const cv::Mat& inRotationMatrix, const cv::Mat& inTranslationMatrix, Windows::Foundation::Numerics::float4x4& outMatrix) { outMatrix = float4x4::identity(); outMatrix.m11 = inRotationMatrix.at<float>(0, 0); outMatrix.m12 = inRotationMatrix.at<float>(0, 1); outMatrix.m13 = inRotationMatrix.at<float>(0, 2); outMatrix.m21 = inRotationMatrix.at<float>(1, 0); outMatrix.m22 = inRotationMatrix.at<float>(1, 1); outMatrix.m23 = inRotationMatrix.at<float>(1, 2); outMatrix.m31 = inRotationMatrix.at<float>(2, 0); outMatrix.m32 = inRotationMatrix.at<float>(2, 1); outMatrix.m33 = inRotationMatrix.at<float>(2, 2); outMatrix.m14 = inTranslationMatrix.at<float>(0, 0); outMatrix.m24 = inTranslationMatrix.at<float>(1, 0); outMatrix.m34 = inTranslationMatrix.at<float>(2, 0); outMatrix = transpose(outMatrix); return true; } //---------------------------------------------------------------------------- bool Float4x4ToOpenCV(const float4x4& inMatrix, cv::Mat& outMatrix) { float array[16]; if (!Float4x4ToArray(inMatrix, array)) { return false; } outMatrix = cv::Mat(4, 4, CV_32F, array); return true; } //---------------------------------------------------------------------------- bool Float4x4ToOpenCV(const Windows::Foundation::Numerics::float4x4& inMatrix, cv::Mat& outRotation, cv::Mat& outTranslation) { outRotation = cv::Mat::eye(3, 3, CV_32F); outTranslation = cv::Mat::zeros(3, 1, CV_32F); outRotation.at<float>(0, 0) = inMatrix.m11; outRotation.at<float>(0, 1) = inMatrix.m12; outRotation.at<float>(0, 2) = inMatrix.m13; outRotation.at<float>(1, 0) = inMatrix.m21; outRotation.at<float>(1, 1) = inMatrix.m22; outRotation.at<float>(1, 2) = inMatrix.m23; outRotation.at<float>(2, 0) = inMatrix.m31; outRotation.at<float>(2, 1) = inMatrix.m32; outRotation.at<float>(2, 2) = inMatrix.m33; outTranslation.at<float>(0, 0) = inMatrix.m14; outTranslation.at<float>(1, 0) = inMatrix.m24; outTranslation.at<float>(2, 0) = inMatrix.m34; return true; } //---------------------------------------------------------------------------- bool Float4x4ToArray(const float4x4& inMatrix, float outMatrix[16]) { outMatrix[0] = inMatrix.m11; outMatrix[1] = inMatrix.m12; outMatrix[2] = inMatrix.m13; outMatrix[3] = inMatrix.m14; outMatrix[4] = inMatrix.m21; outMatrix[5] = inMatrix.m22; outMatrix[6] = inMatrix.m23; outMatrix[7] = inMatrix.m24; outMatrix[8] = inMatrix.m31; outMatrix[9] = inMatrix.m32; outMatrix[10] = inMatrix.m33; outMatrix[11] = inMatrix.m34; outMatrix[12] = inMatrix.m41; outMatrix[13] = inMatrix.m42; outMatrix[14] = inMatrix.m43; outMatrix[15] = inMatrix.m44; return true; } //---------------------------------------------------------------------------- bool Float4x4ToArray(const float4x4& inMatrix, std::array<float, 16> outMatrix) { return Float4x4ToArray(inMatrix, outMatrix.data()); } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const float (&inMatrix)[16], float4x4& outMatrix) { outMatrix.m11 = inMatrix[0]; outMatrix.m12 = inMatrix[1]; outMatrix.m13 = inMatrix[2]; outMatrix.m14 = inMatrix[3]; outMatrix.m21 = inMatrix[4]; outMatrix.m22 = inMatrix[5]; outMatrix.m23 = inMatrix[6]; outMatrix.m24 = inMatrix[7]; outMatrix.m31 = inMatrix[8]; outMatrix.m32 = inMatrix[9]; outMatrix.m33 = inMatrix[10]; outMatrix.m34 = inMatrix[11]; outMatrix.m41 = inMatrix[12]; outMatrix.m42 = inMatrix[13]; outMatrix.m43 = inMatrix[14]; outMatrix.m44 = inMatrix[15]; return true; } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const std::array<float, 16>& inMatrix, float4x4& outMatrix) { return ArrayToFloat4x4(inMatrix.data(), 16, outMatrix); } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const float (&inMatrix)[9], float4x4& outMatrix) { outMatrix = float4x4::identity(); outMatrix.m11 = inMatrix[0]; outMatrix.m12 = inMatrix[1]; outMatrix.m13 = inMatrix[2]; outMatrix.m21 = inMatrix[4]; outMatrix.m22 = inMatrix[5]; outMatrix.m23 = inMatrix[6]; outMatrix.m31 = inMatrix[8]; outMatrix.m32 = inMatrix[9]; outMatrix.m33 = inMatrix[10]; return true; } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const std::array<float, 9>& inMatrix, float4x4& outMatrix) { return ArrayToFloat4x4(inMatrix.data(), 9, outMatrix); } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const float* inMatrix, uint32 matrixSize, Windows::Foundation::Numerics::float4x4& outMatrix) { if (matrixSize != 3 && matrixSize != 4) { return false; } outMatrix = float4x4::identity(); if (matrixSize == 3) { outMatrix.m11 = inMatrix[0]; outMatrix.m12 = inMatrix[1]; outMatrix.m13 = inMatrix[2]; outMatrix.m21 = inMatrix[3]; outMatrix.m22 = inMatrix[4]; outMatrix.m23 = inMatrix[5]; outMatrix.m31 = inMatrix[6]; outMatrix.m32 = inMatrix[7]; outMatrix.m33 = inMatrix[8]; } else { outMatrix.m11 = inMatrix[0]; outMatrix.m12 = inMatrix[1]; outMatrix.m13 = inMatrix[2]; outMatrix.m14 = inMatrix[3]; outMatrix.m21 = inMatrix[4]; outMatrix.m22 = inMatrix[5]; outMatrix.m23 = inMatrix[6]; outMatrix.m24 = inMatrix[7]; outMatrix.m31 = inMatrix[8]; outMatrix.m32 = inMatrix[9]; outMatrix.m33 = inMatrix[10]; outMatrix.m34 = inMatrix[11]; outMatrix.m41 = inMatrix[12]; outMatrix.m42 = inMatrix[13]; outMatrix.m43 = inMatrix[14]; outMatrix.m44 = inMatrix[15]; } return true; } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const float(&inMatrix)[4][4], Windows::Foundation::Numerics::float4x4& outMatrix) { outMatrix.m11 = inMatrix[0][0]; outMatrix.m12 = inMatrix[0][1]; outMatrix.m13 = inMatrix[0][2]; outMatrix.m14 = inMatrix[0][3]; outMatrix.m21 = inMatrix[1][0]; outMatrix.m22 = inMatrix[1][1]; outMatrix.m23 = inMatrix[1][2]; outMatrix.m24 = inMatrix[1][3]; outMatrix.m31 = inMatrix[2][0]; outMatrix.m32 = inMatrix[2][1]; outMatrix.m33 = inMatrix[2][2]; outMatrix.m34 = inMatrix[2][3]; outMatrix.m41 = inMatrix[3][0]; outMatrix.m42 = inMatrix[3][1]; outMatrix.m43 = inMatrix[3][2]; outMatrix.m44 = inMatrix[3][3]; return true; } //---------------------------------------------------------------------------- bool ArrayToFloat4x4(const float(&inMatrix)[3][3], Windows::Foundation::Numerics::float4x4& outMatrix) { outMatrix.m11 = inMatrix[0][0]; outMatrix.m12 = inMatrix[0][1]; outMatrix.m13 = inMatrix[0][2]; outMatrix.m21 = inMatrix[1][0]; outMatrix.m22 = inMatrix[1][1]; outMatrix.m23 = inMatrix[1][2]; outMatrix.m31 = inMatrix[2][0]; outMatrix.m32 = inMatrix[2][1]; outMatrix.m33 = inMatrix[2][2]; return true; } //---------------------------------------------------------------------------- std::wstring PrintMatrix(const Windows::Foundation::Numerics::float4x4& matrix) { std::wostringstream woss; woss << matrix.m11 << " " << matrix.m12 << " " << matrix.m13 << " " << matrix.m14 << " " << matrix.m21 << " " << matrix.m22 << " " << matrix.m23 << " " << matrix.m24 << " " << matrix.m31 << " " << matrix.m32 << " " << matrix.m33 << " " << matrix.m34 << " " << matrix.m41 << " " << matrix.m42 << " " << matrix.m43 << " " << matrix.m44 << std::endl; return woss.str(); } //---------------------------------------------------------------------------- float4x4 ReadMatrix(const std::wstring& string) { float4x4 result; std::wstringstream wss; wss << string; try { wss >> result.m11; wss >> result.m12; wss >> result.m13; wss >> result.m14; wss >> result.m21; wss >> result.m22; wss >> result.m23; wss >> result.m24; wss >> result.m31; wss >> result.m32; wss >> result.m33; wss >> result.m34; wss >> result.m41; wss >> result.m42; wss >> result.m43; wss >> result.m44; } catch (...) { WLOG_ERROR(std::wstring(L"Unable to parse matrix: ") + string); return float4x4::identity(); } return result; } //---------------------------------------------------------------------------- Windows::Foundation::Numerics::float4x4 ReadMatrix(const std::string& string) { return ReadMatrix(std::wstring(begin(string), end(string))); } //---------------------------------------------------------------------------- Windows::Foundation::Numerics::float4x4 ReadMatrix(Platform::String^ string) { return ReadMatrix(std::wstring(string->Data())); } //---------------------------------------------------------------------------- void LinesIntersection(const std::vector<Line>& lines, Point& outPoint, float& outFRE) { /* based on the following doc by Johannes Traa (UIUC 2013) Least-Squares Intersection of Lines http://cal.cs.illinois.edu/~johannes/research/LS_line_intersect.pdf */ auto sizex = 3; outPoint = float3::zero(); cv::Mat I = cv::Mat::eye(sizex, sizex, CV_32F); cv::Mat R = cv::Mat::zeros(sizex, sizex, CV_32F); cv::Mat q = cv::Mat::zeros(sizex, 1, CV_32F); cv::Mat lineDirectionNormalized = cv::Mat::zeros(sizex, 1, CV_32F); cv::Mat lineOrigin = cv::Mat::zeros(sizex, 1, CV_32F); cv::Mat tempR, tempq; for (std::vector<float3>::size_type i = 0; i < lines.size(); i++) { // normalize N float3 norm = normalize(lines[i].second); lineDirectionNormalized.at<float>(0, 0) = norm.x; lineDirectionNormalized.at<float>(1, 0) = norm.y; lineDirectionNormalized.at<float>(2, 0) = norm.z; lineOrigin.at<float>(0, 0) = lines[i].first.x; lineOrigin.at<float>(1, 0) = lines[i].first.y; lineOrigin.at<float>(2, 0) = lines[i].first.z; cv::Mat tempLineDirectionNormTranspose; cv::transpose(lineDirectionNormalized, tempLineDirectionNormTranspose); tempR = I - lineDirectionNormalized * tempLineDirectionNormTranspose; tempq = tempR * lineOrigin; R = R + tempR; q = q + tempq; } cv::Mat RInverse; cv::invert(R, RInverse); cv::Mat output = RInverse * q; outPoint.x = output.at<float>(0, 0); outPoint.y = output.at<float>(1, 0); outPoint.z = output.at<float>(2, 0); // compute FRE outFRE = 0.0; for (std::vector<float3>::size_type i = 0; i < lines.size(); i++) { float3 norm = normalize(lines[i].second); outFRE += PointToLineDistance(outPoint, lines[i].first, norm); } outFRE = outFRE / lines.size(); } //---------------------------------------------------------------------------- float PointToLineDistance(const float3& point, const float3& lineOrigin, const float3& lineDirection) { auto point2 = point + (10 * lineDirection); return length(cross(point - lineOrigin, point - point2)) / length(point2 - lineOrigin); } }
#ifndef DOUBLE_INTEGRATION_HPP #define DOUBLE_INTEGRATION_HPP #include "Function.hpp" #include <cmath> // Curvature for configuration 1. This is the default. double c1(double x, double b) { return (sin(x) + cos(x) + (cos(x) - sin(x))*b)/2.0; } double det1(double x, double l1, double l2) { return (l2 - l1) * (cos(x) - sin(x))/4.0; } // Curvature for configuration 2. double c2(double x, double b) { return sin(x) + cos(x) + (cos(x) - sin(x))*b; } double det2(double x, double l1, double l2) { return (l2 - l1) * (cos(x) - sin(x))/2; } class DoubleIntegration { public: DoubleFunction f, c; Determinant det; double line1, line2; int legendre_points_a, legendre_points_b; double alpha[3]; double beta[3]; double alpha_weight[3]; double beta_weight[3]; DoubleIntegration() { this->c = c1; this->line1 = 3.14159/4; this->line2 = 0.0; } DoubleIntegration(DoubleFunction f, int legendre_points_a, int legendre_points_b) { this->f = f; this->legendre_points_a = legendre_points_a; this->legendre_points_b = legendre_points_b; switch (legendre_points_a) { case 2: alpha_weight[0] = 1.0; alpha_weight[1] = 1.0; alpha[0] = -0.57735; alpha[1] = 0.57735; break; case 3: alpha_weight[0] = 0.55555; alpha_weight[1] = 0.88888; alpha_weight[2] = 0.55555; alpha[0] = -0.77459; alpha[1] = 0.0; alpha[2] = 0.77459; break; } switch(legendre_points_b) { case 2: beta_weight[0] = 1.0; beta_weight[1] = 1.0; beta[0] = -0.57735; beta[1] = 0.57735; break; case 3: beta_weight[0] = 0.55555; beta_weight[1] = 0.88888; beta_weight[2] = 0.55555; beta[0] = -0.77459; beta[1] = 0.0; beta[2] = 0.77459; break; } } DoubleIntegration(DoubleFunction f, int legendre_points_a, int legendre_points_b, int lines_config, int curvature_config) { this->f = f; this->legendre_points_a = legendre_points_a; this->legendre_points_b = legendre_points_b; if (curvature_config == 1) { this->c = c1; this->det = det1; } else { this->c = c2; this->det = det2; } if (lines_config == 1) { this->line2 = 3.14159/4.0; } else { this->line2 = 3.14159/6.0; } this->line1 = 0.0; switch (legendre_points_a) { case 2: alpha_weight[0] = 1.0; alpha_weight[1] = 1.0; alpha[0] = -0.57735; alpha[1] = 0.57735; break; case 3: alpha_weight[0] = 0.55555; alpha_weight[1] = 0.88888; alpha_weight[2] = 0.55555; alpha[0] = -0.77459; alpha[1] = 0.0; alpha[2] = 0.77459; break; } switch(legendre_points_b) { case 2: beta_weight[0] = 1.0; beta_weight[1] = 1.0; beta[0] = -0.57735; beta[1] = 0.57735; break; case 3: beta_weight[0] = 0.55555; beta_weight[1] = 0.88888; beta_weight[2] = 0.55555; beta[0] = -0.77459; beta[1] = 0.0; beta[2] = 0.77459; break; } } double N2(double alpha, double beta) { return (-1.0/4.0)*(alpha+1)*(beta-1); } double N3(double alpha, double beta) { return (1.0/4.0)*(alpha+1)*(beta+1); } double N4(double alpha, double beta) { return (-1.0/4.0)*(alpha-1)*(beta+1); } double X(double alpha, double beta) { // X value for the exam question. return 2*N2(alpha, beta) + 3*N3(alpha, beta) + N4(alpha, beta); // X value for the practice exercise. // return (this->line1 + this->line2 + (this->line2 - this->line1)*alpha)/2.0; } double Y(double alpha, double beta) { // Y value for the exam question. return N2(alpha, beta) + 3*N3(alpha, beta) + 2*N4(alpha, beta); // Y value for the practice exercise. // double x = X(alpha, beta); // return c(x, beta); } double determinant(double x_alpha) { // determinant value for the exam question. return 0.75; // determinant value for the practice exercise. // return det(x_alpha, this->line1, this->line2); } double solve() { double result = 0.0; double x = 0.0, y = 0.0, det = 0.0, fx = 0.0; int i = 0; int j = 0; for (i = 0; i <= legendre_points_a - 1; i++) { for (j = 0; j <= legendre_points_b - 1; j++) { x = X(alpha[i], beta[j]); y = Y(alpha[i], beta[j]); det = determinant(x); fx = f(x, y); result += alpha_weight[i]*beta_weight[j]*fx*det; } } return result; } }; #endif
//---------------------------------------------------------------- // VehicleController.cpp // // Copyright 2002-2004 Raven Software //---------------------------------------------------------------- #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "Vehicle.h" /* ================ rvVehiclePosition::rvVehiclePosition ================ */ rvVehiclePosition::rvVehiclePosition ( void ) { memset ( &mInputCmd, 0, sizeof(mInputCmd) ); mInputAngles.Zero ( ); memset ( &fl, 0, sizeof(fl) ); mCurrentWeapon = -1; mSoundPart = -1; mDriver = NULL; mParent = NULL; mEyeOrigin.Zero(); mEyeAxis.Identity(); mEyeOffset.Zero(); mEyeJoint = INVALID_JOINT; mDriverOffset.Zero ( ); mDriverJoint = INVALID_JOINT; } /* ================ rvVehiclePosition::~rvVehiclePosition ================ */ rvVehiclePosition::~rvVehiclePosition ( void ) { mParts.DeleteContents ( true ); mWeapons.DeleteContents ( true ); } void InitIntArray( const idVec3& vec, int array[] ) { int ix; for( ix = 0; ix < vec.GetDimension(); ++ix ) { array[ix] = (int)vec[ix]; } } /* ================ rvVehiclePosition::Init ================ */ void rvVehiclePosition::Init ( rvVehicle* parent, const idDict& args ) { idVec3 garbage; mParent = parent; mEyeJoint = mParent->GetAnimator()->GetJointHandle ( args.GetString ( "eyeJoint" ) ); // abahr & twhitaker: removed this due to other changes. //if( !mParent->GetAnimator()->GetJointTransform(mEyeJoint, gameLocal.GetTime(), garbage, mEyeJointTransform) ) { mEyeJointTransform.Identity(); //} //mEyeJointTransform.TransposeSelf(); mEyeOffset = args.GetVector ( "eyeOffset", "0 0 0" ); mDeltaEyeAxisScale = args.GetAngles( "deltaEyeAxisScale", "1 1 0" ); mDeltaEyeAxisScale.Clamp( ang_zero, idAngles(1.0f, 1.0f, 1.0f) ); InitIntArray( args.GetVector("eyeJointAxisMap", "0 1 2"), mEyeJointAxisMap ); InitIntArray( args.GetVector("eyeJointDirMap", "1 1 1"), mEyeJointDirMap ); mAxisOffset = args.GetAngles( "angles_offset" ).ToMat3(); mDriverJoint = mParent->GetAnimator()->GetJointHandle ( args.GetString ( "driverJoint" ) ); // abahr & twhitaker: removed this due to other changes. //if( !mParent->GetAnimator()->GetJointTransform(mDriverJoint, gameLocal.GetTime(), garbage, mDriverJointTransform) ) { mDriverJointTransform.Identity(); //} //mDriverJointTransform.TransposeSelf( ); mDriverOffset = args.GetVector ( "driverOffset", "0 0 0" ); mDeltaDriverAxisScale = args.GetAngles( "deltaDriverAxisScale", "1 1 0" ); mDeltaDriverAxisScale.Clamp( ang_zero, idAngles(1.0f, 1.0f, 1.0f) ); InitIntArray( args.GetVector("driverJointAxisMap", "0 1 2"), mDriverJointAxisMap ); InitIntArray( args.GetVector("driverJointDirMap", "1 1 1"), mDriverJointDirMap ); mExitPosOffset = args.GetVector( "exitPosOffset" ); mExitAxisOffset = args.GetAngles( "exitAxisOffset" ).ToMat3(); mDriverAnim = args.GetString ( "driverAnim", "driver" ); fl.driverVisible = args.GetBool ( "driverVisible", "0" ); fl.engine = args.GetBool ( "engine", "0" ); fl.depthHack = args.GetBool ( "depthHack", "1" ); fl.bindDriver = args.GetBool ( "bindDriver", "1" ); args.GetString ( "internalSurface", "", mInternalSurface ); SetParts ( args ); mSoundMaxSpeed = args.GetFloat ( "maxsoundspeed", "0" ); // Looping sound when occupied? if ( *args.GetString ( "snd_loop", "" ) ) { mSoundPart = AddPart ( rvVehicleSound::GetClassType(), args ); static_cast<rvVehicleSound*>(mParts[mSoundPart])->SetAutoActivate ( false ); } SelectWeapon ( 0 ); UpdateInternalView ( true ); } /* ================ rvVehiclePosition::SetParts ================ */ void rvVehiclePosition::SetParts ( const idDict& args ) { const idKeyValue* kv; // Spawn all parts kv = args.MatchPrefix( "def_part", NULL ); while ( kv ) { const idDict* dict; idTypeInfo* typeInfo; // Skip empty strings if ( !kv->GetValue().Length() ) { kv = args.MatchPrefix( "def_part", kv ); continue; } // Get the dictionary for the part dict = gameLocal.FindEntityDefDict ( kv->GetValue() ); if ( !dict ) { gameLocal.Error ( "Invalid vehicle part definition '%'", kv->GetValue().c_str() ); } // Determine the part type typeInfo = idClass::GetClass ( dict->GetString ( "spawnclass" ) ); if ( !typeInfo || !typeInfo->IsType ( rvVehiclePart::GetClassType() ) ) { gameLocal.Error ( "Class '%s' is not a vehicle part", dict->GetString ( "spawnclass" ) ); } // Add the new part AddPart ( *typeInfo, *dict ); kv = args.MatchPrefix( "def_part", kv ); } } /* ================ rvVehiclePosition::AddPart ================ */ int rvVehiclePosition::AddPart ( const idTypeInfo &classdef, const idDict& args ) { rvVehiclePart* part; int soundChannel; // Get a sound channel soundChannel = SND_CHANNEL_CUSTOM; soundChannel += mParts.Num(); // Allocate the new part part = static_cast<rvVehiclePart*>(classdef.CreateInstance ( )); part->Init ( this, args, (s_channelType)soundChannel ); part->CallSpawn ( ); // Weapons go into their own list since only one can be active // and any given point in time. if ( part->IsType ( rvVehicleWeapon::GetClassType() ) ) { return mWeapons.Append ( part ); } return mParts.Append ( part ); } /* ================ rvVehiclePosition::SetDriver ================ */ bool rvVehiclePosition::SetDriver ( idActor* driver ) { if ( mDriver == driver ) { return false; } fl.inputValid = false; if ( driver ) { mDriver = driver; // Keep the driver visible if the position is exposed if ( fl.driverVisible ) { mDriver->Show ( ); } else { mDriver->Hide ( ); // Dont let the player take damage when inside the if not visible mDriver->fl.takedamage = false; } if ( mSoundPart != -1 ) { static_cast<rvVehicleSound*>(mParts[mSoundPart])->Play ( ); } // Bind the driver to a joint or to the vehicles origin? if( fl.bindDriver ) { if ( INVALID_JOINT != mDriverJoint ) { mDriver->GetPhysics()->SetAxis ( mParent->GetAxis( ) );// Not sure if this is needed mDriver->BindToJoint ( mParent, mDriverJoint, true ); mDriver->GetPhysics()->SetOrigin ( vec3_origin ); } else { mDriver->Bind ( mParent, true ); mDriver->GetPhysics()->SetOrigin( mDriverOffset ); } } else {// If not bound put the vehicle first in the active list mParent->activeNode.Remove(); mParent->activeNode.AddToFront( gameLocal.activeEntities ); } // Play a certain animation on the driver if ( mDriverAnim.Length() ) { mDriver->GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, mDriver->GetAnimator()->GetAnim( mDriverAnim ), gameLocal.time, 0 ); } } else { if ( !fl.driverVisible ) { mDriver->Show ( ); // Take damage again mDriver->fl.takedamage = true; } // Driver is no longer bound to the vehicle mDriver->Unbind(); mDriver = driver; if ( mSoundPart != -1 ) { static_cast<rvVehicleSound*>(mParts[mSoundPart])->Stop ( ); } // Clear out the input commands so the guns dont keep firing and what not when // the player gets out memset ( &mInputCmd, 0, sizeof(mInputCmd) ); mInputAngles.Zero ( ); } return true; } /* ================ rvVehiclePosition::GetAxis ================ */ idMat3 rvVehiclePosition::GetAxis() const { return mAxisOffset * GetParent()->GetPhysics()->GetAxis(); } /* ================ rvVehiclePosition::GetOrigin ================ */ idVec3 rvVehiclePosition::GetOrigin( const idVec3& offset ) const { return GetParent()->GetPhysics()->GetOrigin() + (mDriverOffset + offset) * GetAxis(); } /* ================ rvVehiclePosition::ActivateParts ================ */ void rvVehiclePosition::ActivateParts ( bool active ) { int i; // Activate or deactive the parts based on whether there is a driver for ( i = mParts.Num() - 1; i >= 0; i -- ) { mParts[i]->Activate ( active ); } for ( i = mWeapons.Num() - 1; i >= 0; i -- ) { mWeapons[i]->Activate ( active ); } } /* ================ rvVehiclePosition::EjectDriver ================ */ bool rvVehiclePosition::EjectDriver ( bool force ) { if ( !IsOccupied ( ) ) { return false; } // Physically eject the actor from the position if ( !force && mParent->IsLocked ( ) ) { mParent->IssueLockedWarning ( ); return false; } // Remove the driver and if successful disable all parts for // this position if ( SetDriver ( NULL ) ) { ActivateParts ( false ); return true; } return false; } /* ================ rvVehiclePosition::SetInput ================ */ void rvVehiclePosition::SetInput ( const usercmd_t& cmd, const idAngles& newAngles ) { if ( gameDebug.IsHudActive ( DBGHUD_VEHICLE ) ) { if ( mDriver == gameLocal.GetLocalPlayer ( ) ) { gameDebug.SetFocusEntity ( mParent ); } } if ( fl.inputValid || !mDriver ) { mOldInputCmd = mInputCmd; mOldInputAngles = mInputAngles; } else { mOldInputCmd = cmd; mInputCmd = cmd; mInputAngles = newAngles; // We have valid input now and there is a driver so activate all of the parts if ( !fl.inputValid && mDriver ) { ActivateParts ( true ); } } fl.inputValid = true; mInputCmd = cmd; mInputAngles = newAngles; } /* ================ rvVehiclePosition::GetInput ================ */ void rvVehiclePosition::GetInput( usercmd_t& cmd, idAngles& newAngles ) const { cmd = mInputCmd; newAngles = mInputAngles; } /* ================ rvVehiclePosition::UpdateHUD ================ */ void rvVehiclePosition::UpdateHUD ( idUserInterface* gui ) { // HACK: twhitaker: this is ugly but since the GEV and the Walker now have a unified HUD, it is a necessary evil int guiWeaponID; if ( !stricmp( mParent->spawnArgs.GetString( "classname" ), "vehicle_walker" ) ) { guiWeaponID = mCurrentWeapon + 2; } else { guiWeaponID = mCurrentWeapon; } gui->SetStateInt ( "vehicle_weapon", guiWeaponID ); // HACK: twhitaker end gui->SetStateInt ( "vehicle_weaponcount", mWeapons.Num() ); if ( mCurrentWeapon >= 0 && mCurrentWeapon < mWeapons.Num() ) { rvVehicleWeapon* weapon; weapon = static_cast<rvVehicleWeapon*>(mWeapons[mCurrentWeapon]); gui->SetStateFloat ( "vehicle_weaponcharge", weapon->GetCurrentCharge() ); gui->SetStateInt ( "vehicle_weaponammo", weapon->GetCurrentAmmo() ); } // Calculate the rotation of the view in relation to the vehicle itself gui->SetStateFloat ( "vehicle_rotate", -idMath::AngleDelta ( mEyeAxis.ToAngles()[YAW], mParent->GetAxis ( ).ToAngles()[YAW] ) ); if( GetParent() ) { GetParent()->UpdateHUD( GetDriver(), gui ); } } /* ================ rvVehiclePosition::UpdateCursorGUI ================ */ void rvVehiclePosition::UpdateCursorGUI ( idUserInterface* gui ) { if ( mCurrentWeapon < 0 || mCurrentWeapon >= mWeapons.Num() ) { return; } rvVehicleWeapon* weapon; weapon = static_cast<rvVehicleWeapon*>(mWeapons[mCurrentWeapon]); assert ( weapon ); weapon->UpdateCursorGUI ( gui ); } /* ================ rvVehiclePosition::UpdateInternalView ================ */ void rvVehiclePosition::UpdateInternalView ( bool force ) { bool internal = false; // If the local player is driving and not in third person then use internal internal = ( mDriver == gameLocal.GetLocalPlayer() && !pm_thirdPerson.GetInteger() ); // force the update? if ( !force && internal == fl.internalView ) { return; } fl.internalView = internal; if ( fl.depthHack ) { mParent->GetRenderEntity()->weaponDepthHackInViewID = (IsOccupied() && fl.internalView) ? GetDriver()->entityNumber + 1 : 0; } // Show and hide the internal surface if ( mInternalSurface.Length() ) { mParent->ProcessEvent ( fl.internalView ? &EV_ShowSurface : &EV_HideSurface, mInternalSurface.c_str() ); } } /* ================ rvVehiclePosition::RunPrePhysics ================ */ void rvVehiclePosition::RunPrePhysics ( void ) { int i; UpdateInternalView ( ); if ( mParent->IsStalled() ) { if ( !fl.stalled ) { // we just stalled fl.stalled = true; ActivateParts( false ); } return; } else if ( IsOccupied() && !mParent->IsStalled() && fl.stalled ) { // we just restarted fl.stalled = false; ActivateParts( true ); } // Give the parts a chance to set up for physics for ( i = mParts.Num() - 1; i >= 0; i -- ) { assert ( mParts[i] ); mParts[i]->RunPrePhysics ( ); } if ( mCurrentWeapon >= 0 ) { mWeapons[mCurrentWeapon]->RunPrePhysics ( ); } // Run physics for each part for ( i = mParts.Num() - 1; i >= 0; i -- ) { assert ( mParts[i] ); mParts[i]->RunPhysics ( ); } // Attenuate the attached sound if speed based if ( mSoundPart != -1 && mSoundMaxSpeed > 0.0f ) { float f; float speed; idVec3 vel; // Only interested in forward or backward velocity vel = mParent->GetPhysics()->GetLinearVelocity ( ) * mParent->GetPhysics()->GetAxis ( ); speed = idMath::ClampFloat ( 0.0f, mSoundMaxSpeed, vel.Normalize ( ) ); f = speed / mSoundMaxSpeed; static_cast<rvVehicleSound*>(mParts[mSoundPart])->Attenuate ( f, f ); } if ( mCurrentWeapon >= 0 ) { mWeapons[mCurrentWeapon]->RunPhysics ( ); } } /* ================ rvVehiclePosition::RunPostPhysics ================ */ void rvVehiclePosition::RunPostPhysics ( void ) { int i; for ( i = 0; i < mParts.Num(); i ++ ) { assert ( mParts[i] ); mParts[i]->RunPostPhysics ( ); } if ( mCurrentWeapon >= 0 ) { mWeapons[mCurrentWeapon]->RunPostPhysics ( ); } if ( !IsOccupied ( ) ) { return; } if ( fl.inputValid ) { if ( mInputCmd.upmove > 0 && !mParent->IsLocked() ) { // inform the driver that its time to get out of the vehicle. if( !mDriver->EventIsPosted(&AI_ExitVehicle) ) { mDriver->PostEventMS( &AI_ExitVehicle, 250, false );// To remove jump when exiting } // If the position isnt occupied anymore then the vehicle exit was successful and there // is nothing else to do if ( !IsOccupied ( ) ) { return; } } else if ( (mInputCmd.flags & UCF_IMPULSE_SEQUENCE) != (mOldInputFlags & UCF_IMPULSE_SEQUENCE) ) { int i; if ( mInputCmd.impulse >= IMPULSE_0 && mInputCmd.impulse <= IMPULSE_12 ) { SelectWeapon( mInputCmd.impulse - IMPULSE_0 ); } if ( mWeapons.Num () ) { switch ( mInputCmd.impulse ) { case IMPULSE_14: SelectWeapon ( (mCurrentWeapon + mWeapons.Num() + 1) % mWeapons.Num() ); break; case IMPULSE_15: SelectWeapon ( (mCurrentWeapon + mWeapons.Num() - 1) % mWeapons.Num() ); break; } } for( i = 0; i < mParts.Num(); i++ ) { mParts[ i ]->Impulse ( mInputCmd.impulse ); } mOldInputFlags = mInputCmd.flags; } } // Update the eye origin and axis GetEyePosition( mEyeOrigin, mEyeAxis ); if ( g_debugVehicle.GetInteger() == 2 ) { gameRenderWorld->DebugArrow( colorMagenta, mEyeOrigin, mEyeOrigin + mEyeAxis[0] * 30.0f, 3 ); } } /* ================ rvVehiclePosition::GetEyePosition ================ */ void rvVehiclePosition::GetEyePosition( idVec3& origin, idMat3& axis ) const { GetPosition( mEyeJoint, mEyeOffset, mEyeJointTransform, mDeltaEyeAxisScale, mEyeJointAxisMap, mEyeJointDirMap, origin, axis ); axis *= GetParent()->GetAxis(); } /* ================ rvVehiclePosition::GetDriverPosition ================ */ void rvVehiclePosition::GetDriverPosition( idVec3& origin, idMat3& axis ) const { if( fl.bindDriver ) { GetPosition( mDriverJoint, mDriverOffset, mDriverJointTransform, mDeltaDriverAxisScale, mDriverJointAxisMap, mDriverJointDirMap, origin, axis ); } else { origin = GetDriver()->GetPhysics()->GetOrigin(); axis = GetDriver()->viewAxis; } } /* ================ rvVehiclePosition::GetPosition ================ */ void rvVehiclePosition::GetPosition( const jointHandle_t jointHandle, const idVec3& offset, const idMat3& jointTransform, const idAngles& scale, const int axisMap[], const int dirMap[], idVec3& origin, idMat3& axis ) const { if( GetParent()->GetAnimator()->GetJointTransform(jointHandle, gameLocal.GetTime(), origin, axis) ) { axis *= jointTransform; idAngles ang( axis.ToAngles().Remap(axisMap, dirMap).Scale(scale) ); axis = ang.Normalize360().ToMat3() * mAxisOffset; origin = GetParent()->GetOrigin() + (origin + offset * axis) * GetParent()->GetAxis(); } else { origin = GetOrigin( mEyeOffset ); axis = GetAxis(); } } /* ================ rvVehiclePosition::FireWeapon ================ */ void rvVehiclePosition::FireWeapon( void ) { if ( mCurrentWeapon >= 0 ) { static_cast<rvVehicleWeapon*>( mWeapons[mCurrentWeapon] )->Fire(); } } /* ================ rvVehiclePosition::SelectWeapon ================ */ void rvVehiclePosition::SelectWeapon ( int weapon ) { if ( weapon < 0 || weapon >= mWeapons.Num ( ) ) { return; } // mekberg: clear effect if ( mCurrentWeapon != -1 ) { static_cast<rvVehicleWeapon*> ( mWeapons[ mCurrentWeapon ] )->StopTargetEffect( ); } mCurrentWeapon = weapon; } /* ================ rvVehiclePosition::WriteToSnapshot ================ */ void rvVehiclePosition::WriteToSnapshot ( idBitMsgDelta &msg ) const { msg.WriteBits ( mCurrentWeapon, 3 ); } /* ================ rvVehiclePosition::ReadFromSnapshot ================ */ void rvVehiclePosition::ReadFromSnapshot ( const idBitMsgDelta &msg ) { mCurrentWeapon = msg.ReadBits ( 3 ); } /* ================ rvVehiclePosition::Save ================ */ void rvVehiclePosition::Save ( idSaveGame* savefile ) const { int i; savefile->WriteUsercmd( mInputCmd ); savefile->WriteAngles ( mInputAngles ); savefile->WriteUsercmd ( mOldInputCmd ); savefile->WriteAngles ( mOldInputAngles ); savefile->WriteInt ( mOldInputFlags ); savefile->WriteInt ( mCurrentWeapon ); mDriver.Save ( savefile ); mParent.Save ( savefile ); savefile->WriteInt ( mParts.Num ( ) ); for ( i = 0; i < mParts.Num(); i ++ ) { savefile->WriteString ( mParts[i]->GetClassname() ); savefile->WriteStaticObject ( *mParts[i] ); } savefile->WriteInt ( mWeapons.Num ( ) ); for ( i = 0; i < mWeapons.Num(); i ++ ) { savefile->WriteString ( mWeapons[i]->GetClassname() ); savefile->WriteStaticObject ( *mWeapons[i] ); } savefile->WriteVec3 ( mEyeOrigin ); savefile->WriteMat3 ( mEyeAxis ); savefile->WriteJoint ( mEyeJoint ); savefile->WriteVec3 ( mEyeOffset ); savefile->WriteMat3( mEyeJointTransform ); savefile->WriteAngles( mDeltaEyeAxisScale ); savefile->Write ( mEyeJointAxisMap, sizeof mEyeJointAxisMap ); savefile->Write ( mEyeJointDirMap, sizeof mEyeJointDirMap ); savefile->WriteMat3 ( mAxisOffset ); savefile->WriteJoint ( mDriverJoint ); savefile->WriteVec3 ( mDriverOffset ); savefile->WriteMat3 ( mDriverJointTransform ); savefile->WriteAngles( mDeltaDriverAxisScale ); savefile->Write ( mDriverJointAxisMap, sizeof mDriverJointAxisMap ); savefile->Write ( mDriverJointDirMap, sizeof mDriverJointDirMap ); savefile->WriteVec3 ( mExitPosOffset ); savefile->WriteMat3 ( mExitAxisOffset ); savefile->WriteString ( mDriverAnim ); savefile->WriteString ( mInternalSurface ); savefile->Write ( &fl, sizeof ( fl ) ); savefile->WriteInt ( mSoundPart ); savefile->WriteFloat ( mSoundMaxSpeed ); } /* ================ rvVehiclePosition::Restore ================ */ void rvVehiclePosition::Restore ( idRestoreGame* savefile ) { int i; int num; savefile->ReadUsercmd( mInputCmd ); savefile->ReadAngles ( mInputAngles ); savefile->ReadUsercmd ( mOldInputCmd ); savefile->ReadAngles ( mOldInputAngles ); savefile->ReadInt ( mOldInputFlags ); savefile->ReadInt ( mCurrentWeapon ); mDriver.Restore ( savefile ); mParent.Restore ( savefile ); savefile->ReadInt ( num ); mParts.Clear ( ); mParts.SetNum ( num ); for ( i = 0; i < num; i ++ ) { idStr spawnclass; rvVehiclePart* part; idTypeInfo* typeInfo; savefile->ReadString ( spawnclass ); // Determine the part type typeInfo = idClass::GetClass ( spawnclass ); if ( !typeInfo || !typeInfo->IsType ( rvVehiclePart::GetClassType() ) ) { gameLocal.Error ( "Class '%s' is not a vehicle part", spawnclass.c_str() ); } part = static_cast<rvVehiclePart*>(typeInfo->CreateInstance ( )); savefile->ReadStaticObject ( *part ); mParts[i] = part; } savefile->ReadInt ( num ); mWeapons.Clear ( ); mWeapons.SetNum ( num ); for ( i = 0; i < num; i ++ ) { idStr spawnclass; rvVehiclePart* part; idTypeInfo* typeInfo; savefile->ReadString ( spawnclass ); // Determine the part type typeInfo = idClass::GetClass ( spawnclass ); if ( !typeInfo || !typeInfo->IsType ( rvVehiclePart::GetClassType() ) ) { gameLocal.Error ( "Class '%s' is not a vehicle part", spawnclass.c_str() ); } part = static_cast<rvVehiclePart*>(typeInfo->CreateInstance ( )); savefile->ReadStaticObject ( *part ); mWeapons[i] = part; } savefile->ReadVec3 ( mEyeOrigin ); savefile->ReadMat3 ( mEyeAxis ); savefile->ReadJoint ( mEyeJoint ); savefile->ReadVec3 ( mEyeOffset ); savefile->ReadMat3 ( mEyeJointTransform ); savefile->ReadAngles( mDeltaEyeAxisScale ); savefile->Read( mEyeJointAxisMap, sizeof mEyeJointAxisMap ); savefile->Read( mEyeJointDirMap, sizeof mEyeJointDirMap ); savefile->ReadMat3 ( mAxisOffset ); savefile->ReadJoint ( mDriverJoint ); savefile->ReadVec3 ( mDriverOffset ); savefile->ReadMat3 ( mDriverJointTransform ); savefile->ReadAngles( mDeltaDriverAxisScale ); savefile->Read( mDriverJointAxisMap, sizeof mDriverJointAxisMap ); savefile->Read( mDriverJointDirMap, sizeof mDriverJointDirMap ); savefile->ReadVec3 ( mExitPosOffset ); savefile->ReadMat3 ( mExitAxisOffset ); savefile->ReadString ( mDriverAnim ); savefile->ReadString ( mInternalSurface ); savefile->Read ( &fl, sizeof(fl) ); savefile->ReadInt ( mSoundPart ); savefile->ReadFloat ( mSoundMaxSpeed ); }
/* Copyright 2020 The TensorFlow Authors 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 "tensorflow/core/profiler/rpc/client/remote_profiler_session_manager.h" #include <memory> #include <string> #include <vector> #include "absl/time/clock.h" #include "absl/time/time.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/profiler_options.pb.h" #include "tensorflow/core/profiler/profiler_service.pb.h" #include "tensorflow/core/profiler/rpc/client/profiler_client_test_util.h" namespace tensorflow { namespace profiler { namespace { using ::tensorflow::profiler::test::DurationApproxLess; using ::tensorflow::profiler::test::DurationNear; using ::tensorflow::profiler::test::StartServer; using Response = tensorflow::profiler::RemoteProfilerSessionManager::Response; TEST(RemoteProfilerSessionManagerTest, Simple) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options = RemoteProfilerSessionManager::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_addresses; auto server = StartServer(duration, &service_addresses); options.add_service_addresses(service_addresses); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); Status status; auto sessions = RemoteProfilerSessionManager::Create(options, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_FALSE(responses.back().profile_response->empty_trace()); EXPECT_GT(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSessionManagerTest, ExpiredDeadline) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options = RemoteProfilerSessionManager::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_addresses; auto server = StartServer(duration, &service_addresses); options.add_service_addresses(service_addresses); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); // This will create a deadline in the past. options.set_session_creation_timestamp_ns(0); absl::Time approx_start = absl::Now(); Status status; auto sessions = RemoteProfilerSessionManager::Create(options, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationNear(absl::Seconds(0))); ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(errors::IsDeadlineExceeded(responses.back().status)); EXPECT_FALSE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); } TEST(RemoteProfilerSessionManagerTest, LongSession) { absl::Duration duration = absl::Seconds(3); RemoteProfilerSessionManagerOptions options = RemoteProfilerSessionManager::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_addresses; auto server = StartServer(duration, &service_addresses); options.add_service_addresses(service_addresses); absl::Time approx_start = absl::Now(); // Empirically determined value. absl::Duration grace = absl::Seconds(20); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); Status status; auto sessions = RemoteProfilerSessionManager::Create(options, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_FALSE(responses.back().profile_response->empty_trace()); EXPECT_GT(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } // namespace } // namespace profiler } // namespace tensorflow
/* * SDEV 340 Week 12 Problem 2 * Extension of pc1 SimpleLinkedList class that provdes a method returning the index of a found item, instead of just a boolean * Benjamin Lovy */ // To avoid redefining "main", instead of including SimpleLinkedList // I just copied the relevant parts of pc1's code into this file, and changed the head pointer to public instead of private // Ideally, I'd have provided SimpleLinkedList.h separately but that starts needing a makefile #include <iostream> #include <string> template <class T> struct ListNode { T val; ListNode *next; ListNode(T value, ListNode *nextptr = nullptr) { val = value; next = nextptr; } }; // // Class declaration // template <class T> class SimpleLinkedList { protected: ListNode<T> *head; public: SimpleLinkedList(); ~SimpleLinkedList(); void add(T x); }; // Class methods template <class T> SimpleLinkedList<T>::SimpleLinkedList() { head = nullptr; } template <class T> SimpleLinkedList<T>::~SimpleLinkedList() { ListNode<T> *currentNodePtr = head; while (currentNodePtr) { ListNode<T> *toDelete = currentNodePtr; currentNodePtr = currentNodePtr->next; delete toDelete; } } template <class T> void SimpleLinkedList<T>::add(T x) { head = new ListNode<T>(x, head); } // // Searchable derived class implementation // template <class T> class SearchableLinkedList : public SimpleLinkedList<T> { public: // Inherits base class constructor SearchableLinkedList() : SimpleLinkedList<T>() {} // Run search int search(T x) const; // Display search result void showSearch(T x) const; }; template <class T> int SearchableLinkedList<T>::search(T x) const { ListNode<T> *currentNodePtr = this->head; int ret = -1; int idx = 0; while (currentNodePtr) { if (currentNodePtr->val == x) { ret = idx; break; } currentNodePtr = currentNodePtr->next; idx++; } return ret; } template <class T> void SearchableLinkedList<T>::showSearch(T x) const { std::cout << "Index of " << x << ": " << search(x) << "\n"; } int main() { using std::cout; // Init SearchableLinkedList<double> sll; // Add numbers 1 through 5 std::cout << "Adding numbers 1 though 10 (creating [10,9,8,7,6,5,4,3,2,1])...\n"; for (int i = 1; i <= 10; i++) sll.add(i); // Search for 7 sll.showSearch(7); // Search for 16 sll.showSearch(16); // Exit success return 0; }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFileDialog> #include <QImage> #include "morphology.h" #include <QtDebug> #include "imageutil.h" #include <QResizeEvent> #include <QTransform> #include "anl.h" #include "templates/tarrays.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_pScene = new QGraphicsScene(this); ui->graphicsView->setScene(m_pScene); m_pBitmap = NULL; } MainWindow::~MainWindow() { delete ui; delete m_pBitmap; m_pBitmap = NULL; } void MainWindow::loadImage() { QString filename = QFileDialog::getOpenFileName(this, "Choose an image to open", qApp->applicationDirPath(), "Image file (*bmp; *.png)"); if ( filename.isEmpty() ) return; delete m_pBitmap; m_pBitmap = new QBitmap(filename); m_pScene->addPixmap(*m_pBitmap); zoomGraphicsToFit(); } void MainWindow::dilateImage() { modifyImage(true); } void MainWindow::erodeImage() { modifyImage(false); } void MainWindow::modifyImage(bool dilate) { if ( !m_pBitmap ) return; QImage image = m_pBitmap->toImage().convertToFormat(QImage::Format_ARGB32); QImage kernel(3, 3, QImage::Format_RGB32); QRgb col0 = QColor(Qt::color0).rgb(); QRgb col1 = QColor(Qt::color1).rgb(); for ( int x = 0; x < 3; x++ ) { for ( int y = 0; y < 3; y++ ) { if ( x == 1 ) { kernel.setPixel(x, y, col1); } else { if ( y == 1 ) { kernel.setPixel(x, y, col1); } else { kernel.setPixel(x, y, col0); } } } } if ( dilate ) Morphology::dilate(image, kernel, QPoint(1,1)); else Morphology::erode(image, kernel, QPoint(1,1)); delete m_pBitmap; m_pBitmap = new QBitmap(QBitmap::fromImage(image)); m_pScene->clear(); m_pScene->addPixmap(*m_pBitmap); zoomGraphicsToFit(); } void MainWindow::applyAlphaThreshold() { if ( !m_pBitmap ) return; QImage image = m_pBitmap->toImage().convertToFormat(QImage::Format_ARGB32); Morphology::thresholdAlpha(image, (unsigned char)ui->alphaThreshold->value()); delete m_pBitmap; m_pBitmap = new QBitmap(QBitmap::fromImage(image)); m_pScene->clear(); m_pScene->addPixmap(*m_pBitmap); zoomGraphicsToFit(); } void MainWindow::applyBrightnessThreshold() { QString filename = QFileDialog::getOpenFileName(this, "Choose an image to open", qApp->applicationDirPath(), "Image file (*bmp; *.png)"); if ( filename.isEmpty() ) return; QImage image = QImage(filename).convertToFormat(QImage::Format_ARGB32); Morphology::thresholdBrightness(image, (unsigned char)ui->brightnessThreshold->value()); m_pScene->clear(); m_pScene->addPixmap(QPixmap::fromImage(image)); zoomGraphicsToFit(); } void MainWindow::zoomGraphicsToFit() { // Get the longest side of the rectangle. QRectF r = m_pScene->itemsBoundingRect(); float longest = 0; bool width = false; if ( r.width() > r.height() ) { longest = r.width(); width = true; } else { longest = r.height(); width = false; } if ( longest == 0.0f ) return; // Scale so that the value of longest becomes the same as the length of the shortest side of the view. float scaleFactor = 1; if ( ui->graphicsView->width() < ui->graphicsView->height() ) { scaleFactor = (float)ui->graphicsView->width() / longest; } else { scaleFactor = (float)ui->graphicsView->height() / longest; } ui->graphicsView->setSceneRect(m_pScene->itemsBoundingRect()); ui->graphicsView->setTransform(QTransform(scaleFactor, 0, 0, 0, scaleFactor, 0, 0, 0, 1)); } void MainWindow::resizeEvent(QResizeEvent *e) { Q_UNUSED(e); zoomGraphicsToFit(); } void MainWindow::accidentalNoiseSample() { anl::CMWC4096 rnd; rnd.setSeedTime(); anl::CImplicitFractal frac1(anl::FBM, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac2(anl::FBM, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac3(anl::FBM, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac4(anl::RIDGEDMULTI, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac5(anl::FBM, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac6(anl::FBM, anl::GRADIENT, anl::QUINTIC); anl::CImplicitFractal frac7(anl::FBM, anl::GRADIENT, anl::QUINTIC); frac1.setSeed(rnd.get()); frac2.setSeed(rnd.get()); frac3.setSeed(rnd.get()); frac4.setSeed(rnd.get()); frac5.setSeed(rnd.get()); frac6.setSeed(rnd.get()); frac7.setSeed(rnd.get()); anl::CImplicitAutoCorrect ac1(0.0, 1.0), ac2(0.0,1.0), ac3(0,1.0), ac4(0.0, 360.0), ac5(-1.0,1.0), ac6(-1.0,1.0), ac7(-1.0,1.0); ac1.setSource(&frac1); ac2.setSource(&frac2); ac3.setSource(&frac3); ac4.setSource(&frac4); ac5.setSource(&frac5); ac6.setSource(&frac6); ac7.setSource(&frac7); anl::CRGBACompositeChannels compose1(anl::RGB); compose1.setRedSource(&ac1); compose1.setGreenSource(&ac2); compose1.setBlueSource(&ac3); compose1.setAlphaSource(1.0); anl::CRGBARotateColor rot; rot.setAngle(&ac4); rot.setAxisX(&ac5); rot.setAxisY(&ac6); rot.setAxisZ(&ac7); rot.setNormalizeAxis(true); rot.setSource(&compose1); anl::TArray2D<anl::SRGBA> img(256,256); anl::SMappingRanges ranges; anl::mapRGBA2D(anl::SEAMLESS_NONE,img,rot,ranges,0); // QString a = qApp->applicationDirPath() + QString("/a.tga"); // saveRGBAArray(a.toLatin1().data(),&img); anl::mapRGBA2D(anl::SEAMLESS_NONE,img,compose1,ranges,0); m_pScene->clear(); m_pScene->addPixmap(QPixmap::fromImage(ImageUtil::arrayToImage(img))); zoomGraphicsToFit(); // QString b = qApp->applicationDirPath() + QString("/b.tga"); // saveRGBAArray(b.toLatin1().data(),&img); } void MainWindow::runAccidentalNoiseSample() { // Create a random number generator and seed it with the current system time. anl::CMWC4096 rnd; rnd.setSeedTime(); // Create a fractal generator. // FBM is a default cloud-like fractal. // Gradient is the original Perlin function for generating the noise. // Quintic is the interpolation used. anl::CImplicitFractal frac1(anl::FBM, anl::GRADIENT, anl::QUINTIC); // Seed the fractal with a value from the random number generator. frac1.setSeed(rnd.get()); // Create an auto-corrector. This samples the outputs of the fractal // and attempts to formulate a set of parameters in order to map the fractal // output into a usable range (in this case, [0 1]). anl::CImplicitAutoCorrect ac1(0.0, 1.0); // Set the auto-corrector source to the fractal. // Note that this function incurs some non-trivial processing time // because of the output sampling. ac1.setSource(&frac1); // Create an RGBA channel. This allows different fractals // to generate output for different channels. // Here we just set all channels to come from the one fractal // in order to generate a greyscale image. // The source specified is the auto-corrector. anl::CRGBACompositeChannels compose1(anl::RGB); compose1.setRedSource(&ac1); compose1.setGreenSource(&ac1); compose1.setBlueSource(&ac1); compose1.setAlphaSource(1.0); // Create a 2D array to hold the fractal texture. anl::TArray2D<anl::SRGBA> img(256,256); // Not sure what this is for. anl::SMappingRanges ranges; // Map the output of the fractal (through the RGBA channel) into the vector as a texture. anl::mapRGBA2D(anl::SEAMLESS_X, img, compose1, ranges, 0); // Display the texture. QImage i = ImageUtil::arrayToImage(img); Morphology::thresholdBrightness(i, ui->brightnessThreshold->value()); m_pScene->clear(); m_pScene->addPixmap(QPixmap::fromImage(i)); delete m_pBitmap; m_pBitmap = new QBitmap(QBitmap::fromImage(i)); zoomGraphicsToFit(); }
#include <vector> #include <cmath> #include <sstream> #include <string> #include <iostream> #include <boost/math/special_functions/bessel.hpp> #include <boost/math/special_functions/bessel_prime.hpp> #include <fstream> #include "rd.hpp" #include "interp.hpp" #include "models.hpp" #include "RK4.hpp" using namespace std; template<typename Model> double Relic_density<Model>::Yeq(double x) { double h_eff=100; return boost::math::cyl_bessel_k(2,x)*(45/(4*pow(data.Pi,4)))*pow(x,2)/(h_eff); } template<typename Model> double Relic_density<Model>::dYeq(double x) { double h_eff=100; return boost::math::cyl_bessel_k_prime(2,x)*(45/(4*pow(data.Pi,4)))*pow(x,2)/(h_eff) + (float(2)/x)*Yeq(x); } template<typename Model> double Relic_density<Model>::hat(double func, double x) { return exp(x)*func; } template<typename Model> double Relic_density<Model>::x_f() { // calculate x value of free-out double deltaf=0.618; double x_star=15,x_prev=0; Z_func<Model> func(data); //for (int i=0;i<10;i++) while (abs(x_star-x_prev)>0.001) { x_star=log( (deltaf*(2+deltaf)/(1+deltaf)) * ( func(x_star)* pow(hat(Yeq(x_star),x_star),2) )/ (hat(Yeq(x_star),x_star) -hat(Yeq(x_star)+dYeq(x_star),x_star) )); x_prev=x_star; } //cout<< "x* is = " << x_star << endl; return x_star; } template<typename Model> double Relic_density<Model>::Y_today(double x_f) { double Y_f=(1+0.618)*Yeq(x_f), result=0; if (method==1) { result=Y_f/(1+Y_f*A(x_f)); } else { result = solve_boltzman_Y_today(x_f); } return result; } template<typename Model> double Relic_density<Model>::A(double x_f) { double x_upper=1e5, x_lower=x_f; double T_lower=data.M_dm/x_upper,T_upper=data.M_dm/x_lower; thermal_average_make_interp(T_lower*0.9,T_upper*1.1,5); Z_func<Model> func(data,T_m,thermal_av_m); double I=qtrap(func, x_lower,x_upper,1e-3); return I; //Z_func func(M_dm); // //return x_f*func(x_f); } template<typename Model> double Relic_density<Model>::calc_cross_section(double T) { if (fast_mode) { return calc_cross_section_fast(T); } else { return calc_cross_section_slow(T); } } template<typename Model> double Relic_density<Model>::calc_cross_section_fast(double T) { Model model; return model.quick_cs(T); } template<typename Model> double Relic_density<Model>::calc_cross_section_slow(double T) { if (make_interp==1) { Poly_interp myfunc(T_m,thermal_av_m,5); return myfunc.interp(T); } else { // find ul such that f(ul)=1e-30 double s=4*pow(data.M_dm,2)+1; cs_func<Model> f(T,data); double a=s*10.0; double delta=1; double fa; try{ f(s); } catch (const char* msg) { cout << "catch 1" << endl; throw "invalid_pt"; return 0; } fa=f(a); double val=1e-30; double fdelta=f(a+delta); double diff=fa-fdelta; double b,bb=-1; if (diff<0) { cout << " gradient is positive " << endl; while (diff<0) { a=a*10; fa=f(a); fdelta=f(a+delta); diff=fa-fdelta; } } if (fa>val) { // cout << " fa is too large, descending downhill " << endl; if (f(a+delta)<val) { // desired point is between a and delta, so set b = a + delta bb=a+delta; } else { // cout << "looking for f < val "<< endl; // need to go beyond a+delta to find point // here we will find a value such that f < val double b=delta+a,fb=f(a+delta); while (fb>val) // find a and b around root { a=b; b=b*10; bb=b; // cout << "attempt = " << b << " f = " << f(b) << endl; fb=f(b); } } } else { // cout << " fa is too small, going uphill" << endl; if (f(a-delta)>val) { // desired point is between a and delta, so set b = a + delta bb=a+delta; } else { // need to go below a-delta to find point // but we our bounded below by s so just use this bb=a; a=s; // now have lower (a) and upper (b) bound for x such that f(x)=val } } b=bb; // cout << "root bounded between (a,b) = " << a << " " << b << endl; // cout << "root bounded between (f(a),f(b)) = " << f(a) << " " << f(b) << endl; fa=f(a); double ft=val*1e10,m; // now root find between a and b while (abs(log10(ft)-log10(val))>5) { m=(b-a)/2+a; // cout << " mid point = " << m << endl; if (f(m)<val) { b=m; } else { a=m; } double fm=f(m); if (fm!=0) { ft=fm; } } double ul=m; // cout << "integrating from s to " << ul << " for T = " << T << endl; double result; // if (s<2*pow(data.M_h,2)) // split integral into two parts, one around the Higgs resonance and one for the tail // { // double mid_pt=s+(ul-s)/2;//2*pow(data.M_h,2); // cout << " (s, mid) = " << s << " " << mid_pt << endl; // // double int_lower=qtrap(f,s,mid_pt,1e-4); // double int_upper=qtrap(f,mid_pt,ul,1e-4); // result=int_lower+int_upper; // } // else // { // result=qtrap(f,s,ul,1e-4); // } result=qtrap(f,s,ul,1e-4); return result; } } template<typename Model> void Relic_density<Model>::thermal_average_make_interp(double T_lower, double T_upper,int pts) { std::vector<double> T(pts); std::vector<double> thermal_av(pts); double step=(T_upper-T_lower)/float(pts); T[0]=T_lower; for (int n=0;n<pts;n++) { try { thermal_av[n]=calc_cross_section(T[n]); } catch (const char* msg) { cout << "catch 2" << endl; thermal_av[n]=0; } T[n+1]=T[n]+step; } T_m=T; thermal_av_m=thermal_av; make_interp=1; } template<typename Model> double Relic_density<Model>::solve_boltzman_Y_today(double x_f) { // use RK4 method to solve Boltzman equation from intial condition at x_f // convergence is achieved for sufficiently large x such that Y is constant at Y=Y_today double x_upper=1e5, x_lower=x_f; double T_lower=data.M_dm/x_upper,T_upper=data.M_dm/x_lower; thermal_average_make_interp(T_lower*0.9,T_upper*1.1,5); Boltz_func<Model> F(data,T_m,thermal_av_m); double Yf = (1+0.618)*Yeq(x_f); // Y_f RK4<Boltz_func<Model>> rk(F,x_f,x_upper,Yf); return rk.solve_RK4(data.rk_tol); }
// https://oj.leetcode.com/problems/generate-parentheses/ class Solution { // nr_open/nr_close: # of open/close paranthesis generated void do_generate(vector<string> &ret, string &buf, int nr_open, int nr_close, int n) { if (nr_open + nr_close == 2 * n) { ret.push_back(buf); return; } if (nr_open < n) { buf.push_back('('); do_generate(ret, buf, nr_open + 1, nr_close, n); buf.pop_back(); } if (nr_open > nr_close) { buf.push_back(')'); do_generate(ret, buf, nr_open, nr_close + 1, n); buf.pop_back(); } } public: vector<string> generateParenthesis(int n) { vector<string> ret; if (n <= 0) { return ret; } string buf; do_generate(ret, buf, 0, 0, n); return ret; } };
#include <iostream> class Vector { private: int erk = 0; int* arr; int tamp = 0; int i = 0; int* newArr(int size, int& er) { int* array; if(size == 1) { array = new int [er * 2]; for(int j = 0; j < i; ++j) { array[j] = arr[j]; } for(int j = i; j < i * 2; ++j) { array[j] = tamp; } er = 2 * er; } else { array = new int [er - 1]; for(int j = 0; j < er - 1; ++j) { array[j] = arr[j]; } er = er - 1; } delete []arr; return array; } public: Vector() { erk = 10; tamp = 0; for(int j = 0; j < erk; ++j) { arr[i] = tamp; } } Vector(int n, int a) { arr = new int [n]; for(int j = 0; j < n; ++j) { arr[j] = a; } erk = n; tamp = a; } Vector(const Vector& obj) { erk = obj.erk; i = obj.i; arr = obj.arr; for(int j = 0; j < erk; ++j) { arr[j] = obj.arr[j]; } } Vector(Vector&& obj) { erk = obj.erk; i = obj.i; arr = obj.arr; obj.arr = nullptr; } ~Vector() { delete []arr; arr = nullptr; } int pushBack(int num) { if(i < erk) { arr[i] = num; } else { arr = newArr(1, erk); arr[i] = num; } ++i; } void popBack() { --i; arr[i] = tamp; arr = newArr(0, erk); } void print() { for(int j = 0; j < erk; ++j) { std :: cout << arr[j] << " "; } std :: cout << '\n'; } }; class Stack : private Vector { private: int erk = 0; int* arr; int tamp = 0; int i = 0; public: Stack() : Vector() { erk = 10; tamp = 0; for(int j = 0; j < erk; ++j) { arr[i] = tamp; } } Stack(int n, int a) : Vector(n, a) { arr = new int [n]; for(int j = 0; j < n; ++j) { arr[j] = a; } erk = n; tamp = a; } Stack(const Stack& obj) { erk = obj.erk; i = obj.i; arr = obj.arr; for(int j = 0; j < erk; ++j) { arr[j] = obj.arr[j]; } } Stack(Stack&& obj) { erk = obj.erk; i = obj.i; arr = obj.arr; obj.arr = nullptr; } ~Stack() { delete []arr; arr = nullptr; } void push(int num) { pushBack(num); } void pop() { popBack(); } void printf () { print(); } }; int main() { int size, num; std :: cin >> size >> num; Vector v(size, num); v.pushBack(5); v.pushBack(1); v.pushBack(2); v.pushBack(3); v.pushBack(4); v.pushBack(9); v.print(); v.popBack(); v.print(); Stack s = Stack(size, num); s.push(5); s.push(1); s.push(2); s.push(3); s.push(4); s.push(9); s.printf(); s.pop(); s.printf(); return 0; }
#include "processslot.h" #include <QDebug> #include <game.h> extern Game* game; ProcessSlot::ProcessSlot(QObject* parent) { Q_UNUSED(parent) setRect(0,0,100,100); setPen(QPen(Qt::PenStyle::DashLine)); process = nullptr; }
#include <bits/stdc++.h> using namespace std; class Solution { public: string minWindow(string s, string t) { int n = s.size(); int m = t.size(); int left = 0; int right = 0; int tcounter = m; int start = 0; int len = INT_MAX; unordered_map<char, int> thm; for(auto ch:t) thm[ch]++; while(right < n) { if(thm[s[right]] > 0) tcounter--; thm[s[right]]--; // increasing window right++; // window now consist of all ch of 't' and possibly more. while(tcounter == 0){ if(right-left < len) { len = min(len, right-left); start = left; } // removing ch from window thm[s[left]]++; // removed ch exists in 't'. It is > 0 as initially all ch in t were counted by occurence. if(thm[s[left]] > 0) tcounter++; // decreasing window left++; } } return len == INT_MAX ? "" : s.substr(start, len); } };
#include <math.h> #include "Globals.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleParticles.h" #include "ModuleCollision.h" #include "ModuleSceneTemple.h" #include "ModuleKatana.h" #include "ModuleEnemies.h" #include "ModuleInterface.h" #include "ModuleAudio.h" #include "SDL/include/SDL_timer.h" ModuleParticles::ModuleParticles() { for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) active[i] = nullptr; } ModuleParticles::~ModuleParticles() {} // Load assets bool ModuleParticles::Start() { LOG("Loading particles"); //graphics = App->textures->Load("assets/sprites/miko.png"); //graphics1 = App->textures->Load("assets/sprites/explosions/fish_explosions2.png"); //graphics2 = App->textures->Load("assets/sprites/sho.png"); //graphics3 = App->textures->Load("assets/enemies2.png"); graphics4 = App->textures->Load("assets/sprites/characters/katana/Katana_Spritesheet.png"); //Audio Katana_Death = App->audio->LoadFx("assets/audio/voices/Getting hit/katanagettinghit.wav"); fx_death = App->audio->LoadFx("assets/aduio/effects/Impacts/tengai-134effect6.wav"); Katana_Explosion = App->audio->LoadFx("assets/audio/effects/Explotions/playerdeath_explosion.wav"); card1.anim.PushBack({ 26, 136, 11, 13 }); card2.anim.PushBack({ 49, 136, 12, 12 }); card3.anim.PushBack({ 73, 137, 12, 11 }); card4.anim.PushBack({ 97, 137, 13, 11 }); card5.anim.PushBack({ 121, 139, 12, 7 }); card1.anim.loop = false; card1.anim.speed = 1; card1.speed = { 10,0 }; card1.life = 5 *500; card2.anim.loop = false; card2.anim.speed = 1; card2.speed = { 10,0 }; card2.life = 5 * 500; card3.anim.loop = false; card3.anim.speed = 1; card3.speed = { 10,0 }; card3.life = 5 * 500; card4.anim.loop = false; card4.anim.speed = 1; card4.speed = { 10,0 }; card4.life = 5 * 500; card5.anim.loop = false; card5.anim.speed = 1; card5.speed = { 10,0 }; card5.life = 5 * 500; BigC1.anim.PushBack({ 144,135,13 ,15 }); BigC1.anim.loop = false; BigC1.speed = { 15,0 }; BigC1.life = 5 * 500; BigC2.anim.PushBack({ 168,135,15 ,15 }); BigC2.anim.loop = false; BigC2.speed = { 15,0 }; BigC2.life = 5 * 500; BigC3.anim.PushBack({ 192,135, 15 ,14 }); BigC3.anim.loop = false; BigC3.speed = { 15,0 }; BigC3.life = 5 * 500; BigC4.anim.PushBack({ 216,136,15 ,13 }); BigC4.anim.loop = false; BigC4.speed = { 15,0 }; BigC4.life = 5 * 500; BigC5.anim.PushBack({ 240,138,14 ,8 }); BigC5.anim.loop = false; BigC5.speed = { 15,0 }; BigC5.life = 5 * 500; //Sho shots sword1.anim.PushBack({ 108, 151, 32, 4 }); sword1.anim.loop = false; sword1.speed = { 10,0 }; sword1.life = 5 * 500; sword2.anim.PushBack({ 149, 151, 32, 3 }); sword2.anim.loop = false; sword2.speed = { 10,0 }; sword2.life = 5 * 500; //Katana shoots shoot1.anim.PushBack({444, 165, 15, 8}); shoot1.anim.loop = true; shoot1.life = 1400; shoot1.speed.x = 12; shoot2.anim.PushBack({396, 164, 15, 10}); shoot2.anim.loop = true; shoot2.life = 1400; shoot2.speed.x = 12; shoot3.anim.PushBack({348, 164, 15, 10}); shoot3.anim.loop = true; shoot3.life = 1400; shoot3.speed.x = 12; //Arrow Katana shoot arrow_shoot.anim.PushBack({462, 453, 16, 3}); arrow_shoot.anim.loop = true; arrow_shoot.life = 1400; arrow_shoot.speed.x = 12; //Charged Katana shoot charged_arrow_shoot.anim.PushBack({308, 427, 35, 18}); charged_arrow_shoot.anim.loop = false; charged_arrow_shoot.life = 800; charged_arrow_shoot.speed.x = App->scene_temple->speed; //charged_arrow_shoot.speed.y = 2; //Ayin shoots (pu 0 - 4) //Power up 0 & 1 ayin_shoot1.anim.PushBack({6, 516, 21, 5}); ayin_shoot1.anim.loop = true; ayin_shoot1.life = 1400; ayin_shoot1.speed.x = 12; ayin_shoot2.anim.PushBack({31, 516, 21, 5}); ayin_shoot2.anim.loop = true; ayin_shoot2.life = 1400; ayin_shoot2.speed.x = 12; ayin_shoot3.anim.PushBack({58, 516, 21, 5}); ayin_shoot3.anim.loop = true; ayin_shoot3.life = 1400; ayin_shoot3.speed.x = 12; //Power up 2 ayin_shoot1_2.anim.PushBack({ 88, 516, 27, 7 }); ayin_shoot1_2.anim.loop = true; ayin_shoot1_2.life = 1400; ayin_shoot1_2.speed.x = 12; ayin_shoot2_2.anim.PushBack({ 121, 515, 27, 7 }); ayin_shoot2_2.anim.loop = true; ayin_shoot2_2.life = 1400; ayin_shoot2_2.speed.x = 12; ayin_shoot3_2.anim.PushBack({ 154, 515, 27, 7 }); ayin_shoot3_2.anim.loop = true; ayin_shoot3_2.life = 1400; ayin_shoot3_2.speed.x = 12; //Power up 3 & 4 ayin_shoot1_3.anim.PushBack({ 187, 514, 33, 7 }); ayin_shoot1_3.anim.loop = true; ayin_shoot1_3.life = 1400; ayin_shoot1_3.speed.x = 12; ayin_shoot2_3.anim.PushBack({ 222, 515, 33, 7 }); ayin_shoot2_3.anim.loop = true; ayin_shoot2_3.life = 1400; ayin_shoot2_3.speed.x = 12; ayin_shoot3_3.anim.PushBack({ 259, 515, 33, 7 }); ayin_shoot3_3.anim.loop = true; ayin_shoot3_3.life = 1400; ayin_shoot3_3.speed.x = 12; //Ayin wave (pu 1-4) //Power up 1 ayin_wave.anim.PushBack({11, 529, 16, 23}); ayin_wave.anim.loop = true; ayin_wave.life = 1400; ayin_wave.speed.x = 12; //Power up 2 ayin_wave_2.anim.PushBack({ 315, 505, 17, 32 }); ayin_wave_2.anim.loop = true; ayin_wave_2.life = 1400; ayin_wave_2.speed.x = 12; //Power up 3 ayin_wave_3.anim.PushBack({ 337, 499, 17, 40 }); ayin_wave_3.anim.loop = true; ayin_wave_3.life = 1400; ayin_wave_3.speed.x = 12; //Power up 4 ayin_wave_4.anim.PushBack({ 363, 496, 27, 48 }); ayin_wave_4.anim.loop = true; ayin_wave_4.life = 1400; ayin_wave_4.speed.x = 12; //Ayin charged shot wave (w1) wave1.anim.PushBack({14, 568, 139, 24}); wave1.anim.loop = true; wave1.life = 150; wave1.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w2) wave2.anim.PushBack({ 174, 572, 147, 15 }); wave2.anim.loop = true; wave2.life = 150; wave2.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w3) wave3.anim.PushBack({ 332, 560, 127, 26 }); wave3.anim.loop = true; wave3.life = 150; wave3.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w4) wave4.anim.PushBack({ 11, 603, 112, 26 }); wave4.anim.loop = true; wave4.life = 150; wave4.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w5) wave5.anim.PushBack({ 139, 602, 104, 27 }); wave5.anim.loop = true; wave5.life = 150; wave5.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w6) wave6.anim.PushBack({ 269, 605, 98, 17 }); wave6.anim.loop = true; wave6.life = 150; wave6.speed.x = App->scene_temple->speed; //Ayin charged shot wave (w7) wave7.anim.PushBack({ 376, 608, 88, 12 }); wave7.anim.loop = true; wave7.life = 30; wave7.speed.x = App->scene_temple->speed; //Ayin ultimate ulti_ayin.anim.PushBack({17, 737, 33, 41 }); ulti_ayin.anim.PushBack({ 52, 727, 47, 59 }); ulti_ayin.anim.PushBack({ 110, 718, 57, 67 }); ulti_ayin.anim.PushBack({ 15, 644, 117, 66 }); ulti_ayin.anim.loop = false; ulti_ayin.life = 1400; ulti_ayin.anim.speed = 0.15f; ulti_ayin.speed.x = App->scene_temple->speed + 1.5; //Enemy explosions on Water Stage /* waterExplosion.anim.PushBack({15, 9, 47, 44}); waterExplosion.anim.PushBack({70, 5, 48, 45}); waterExplosion.anim.PushBack({127, 4, 55, 62}); waterExplosion.anim.PushBack({193, 6, 50, 58}); waterExplosion.anim.PushBack({10, 71, 55, 60}); waterExplosion.anim.PushBack({75, 72, 53, 63}); waterExplosion.anim.PushBack({131, 76, 54, 65}); waterExplosion.anim.PushBack({191, 78, 56, 63}); waterExplosion.anim.PushBack({9, 155, 58, 65}); waterExplosion.anim.PushBack({80, 158, 55, 60}); waterExplosion.anim.PushBack({155, 160, 53, 59}); waterExplosion.anim.loop = false; waterExplosion.anim.speed = 0.5; waterExplosion.life = 200; waterExplosion.speed = {0,0}; */ waterExplosion.anim.PushBack({ 26, 522, 47, 44 }); waterExplosion.anim.PushBack({ 81, 518, 48, 54 }); waterExplosion.anim.PushBack({ 138, 518, 55, 61 }); waterExplosion.anim.PushBack({ 203, 520, 51, 57 }); waterExplosion.anim.PushBack({ 23, 583, 53, 61 }); waterExplosion.anim.PushBack({ 85, 585, 53, 63 }); waterExplosion.anim.PushBack({ 143,590, 53, 64 }); waterExplosion.anim.PushBack({ 200, 591, 58, 63 }); waterExplosion.anim.PushBack({ 21, 688,57, 64 }); waterExplosion.anim.PushBack({ 91, 671, 55, 60 }); waterExplosion.anim.PushBack({ 166, 673, 52, 59 }); waterExplosion.anim.loop = false; waterExplosion.anim.speed = 0.3; waterExplosion.life = 360; waterExplosion.speed = { 0,0 }; enemyattack.anim.PushBack({ 288,107,6,6 }); enemyattack.anim.PushBack({ 299, 107, 6,6 }); enemyattack.anim.PushBack({ 311, 107, 6,6 }); enemyattack.anim.loop = true; enemyattack.anim.speed = 0.5f; enemyattack.life = 1200; enemyattack.speed.x = -3; enemy_bullet.anim.PushBack({40, 489, 6, 6}); enemy_bullet.anim.PushBack({ 51, 489, 6, 6 }); enemy_bullet.anim.PushBack({ 63, 489, 6, 6 }); enemy_bullet.anim.PushBack({ 75, 489, 6, 6 }); enemy_bullet.anim.PushBack({ 75, 489, 6, 6 }); enemy_bullet.anim.PushBack({ 88, 489, 6, 6 }); enemy_bullet.anim.PushBack({ 101, 489, 6, 6 }); //enemy_bullet.speed.x = //enemy_bullet.speed.y = enemy_bullet.anim.loop = true; enemy_bullet.life = 2000; //Sharpener bullet sharpener_bullet.anim.PushBack({ 208, 677, 10, 8 }); sharpener_bullet.speed.x = -7; sharpener_bullet.anim.loop = true; sharpener_bullet.life = 1400; //Sharpener shuriken sharpener_shuriken.anim.PushBack({ 167, 650, 10, 10 }); sharpener_shuriken.anim.PushBack({ 180, 650, 10, 10 }); sharpener_shuriken.anim.PushBack({ 193, 651, 8, 8 }); sharpener_shuriken.anim.PushBack({ 204, 651, 8, 8 }); sharpener_shuriken.anim.PushBack({ 215, 650, 10, 10 }); sharpener_shuriken.anim.PushBack({ 228, 650, 10, 10 }); //sharpener_shuriken.speed.x = -7; sharpener_shuriken.anim.loop = true; sharpener_shuriken.life = 1400; //Power Up & Power down power_up.anim.PushBack({436, 657, 30, 17 }); power_up.anim.PushBack({ 436, 675, 29, 17 }); power_up.anim.PushBack({436, 693, 29, 18 }); power_up.anim.loop = true; power_up.anim.speed = 0.20f; power_up.life = 800; power_down.anim.PushBack({ 467, 675, 31, 17 }); power_down.anim.PushBack({ 466, 694, 31, 17 }); power_down.anim.loop = true; power_down.anim.speed = 0.10f; power_down.life = 800; //Coin coin_100.anim.PushBack({ 406, 724, 9, 7 }); coin_100.anim.PushBack({ 406, 733, 9, 7 }); coin_100.anim.PushBack({ 406, 742, 9, 7 }); coin_100.anim.loop = true; coin_100.anim.speed = 0.20f; coin_100.life = 1000; coin_200.anim.PushBack({ 418, 724, 11, 7 }); coin_200.anim.PushBack({ 418, 733, 11, 7 }); coin_200.anim.PushBack({ 418, 742, 11, 7 }); coin_200.anim.loop = true; coin_200.anim.speed = 0.20f; coin_200.life = 1000; coin_500.anim.PushBack({ 432, 724, 11, 7 }); coin_500.anim.PushBack({ 432, 733, 11, 7 }); coin_500.anim.PushBack({ 432, 742, 11, 7 }); coin_500.anim.loop = true; coin_500.anim.speed = 0.20f; coin_500.life = 1000; coin_1000.anim.PushBack({ 446, 724, 13, 7 }); coin_1000.anim.PushBack({ 446, 733, 13, 7 }); coin_1000.anim.PushBack({ 446, 742, 13, 7 }); coin_1000.anim.loop = true; coin_1000.anim.speed = 0.20f; coin_1000.life = 1000; coin_2000.anim.PushBack({ 462, 724, 15, 7 }); coin_2000.anim.PushBack({ 462, 733, 15, 7 }); coin_2000.anim.PushBack({ 462, 742, 15, 7 }); coin_2000.anim.loop = true; coin_2000.anim.speed = 0.20f; coin_2000.life = 1000; coin_4000.anim.PushBack({ 480, 724, 15, 7 }); coin_4000.anim.PushBack({ 480, 733, 15, 7 }); coin_4000.anim.PushBack({ 480, 742, 15, 7 }); coin_4000.anim.loop = true; coin_4000.anim.speed = 0.20f; coin_4000.life = 1000; //Bleeding bleeding.anim.PushBack({ 16, 799, 36, 15 }); bleeding.anim.PushBack({ 66, 797, 44, 19 }); bleeding.anim.PushBack({ 124, 798, 49, 17 }); bleeding.anim.PushBack({ 197, 799, 44, 17 }); bleeding.anim.PushBack({ 248, 800, 47, 18 }); bleeding.anim.PushBack({ 306, 799, 48, 17 }); bleeding.anim.PushBack({ 373, 795, 46, 20 }); bleeding.anim.PushBack({ 439, 796, 42, 20 }); bleeding.anim.loop = false; bleeding.anim.speed = 0.25f; bleeding.life = 1200; //Enemies Explosion explosion.anim.PushBack({ 14, 832, 52, 48 }); explosion.anim.PushBack({ 74, 828, 51, 56 }); explosion.anim.PushBack({ 133, 828, 56, 62 }); explosion.anim.PushBack({ 193, 831, 56, 59}); explosion.anim.PushBack({ 255, 830, 56, 60 }); explosion.anim.PushBack({ 320, 829, 52, 64 }); explosion.anim.PushBack({ 378, 828, 57, 67}); explosion.anim.PushBack({ 11, 910, 59, 66 }); explosion.anim.PushBack({ 77, 909, 60, 68 }); explosion.anim.PushBack({ 142, 908, 58, 66 }); explosion.anim.PushBack({ 208, 908, 56, 63 }); explosion.anim.loop = false; explosion.anim.speed = 0.10f; explosion.life = 700; //Chariot Explosion chariot_explosion.anim.PushBack({ 546, 779, 29, 28 }); chariot_explosion.anim.PushBack({ 610, 778, 31, 31}); chariot_explosion.anim.PushBack({ 672, 776, 36, 34 }); chariot_explosion.anim.PushBack({ 734, 776, 40, 38 }); chariot_explosion.anim.PushBack({ 534, 838, 38, 42 }); chariot_explosion.anim.PushBack({ 606, 839, 38, 41 }); chariot_explosion.anim.PushBack({ 673, 838, 36, 41 }); chariot_explosion.anim.PushBack({ 736, 837, 37, 43 }); chariot_explosion.anim.PushBack({ 548, 901, 33, 41 }); chariot_explosion.anim.PushBack({ 612, 904, 32, 37 }); chariot_explosion.anim.PushBack({ 678, 906, 29, 33 }); chariot_explosion.anim.PushBack({ 743, 908, 29, 30 }); chariot_explosion.anim.loop = false; chariot_explosion.anim.speed = 0.10f; chariot_explosion.life = 700; //Chariot big Explosion chariot_big_explosion.anim.PushBack({ 549, 11, 113, 101 }); chariot_big_explosion.anim.PushBack({ 665, 13, 110, 99 }); chariot_big_explosion.anim.PushBack({ 543, 122, 111, 133 }); chariot_big_explosion.anim.PushBack({ 662, 122, 114, 130 }); chariot_big_explosion.anim.PushBack({ 549, 264, 106, 93 }); chariot_big_explosion.anim.PushBack({ 659, 259, 111, 100 }); chariot_big_explosion.anim.PushBack({ 673, 838, 36, 41 }); chariot_big_explosion.anim.PushBack({ 778, 260, 108, 134}); chariot_big_explosion.anim.PushBack({ 891, 261, 110, 112 }); chariot_big_explosion.anim.PushBack({ 548, 363, 116, 113 }); chariot_big_explosion.anim.PushBack({666, 364, 99, 96 }); chariot_big_explosion.anim.loop = false; chariot_big_explosion.anim.speed = 0.10f; chariot_big_explosion.life = 700; //ball shot ball_bullet.anim.PushBack({ 530, 629, 26, 13 }); ball_bullet.anim.PushBack({ 657, 628, 31, 14}); ball_bullet.anim.PushBack({ 786, 628, 29, 15}); ball_bullet.anim.PushBack({ 913, 620, 69, 29}); ball_bullet.anim.PushBack({ 529, 652, 71, 29 }); ball_bullet.anim.PushBack({ 657, 655, 81, 23 }); ball_bullet.anim.PushBack({ 785, 655, 99, 23}); ball_bullet.anim.PushBack({ 914, 656, 94, 22 }); ball_bullet.anim.PushBack({ 530, 689, 91, 20 }); ball_bullet.anim.PushBack({ 656, 690, 100, 18 }); ball_bullet.anim.PushBack({ 785, 690, 95, 18 }); ball_bullet.anim.PushBack({ 529, 720, 92, 21 }); ball_bullet.speed.x = -4; ball_bullet.anim.loop = false; ball_bullet.life = 2000; //chariot bullet chariot_bullet.anim.PushBack({579, 511, 16, 18}); chariot_bullet.anim.PushBack({609, 511, 20, 18}); chariot_bullet.anim.PushBack({642, 511, 18, 18}); chariot_bullet.anim.PushBack({578, 543, 18, 18}); chariot_bullet.anim.PushBack({610, 543, 19, 18}); chariot_bullet.anim.PushBack({ 641, 543, 20, 18 }); chariot_bullet.anim.PushBack({ 579, 575, 17, 17 }); chariot_bullet.anim.PushBack({ 609, 575, 20, 18 }); chariot_bullet.anim.loop = false; chariot_bullet.life = 2000; return true; } // Unload assets bool ModuleParticles::CleanUp() { LOG("Unloading particles"); //App->textures->Unload(graphics); //App->textures->Unload(graphics1); //App->textures->Unload(graphics2); //App->textures->Unload(graphics3); App->textures->Unload(graphics4); fx_death = nullptr; Katana_Death = nullptr; Katana_Explosion = nullptr; for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if(active[i] != nullptr) { delete active[i]; active[i] = nullptr; } } return true; } // Update: draw background update_status ModuleParticles::Update() { // Update Particle Emmiters ParticleEmmiter* p_emmiter = nullptr; for (uint i = 0; i < MAX_ACTIVE_EMMITERS; ++i) { p_emmiter = emitters_active[i]; if (p_emmiter != nullptr) { if (p_emmiter->Kill()) { delete p_emmiter; emitters_active[i] = nullptr; } else { p_emmiter->Update(); } } } // Update Particles for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] != nullptr) { active[i]->Update(graphics4); if (!active[i]->Valid()) { Particle* p = active[i]; delete p; active[i] = nullptr; } } } //HandleParticleArray(); return UPDATE_CONTINUE; } void ModuleParticles::AddParticle(const Particle& particle, int x, int y, /*int speedx, int speedy,*/ COLLIDER_TYPE collider_type, PARTICLE_TYPE particle_type, Uint32 delay) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] == nullptr) { Particle* p = new Particle(particle); p->born = SDL_GetTicks() + delay; p->position.x = x; p->position.y = y; /*p->speed.x = speedx; p->speed.y = speedy;*/ if (collider_type != COLLIDER_NONE) p->collider = App->collision->AddCollider(p->anim.GetCurrentFrame(), collider_type, this); active[i] = p; break; } } } // ------------------------------------------------------------- // ------------------------------------------------------------- bool ModuleParticles::AddParticle(Particle* p) { bool ret = false; if (p != nullptr) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES && !ret; ++i) { if (this->active[i] == nullptr) { this->active[i] = p; ret = true; } } } return ret; } bool ModuleParticles::AddEmmiter(EmmiterType type, fPoint* pos) { if (pos != nullptr) { for (uint i = 0; i < MAX_ACTIVE_EMMITERS; ++i) { ParticleEmmiter* p_emmiter = emitters_active[i]; if (p_emmiter == nullptr) { switch (type) { case AJIN_ULT: emitters_active[i] = new AjinUlt(&ulti_ayin, pos); break; case SHARPENER_BURST: emitters_active[i] = new SharpenerBurst(&sharpener_shuriken, pos); break; } return (emitters_active[i] != nullptr && !emitters_active[i]->Kill()); } } } } void ModuleParticles::HandleParticleArray() { for (uint i2 = 0; i2 < MAX_ACTIVE_PARTICLES; ++i2) { if (active[i2] != nullptr) { if (i2 > 0 && active[i2 - 1] == nullptr) { active[i2 - 1] = active[i2]; active[i2] = nullptr; i2--; } } } } int ModuleParticles::GetAvailableStorage(uint wanted) const { int ret = 0; for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] == nullptr) ret++; } ret = MIN(wanted, ret); return ret; } void ModuleParticles::OnCollision(Collider* c1, Collider* c2) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { // Always destroy particles that collide if (active[i] != nullptr && active[i]->collider == c1) { if (c2->type == COLLIDER_TYPE::COLLIDER_PLAYER && c1->type == COLLIDER_TYPE::COLLIDER_ENEMY_SHOT) { if (c2 == App->katana->coll) { if (timer) { time_on_entry = SDL_GetTicks(); timer = false; } current_time = SDL_GetTicks() - time_on_entry; if (current_time > 1000) { App->katana->explosion = true; //App->audio->PlaySoundEffects(App->enemies->fx_death); Mix_PlayChannel(-1, Katana_Explosion, 0); Mix_PlayChannel(-1, Katana_Death, 0); Mix_PlayChannel(-1, fx_death, 0); App->particles->AddParticle(App->particles->explosion, active[i]->position.x, active[i]->position.y); //App->audio->PlaySoundEffects(koyori_death); App->inter->num_life_katana--; timer = true; } App->katana->state = DEATH; } } //AddParticle(explosion, active[i]->position.x, active[i]->position.y); delete active[i]; active[i] = nullptr; break; } } } Particle::Particle() { position.SetToZero(); speed.SetToZero(); } Particle::Particle(const Particle& p) : anim(p.anim), position(p.position), speed(p.speed), fx(p.fx), born(p.born), life(p.life) {} Particle::~Particle() { if (collider != nullptr) collider->to_delete = true; } void Particle::Update(SDL_Texture* tex) { actual_life = SDL_GetTicks() - born; //LOG("Updating Particle - actual_life: %d", actual_life); position.x += speed.x + App->scene_temple->speed; position.y += speed.y; if (tex != nullptr) { App->render->Blit( tex, int(position.x), int(position.y), &(anim.GetCurrentFrame())); } if (collider != nullptr) collider->SetPos(position.x, position.y); } bool Particle::Valid() { bool ret = true; if (life > 0) { if (actual_life > life) { LOG("Particle dies after %d", actual_life); ret = false; } } else if (anim.Finished()) { ret = false; } return ret; } ParticleEmmiter::ParticleEmmiter(Particle* p, fPoint* pos) : particle_emited(p), position(pos), life_time(0), repetitions_current(0) { trigger_time = SDL_GetTicks(); valid = (pos != nullptr); offset.SetToZero(); } AjinUlt::AjinUlt(Particle* p, fPoint* pos) : ParticleEmmiter(p, pos) { interval = 180; repetitions_total = 4; offset.x = 5; offset.y = -35; speed.x = 5.f; speed.y = 0.f; total_particles = 1; } void AjinUlt::Update() { life_time = SDL_GetTicks() - trigger_time; if (repetitions_current == repetitions_total) { valid = false; } else if (life_time > interval * repetitions_current) { Particle* p = nullptr; p = new Particle(*particle_emited); p->born = SDL_GetTicks(); p->position.x = int(position->x) + offset.x; p->position.y = int(position->y) + offset.y; p->speed.x = speed.x; p->speed.y = speed.y; //p->collider = App->collision->AddCollider(p->anim.GetCurrentFrame(), COLLIDER_PLAYER_AYIN_ULTI, App->particles); App->particles->AddParticle(p); repetitions_current++; } } SharpenerBurst::SharpenerBurst(Particle* p, fPoint* pos) : ParticleEmmiter(p, pos) { interval = 250; repetitions_total = 4; total_particles = 32; speed_multiplier = 6.0f; offset.x = 50; offset.y = 40; } void SharpenerBurst::Update() { life_time = SDL_GetTicks() - trigger_time; if (repetitions_current == repetitions_total) { valid = false; } else if (life_time > interval * repetitions_current) { double angle_interval = 360.f / total_particles; // Radius casting using the angle to change speeds for (double angle = 0; angle < 360; angle += angle_interval) { Particle* p = new Particle(*particle_emited); p->born = SDL_GetTicks(); p->position.x = int(position->x) + offset.x; p->position.y = int(position->y) + offset.y; // Each has different direction p->speed.x = SDL_sin(angle) * speed_multiplier; p->speed.y = SDL_cos(angle) * speed_multiplier; p->collider = App->collision->AddCollider(p->anim.GetCurrentFrame(), COLLIDER_ENEMY_SHARPENER_KNIFE, App->particles); App->particles->AddParticle(p); } repetitions_current++; } }
struct P{double x,y;}p[2005],s[2005]; double dis(P a,P b) { return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y); } P operator-(P a,P b) { P t;t.x=a.x-b.x;t.y=a.y-b.y;return t; } double operator*(P a,P b) { return a.x*b.y-a.y*b.x; } bool operator<(P a,P b) { double t=(a-p[1])*(b-p[1]); if(t==0)return dis(a,p[1])<dis(b,p[1]); return t<0; } void graham() { int k=1; for(int i=2;i<=n;i++) if(p[k].y>p[i].y||(p[k].y==p[i].y&&p[k].x>p[i].x)) k=i; swap(p[1],p[k]); sort(p+2,p+n+1); s[++top]=p[1];s[++top]=p[2]; for(int i=3;i<=n;i++) { while(top>1&&(p[i]-s[top-1])*(s[top]-s[top-1])<=0) top--; s[++top]=p[i]; } }
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( SIVA ) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESDefs_TabularData_HeaderFile #define _IGESDefs_TabularData_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <IGESData_IGESEntity.hxx> #include <TColStd_HArray1OfReal.hxx> class IGESBasic_HArray1OfHArray1OfReal; class IGESDefs_TabularData; DEFINE_STANDARD_HANDLE(IGESDefs_TabularData, IGESData_IGESEntity) //! Defines IGES Tabular Data, Type <406> Form <11>, //! in package IGESDefs //! This Class is used to provide a Structure to accommodate //! point form data. class IGESDefs_TabularData : public IGESData_IGESEntity { public: Standard_EXPORT IGESDefs_TabularData(); //! This method is used to set the fields of the class //! TabularData //! - nbProps : Number of property values //! - propType : Property Type //! - typesInd : Type of independent variables //! - nbValuesInd : Number of values of independent variables //! - valuesInd : Values of independent variables //! - valuesDep : Values of dependent variables //! raises exception if lengths of typeInd and nbValuesInd are not same Standard_EXPORT void Init (const Standard_Integer nbProps, const Standard_Integer propType, const Handle(TColStd_HArray1OfInteger)& typesInd, const Handle(TColStd_HArray1OfInteger)& nbValuesInd, const Handle(IGESBasic_HArray1OfHArray1OfReal)& valuesInd, const Handle(IGESBasic_HArray1OfHArray1OfReal)& valuesDep); //! returns the number of property values (recorded) Standard_EXPORT Standard_Integer NbPropertyValues() const; //! determines the number of property values required Standard_EXPORT Standard_Integer ComputedNbPropertyValues() const; //! checks, and correct as necessary, the number of property //! values. Returns True if corrected, False if already OK Standard_EXPORT Standard_Boolean OwnCorrect(); //! returns the property type Standard_EXPORT Standard_Integer PropertyType() const; //! returns the number of dependent variables Standard_EXPORT Standard_Integer NbDependents() const; //! returns the number of independent variables Standard_EXPORT Standard_Integer NbIndependents() const; //! returns the type of the num'th independent variable //! raises exception if num <= 0 or num > NbIndependents() Standard_EXPORT Standard_Integer TypeOfIndependents (const Standard_Integer num) const; //! returns the number of different values of the num'th indep. variable //! raises exception if num <= 0 or num > NbIndependents() Standard_EXPORT Standard_Integer NbValues (const Standard_Integer num) const; Standard_EXPORT Standard_Real IndependentValue (const Standard_Integer variablenum, const Standard_Integer valuenum) const; Standard_EXPORT Handle(TColStd_HArray1OfReal) DependentValues (const Standard_Integer num) const; Standard_EXPORT Standard_Real DependentValue (const Standard_Integer variablenum, const Standard_Integer valuenum) const; DEFINE_STANDARD_RTTIEXT(IGESDefs_TabularData,IGESData_IGESEntity) protected: private: Standard_Integer theNbPropertyValues; Standard_Integer thePropertyType; Handle(TColStd_HArray1OfInteger) theTypeOfIndependentVariables; Handle(TColStd_HArray1OfInteger) theNbValues; Handle(IGESBasic_HArray1OfHArray1OfReal) theIndependentValues; Handle(IGESBasic_HArray1OfHArray1OfReal) theDependentValues; }; #endif // _IGESDefs_TabularData_HeaderFile
#include <iostream> #include <stdlib.h> #include <cstdio> #include "h_seqlist.h" #include "seqlist.cpp" using namespace std; int main() { SeqList <int> List1(100); while(1) { int value ; int num ;//序号 int x ;//输入的值 int m ;//保存输入序号 List1.Menu(); cin>>m; switch(m) { case 1:/*1.输入顺序表 Input*/ List1.Input(); break; case 2:/*2.获取当前表最大项数*/ cout<<" 当前表最大项数为:"<<List1.ListSize()<<endl; break; case 3:/*3.获取当前表已存项数*/ cout<<" 当前表已存项数为:"<<List1.ListLen()<<endl; break; case 4:/*4.获取元素 GetData*/ cout<<" 请输入要获取的元素序号(1~"<<List1.ListLen()<<"):"<<endl; cin>>num; List1.GetData(num, value); cout<<" #"<<num<<":"<<value<<endl; break; case 5:/*5.插入元素 Insert*/ cout<<" 请输入要插入的项数序号(1~"<<List1.ListLen()<<")及要插入的元素(用空格隔开):"<<endl; cin>>num>>x; while(List1.GetData(num, value)==false) { cout<<" 你输入的序号超出范围!请重新输入:"; cin>>num>>x; } cout<<" 原#"<<num<<":"<<value<<endl; List1.Insert(num,x); List1.GetData(num, value); cout<<" 现#"<<num<<":"<<value<<endl; break; case 6:/*6.移除元素 Remove*/ cout<<" 请输入要移除的元素序号(1~"<<List1.ListLen()<<"):"<<endl; cin>>num; while(List1.Remove(num, value)==false) { cout<<" 你输入的序号超出范围!请重新输入:"; cin>>num; } List1.Remove(num,value); cout<<" #"<<num<<":"<<value<<"已移除!"<<endl; break; case 7:/*7.设置元素 SetElem*/ cout<<" 请输入要设置的元素序号(1~"<<List1.ListLen()<<")及其赋值(用空格隔开):"<<endl; cin>>num>>x; List1.GetData(num, value); cout<<" 原#"<<num<<":"<<value<<endl; List1.SetElem(num,x); List1.GetData(num, value); cout<<" 现#"<<num<<":"<<value<<endl; break; case 8:/*8.搜索元素 Search*/ cout<<" 请输入要搜索的元素值:"<<endl; cin>>x; cout<<" 该元素的序号为:#"<<List1.Search(x)<<endl; break; case 9:/*9.定位元素 Locate*/ cout<<" 请输入要定位的表项序号(1~"<<List1.ListLen()<<"):"<<endl; cin>>num; cout<<" #"<<num<<"的位置是:"<<List1.Locate(num)<<endl; break; case 10:/*10.判断存储状态 IsEmpty/IsFull*/ if(List1.IsEmpty()) cout<<" 顺序表为空!"<<endl; else if(List1.IsFull()) cout<<" 顺序表已满!"<<endl; else cout<<" 当前顺序表存储状态为:" <<"("<<List1.ListLen()<<"/"<<List1.ListSize()<<")"<<endl; break; case 11:/*11.输出顺序表 Output*/ List1.Output(); break; case 12:/*12.退出*/ cout<<" ……即将退出程序……"<<endl; return 0 ; break; default: cout << "error" << endl; return 0; } } return 0; }
// // Created by JACK on 9/15/2015. // #ifndef CEF02B_MATRIX_H #define CEF02B_MATRIX_H #include <stdlib.h> /* error: 0 -no error * 1 - size incompatible * 2 - no memory * 3 - memory exist * 4 - object crated succesfuly * */ class Matrix{ int **ptr; int nRow; int nCol; int error; public: void getError(); void setError(int error) { Matrix::error = error; } public: Matrix(); Matrix(int); Matrix(int, int); int get_ptr(int, int); int get_nRow(); int get_nCol(); void fill_matrix(); void print_matrix(); ~Matrix(); friend void add_matrix_with_matrix(Matrix* m1,Matrix* m2); friend void sub_matrix_with_matrix(Matrix* m1,Matrix* m2); friend void mult_matrix_with_matrix(Matrix* m1,Matrix* m2); friend void add_matrix_with_number(Matrix* m1,int num); }; #endif //CEF02B_MATRIX_H
#include "stdio.h" #include "conio.h" void main () { clrscr(); int i; printf("\n\n\t"); for (i=1; i<=40; i++) printf("%c",'\xDB'); getch(); }
#include <Windows.h> #ifndef __HSCOMPTR__ #define __HSCOMPTR__ template <typename T> class HSComType : public T { private: //IUnknown インタフェースクラス メンバの2つをprivateにする virtual ULONG STDMETHODCALLTYPE AddRef ( void ) = 0; virtual ULONG STDMETHODCALLTYPE Release ( void ) = 0; }; template <typename T> class HSComPtrBase { protected : T *pm_Interface; public: HSComPtrBase () { pm_Interface = nullptr; } ~HSComPtrBase () { this->Release (); } HRESULT CreateInstance ( const IID Clsid , const IID riid = __uuidof( T )) { if ( pm_Interface != nullptr )return E_FAIL; return CoCreateInstance ( Clsid , NULL , CLSCTX_INPROC_SERVER , riid , (void**) &pm_Interface ); } ULONG AddRef ( void ) { if ( pm_Interface == nullptr )return E_FAIL; return ( (IUnknown*) pm_Interface )->AddRef (); } ULONG Release ( void ) { if ( pm_Interface == nullptr )return E_FAIL; ULONG uRet = ( (IUnknown*) pm_Interface )->Release (); this->pm_Interface = nullptr; return uRet; } bool CheckCreatedInstance ( void ) { return ( pm_Interface ) ? true : false; } HSComType<T> * operator ->( ) { return reinterpret_cast<HSComType<T>*>( pm_Interface ); } }; template <typename T> class HSComPtr : public HSComPtrBase < T > { public: T* Attach ( T* pInterface ) { if ( pInterface == nullptr ) return nullptr; T* old = this->pm_Interface; this->pm_Interface = pInterface; return old; } T* Detach ( void ) { T* det = this->pm_Interface; this->pm_Interface = nullptr; return det; } T** operator&( ) { if ( pm_Interface != nullptr )return nullptr; return &this->pm_Interface; } HSComType<T> * Get ( void ) { return reinterpret_cast<HSComType<T>*>( pm_Interface ); } operator T*( ) { return this->pm_Interface; } }; #endif
#include"head_info.h" #include<time.h> #include<stdlib.h> #include<iostream> #include<bitset> #define MAX 10 int main(){ //排序算法 //int s[MAX],i; //srand((unsigned)time(0)); //for ( i=0;i<MAX;i++ ) // s[i] = rand()%100; //showArray(s,MAX); //shell_sort(s,MAX); ////quick_sort_norecursion(s,0,MAX-1); //showArray(s,MAX); //fibonacci递归和非递归 //std::cout<<"\n"<<fibonacci(20)<<" || "<<fibonacci_norecursion(20)<<std::endl; int s[] = {5,24,8,4,91,6,64,29,43,10}; BinaryTree mytree(s,MAX); //mytree.preOrder(mytree.getRoot()); //mytree.midOrder(mytree.getRoot()); /*mytree.postOrder_unrecursive(mytree.getRoot()); std::cout<<std::endl; mytree.breadthTraversal(mytree.getRoot()); std::cout<<std::endl; std::cout<<"tree depth:"<<mytree.getDepth(mytree.getRoot())<<std::endl;*/ std::cout<<mytree.findAndPrintPath(6)<<std::endl; /*int a[8] = {0}; if( placeQueue(a,0) ) showEightQueue(a);*/ /*double a=2.6+3.7, c = 6.3; std::cout<<a<<" "<<c<<std::endl; if( a==c ) std::cout<<a<<" "<<c<<" a=c"<<std::endl; float b = pow((float)2,(float)-128); int * p = (int *)(void*)&b; if( *p!=0 ) std::cout<<"b is not 0"<<std::endl; std::bitset<32> mybits(*p); std::cout<<mybits<<std::endl; if( !(*p & 0x7fffffff) ) std::cout<< "b is 0\n"; else std::cout<< "b is not 0"<<std::endl; float d = 123.456789; std::cout<<d<<std::endl;*/ } #if 0 //重新自己写一遍!! #include <map> #include <functional> #include <vector> #include <iostream> using namespace std; typedef std::pair<int, int> Range_t; typedef std::pair<Range_t, std::function<double (int)> > Range_Func_t; typedef std::vector<Range_Func_t> Rang2Funcs_t; int main() { Rang2Funcs_t rfs; rfs.push_back(std::make_pair(std::make_pair(0, 300), [](int x){return 2 * x;})); rfs.push_back(std::make_pair(std::make_pair(301, 600), [](int x){return 10 * (x-300);})); rfs.push_back(std::make_pair(std::make_pair(601, 700), [](int x){return 15 * (x-600);})); int x = 620; double ans = 0; for(auto it= rfs.begin(); it != rfs.end(); it++) { Range_t r = it->first; if(x > r.second) ans += it->second(r.second); else if(x >= r.first && x <= r.second) { ans += it->second(x); } } std::cout<<"For x:"<<x<<", we get:"<<ans<<std::endl; return 0; } #include<iostream> class Base{ protected: static int a; int c; }; class b:public Base{ public: void foo(b b1,Base b2){ b1.a = 1; b1.c = 2; } }; void main(){ char str[] = "abcdefg"; int a[] = {1,2,3}; std::cout<<sizeof(str)<<" "<<sizeof(a)<<std::endl; } void main() { char s[] = "abcdef"; reverse_string(s,6); std::cout<<s<<std::endl; } #endif
// // STLVectorUtility.h // Author: Michael Bao // Date: 9/4/2015 // #pragma once #include <vector> #include <utility> namespace STLVectorUtility { template<typename T1, typename T2> void SplitVectorOfPairs(const std::vector<std::pair<T1, T2>>& input, std::vector<T1>& output1, std::vector<T2>& output2) { output1.clear(); output1.reserve(input.size()); output2.clear(); output2.reserve(input.size()); for (auto i = decltype(input.size()){0}; i < input.size(); ++i) { output1.emplace_back(input.at(i).first); output2.emplace_back(input.at(i).second); } } template<typename T1, typename T2> void ZipVectors(const std::vector<T1>& input1, const std::vector<T2>& input2, std::vector<std::pair<T1, T2>>& output) { output.clear(); const auto totalSize = std::min(input1.size(), input2.size()); output.reserve(totalSize); for (auto i = decltype(totalSize){0}; i < totalSize; ++i) { output.emplace_back(std::make_pair(input1.at(i), input2.at(2))); } } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int main() { double d,h,v,e; scanf("%lf%lf%lf%lf",&d,&h,&v,&e); double s = pi*(d/2)*(d/2); if (v/s <= e) puts("NO"); else { puts("YES"); printf("%.12lf\n",h/(v/s-e)); } return 0; }
//g++ 5.4.0 // Moulik Aggarwal - www.github.com/moulikcipherx //all header file included #include <bits/stdc++.h> //for STL library using namespace std; //hamming distance of two strings int hamming(string str1, string str2) { int count = 0; for(int i = 0; i< str1.length(); i++) { if(str1[i] != str2[i]) count++; //Increment the counter when char is not match } return count; } //driver function int main() { string str1,str2; //Enter the two strings std::cout<<"Enter the first String\n"; std::cin>>str1; std::cout<<"Enter the Second String\n"; std::cin>>str2; std::cout<<"Hamming Distance of Given Strings is: "<<hamming(str1,str2)<<'\n'; return 0; }
/* * bracesInit.cpp * * Created on: May 9, 2016 * Author: bakhvalo */ #include "gtest/gtest.h" #include <type_traits> class bracesInit { public: int x {1}; int y = 2; // int z(0); not compiles. }; TEST(BraceInitUnitTest, class_private_fields_init) { bracesInit brIn; ASSERT_EQ(1, brIn.x); ASSERT_EQ(2, brIn.y); } // If in ctor or function parameters there is a std::initializer_list // it will be greedily chosen by the caller to other overloads. // // example: // // foo (int i, double d); // foo (std::initializer_list<long double>) // // foo({5, 10.5}) // calls 2nd overload. // // Rule: if there is a way to call overload with std::initializer it will be called. // // But empty braces means default construction: class bracesDef { public: int x; bracesDef() {x = 1;} bracesDef(std::initializer_list<int>) {x = 2;} }; TEST(BraceInitUnitTest, empty_braces_init) { bracesDef brD1; ASSERT_EQ(1, brD1.x); //bracesDef brD1(); // most vexing parse bracesDef brD2{}; ASSERT_EQ(1, brD2.x); } TEST(BraceInitUnitTest, if_you_want_to_call_inti_list) { bracesDef brD1({}); ASSERT_EQ(2, brD1.x); bracesDef brD2{{}}; ASSERT_EQ(2, brD2.x); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/locale/oplanguagemanager.h" #include "modules/locale/locale-enum.h" OP_STATUS SetLangString(Str::LocaleString str, OpString &target) { if(str == 0) { target.Empty(); return OpStatus::OK; } return g_languageManager->GetString(str, target); } #endif
#include <unistd.h> #include <arpa/inet.h> #include <qt5/QtCore/QByteArray> #include <qt5/QtCore/QDataStream> #include <qt5/QtNetwork/QTcpSocket> #include <qt5/QtNetwork/QHostAddress> #include <qt5/QtWidgets/QFileDialog> #include <qt5/QtWidgets/QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" struct __attribute__((packed)) hello { unsigned int magic; char user[32]; char file[256]; }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), sock(new QTcpSocket), addr(new QHostAddress), file(new QString) { ui->setupUi(this); } MainWindow::~MainWindow() { delete file; delete addr; delete sock; delete ui; } void MainWindow::on_lineEditAddress_textEdited(const QString &newAddr) { addr->setAddress(newAddr); ui->pushButtonSelect->setEnabled(newAddr.length()); } void MainWindow::on_pushButtonSelect_clicked() { QFileInfo info = QFileDialog::getOpenFileName(this, "Select the file...", "~"); if (!info.fileName().length()) return; if (!info.isReadable()) { QMessageBox box; box.setIcon(QMessageBox::Critical); box.setInformativeText("Permission denied"); box.setText("Could not open the file"); box.exec(); return; } *file = info.absoluteFilePath(); ui->pushButtonSend->setEnabled(true); ui->pushButtonSelect->setText(info.fileName()); ui->progressBarUpload->setValue(ui->progressBarUpload->minimum()); } void MainWindow::on_pushButtonSend_clicked() { QByteArray name = file->toLocal8Bit(); struct hello hello; hello.magic = htonl(0xdeadbeef); getlogin_r(hello.user, sizeof(hello.user)-1); strncpy(hello.file, name.data(), sizeof(hello.file)); hello.user[sizeof(hello.user)-1] = '\0'; hello.file[sizeof(hello.file)-1] = '\0'; QFile f(*file); if (!f.open(QFile::ReadOnly)) return; sock->connectToHost(*addr, 2137); sock->write((const char *)&hello, sizeof(hello)); qint64 chunk = 4096, size = f.size(); ui->progressBarUpload->setMaximum(size); QByteArray data = f.read(chunk); while (data.length()) { sock->write(data); data = f.read(chunk); ui->progressBarUpload->setValue(f.pos()); } sock->disconnectFromHost(); sock->close(); f.close(); }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> #include <numeric> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, k; int a[111111]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); cin >> n >> k; for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); LL ans = 0; for (int i = 0; i < n; i++) { int x = a[i] - k; pair<int*, int*> t = equal_range(a, a + n, x); ans += t.second - t.first; } cout << ans << endl; return 0; }
#ifndef WIDGETCONTROL_HPP #define WIDGETCONTROL_HPP #include "Worker.hpp" #include <QApplication> #include <QThread> #include <QWidget> namespace Ui { class WidgetControl; } class WidgetControl : public QWidget { Q_OBJECT public: explicit WidgetControl(QWidget *parent = nullptr); void setupWidget(QWidget *widget); ~WidgetControl(); private slots: void startBtnSlot(); void stopBtnSlot(); void killBtnSlot(); private: Ui::WidgetControl *ui; Worker *w; }; #endif // WIDGETCONTROL_HPP
#pragma once #include <vector> using namespace std; class Account { private: double initialInvestment = 0.00; double monthlyDeposit = 0.00; double interestRate = 0.00; int numberOfYears = 0; std::vector<double> yearlyBalance = { 0.00 }; std::vector<double> yearlyInterestEarned = { 0.00 }; public: void SetInitialInvestment(double x); void SetMonthlyDeposit(double x); void SetInterestRate(double x); void SetNumberOfYears(int x); void SetYearlyBalance(); double GetInitialInvestment(); double GetMonthlyDeposit(); double GetInterestRate(); int GetNumberOfYears(); double GetYearlyBalance(int i); double GetYearlyInterestEarned(int i); void DisplayAllValues(); };
#include "game.h" Game::Game(QGraphicsScene * s) { this->s = s; } void Game::makeBios() { // 5개의 생명체 생성. for (int i = 0; i < 5; i++) { int prob = rand() % 100 + 1; if (prob >= 0 && prob <= 70) // 70%의 확률로 Feed 생성. { bios.push_back(dynamic_cast<Bio*>(new Feed(s))); } else if (prob > 70 && prob <= 85) // 15%의 확률로 Virus 생성. { bios.push_back(dynamic_cast<Bio*>(new Virus(s))); } else // 15%의 확률로 Enemy 생성. { bios.push_back(dynamic_cast<Bio*>(new Enemy(s))); } } } void Game::playGame() { // player와 30개의 생명체 생성. player = dynamic_cast<Bio*>(new Cell(s)); for (int i = 0; i < 6; i++) makeBios(); // 15초마다 5개의 생명체 생성. makeTimer = new QTimer(); connect(makeTimer, SIGNAL(timeout()), this, SLOT(makeBios())); makeTimer->start(15000); // // 50ms마다 game over 체크. // overTimer = new QTimer(); // connect(overTimer, SIGNAL(timeout()), this, SLOT(gameOver())); // overTimer->start(50); }
// 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/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef SHOOTERSTARTER_BTService_ClearPlayerLocation_generated_h #error "BTService_ClearPlayerLocation.generated.h already included, missing '#pragma once' in BTService_ClearPlayerLocation.h" #endif #define SHOOTERSTARTER_BTService_ClearPlayerLocation_generated_h #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_SPARSE_DATA #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_RPC_WRAPPERS #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_RPC_WRAPPERS_NO_PURE_DECLS #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUBTService_ClearPlayerLocation(); \ friend struct Z_Construct_UClass_UBTService_ClearPlayerLocation_Statics; \ public: \ DECLARE_CLASS(UBTService_ClearPlayerLocation, UBTService_BlackboardBase, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/ShooterStarter"), NO_API) \ DECLARE_SERIALIZER(UBTService_ClearPlayerLocation) #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_INCLASS \ private: \ static void StaticRegisterNativesUBTService_ClearPlayerLocation(); \ friend struct Z_Construct_UClass_UBTService_ClearPlayerLocation_Statics; \ public: \ DECLARE_CLASS(UBTService_ClearPlayerLocation, UBTService_BlackboardBase, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/ShooterStarter"), NO_API) \ DECLARE_SERIALIZER(UBTService_ClearPlayerLocation) #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UBTService_ClearPlayerLocation(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBTService_ClearPlayerLocation) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTService_ClearPlayerLocation); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTService_ClearPlayerLocation); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UBTService_ClearPlayerLocation(UBTService_ClearPlayerLocation&&); \ NO_API UBTService_ClearPlayerLocation(const UBTService_ClearPlayerLocation&); \ public: #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UBTService_ClearPlayerLocation(UBTService_ClearPlayerLocation&&); \ NO_API UBTService_ClearPlayerLocation(const UBTService_ClearPlayerLocation&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTService_ClearPlayerLocation); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTService_ClearPlayerLocation); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(UBTService_ClearPlayerLocation) #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_PRIVATE_PROPERTY_OFFSET #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_12_PROLOG #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_PRIVATE_PROPERTY_OFFSET \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_SPARSE_DATA \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_RPC_WRAPPERS \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_INCLASS \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_PRIVATE_PROPERTY_OFFSET \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_SPARSE_DATA \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_INCLASS_NO_PURE_DECLS \ ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h_15_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> SHOOTERSTARTER_API UClass* StaticClass<class UBTService_ClearPlayerLocation>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID ShooterStarter_Source_ShooterStarter_BTService_ClearPlayerLocation_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
#include <vector> #include <iostream> #include <unistd.h> #include <omp.h> double conta_complexa(int i) { return 2 * i; } int main() { int N = 100000000; std::vector<double> vec(N); #pragma omp parallel for default(none) shared(vec) shared(N) for (int i = 0; i < N; i++) { vec[i] = conta_complexa(i); } // for (int i = 0; i < N; i++) { // std::cout << i << " "; // } return 0; }