blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
16a56cb04091d98f42dfd66b5c5f6487e5d2f429
aa3dcfd5842f069b3b356131813086e0613b5e7c
/CodeForces/230b.cpp
2730d46491ad74b39889a22a98960edd729e2ac8
[]
no_license
Ajimi/Practice-C-CPP
029584047588b9780b7b6e06b18604598caad5f4
b8aa6475dca3b0d63409718e9ac714a65c03ebdd
refs/heads/master
2021-06-11T21:12:47.097860
2016-12-07T22:33:41
2016-12-07T22:33:41
73,641,804
0
0
null
null
null
null
UTF-8
C++
false
false
412
cpp
230b.cpp
#include "iostream" using namespace std; bool tprime(long long int a){ int k = a / 2 , count = 0; for(int i = 1 ; i <= k ;i++){ if(a % i == 0) count ++; } return count == 2 ; } int main(int argc, char const *argv[]) { long long int n , x; cin >> n; for(int i = 0;i<n; i++){ cin>> x; if(tprime(x)) cout << "YES"; else cout << "NO"; cout << endl; } return 0; }
1ff5933d69b47f83b80eba3fbe794db61b987b29
0d4ecac4c0151f9dcbb1f4213200d18920875770
/Program 14/TemplateFunction.cpp
ada21be3fab00542d97318650725c4d7b74b9e8c
[]
no_license
akshaykhare19/OOPS-BPIT
16ea0b376afe1be61ce4965ad0e287a193b42cbf
e4c3f4b8c7ccdc0eb3f8346b0c6e270c70c44d23
refs/heads/master
2023-06-04T23:14:34.702797
2021-06-20T11:04:03
2021-06-20T11:04:03
378,148,637
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
TemplateFunction.cpp
//Write a program to define the function template for calculating the square of given numbers with different data types. #include<iostream> #include<bits/stdc++.h> using namespace std; template<class S> S square(S val) { return val * val; }; template<> string square(string str) { return str + str; }; int main() { cout<<"\nMade By: Akshay Khare CSE B 54\n"; int num; string st; cout<<"Enter a number: "; cin>>num; cout<<"Enter a string: "; cin>>st; cout<<num<<" ---> "<<square(num)<<endl; cout<<st<<" ---> "<<square(st)<<endl; return 0; }
f0cd3f754b1c8c96908719f76e179b3ac8acdf93
a65b1ba6939f1de6dbf2f39b18762501a0c99a8b
/Symulacja_Cyfrowa/channel.cpp
3372bc75c8d136feffa5cab9c0787536262f0590
[]
no_license
SzPi1946/Symulacja_Cyfrowa
e0da197fd00c14cffd537ca362ed56ae27b0b839
a5033198a4f4f0eff0bc9abaeb4813726673c3ec
refs/heads/master
2021-05-25T08:11:18.095265
2021-02-23T11:51:27
2021-02-23T11:51:27
253,733,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
channel.cpp
#include "channel.h" #include <iostream> #include "logger.h" Channel::Channel(Logger* logger, Wirelessnetwork* network) { network_ = network; status2 = true; status = true; logger_ = logger; logger_->Debug("The channel has been created."); } Channel::~Channel() { logger_->Debug("The channel has been removed."); } bool Channel::return_status() { return status; } void Channel::set_free(Logger* logger) { logger->Debug("Channel status setting free."); status = true; } double Channel::return_ack() { return ctiz_; } int Channel::return_ter() { return network_->ReturnTer(); } void Channel::add_packet(Packet* packet) { packets_.push_back(packet); if (packets_.size() >= 2) { for (int i = 0; i < packets_.size(); i++) { packets_.at(i)->set_collision(logger_); } } } void Channel::delete_packet(int packet_id, int station_id) { for (int i = 0; i < packets_.size(); i++) if (packets_[i]->return_packet_id() == packet_id && packets_[i]->return_tx_id() == station_id) packets_.erase(packets_.begin() + i); } std::vector<Packet*>* Channel::return_packets() { return &packets_; } void Channel::set_status2(bool status) { status2 = status; } bool Channel::return_status2() { return status2; } void Channel::set_busy(Logger* logger) { logger->Debug("Channel status setting busy."); status = false; }
01f042942bf49804deb4caf980a40e1c6f7c5330
07086560eff6d8f04ffdcf317251e212f67bbfa1
/QuiString.h
a15bdcaba371b0ab0e486d8fc4bc89187a2b57c0
[]
no_license
cryos/QUI
41fb40ac20ef4f315bae89de06358cb6e1d36558
4d5b4322bbed155f44ef781939c28ebb64bebebe
refs/heads/master
2021-01-23T15:04:08.855824
2009-04-29T18:06:44
2009-04-29T18:06:44
188,636
1
1
null
null
null
null
UTF-8
C++
false
false
903
h
QuiString.h
#ifndef QUI_QUISTRING_H #define QUI_QUISTRING_H /*! * \file QuiString.h * * \brief In theory this file should isolate the differeneces between using * QStrings in the QUI and std::strings in the code. * * \author Andrew Gilbert * \date October 2008 */ #ifdef QT_CORE_LIB #include <QString> #else #include <string> #include <cctype> #include <algorithm> #endif namespace Qui { #ifdef QT_CORE_LIB typedef QString String; inline String ToUpper(String s) { return s.toUpper(); } inline String ToLower(String s) { return s.toLower(); } #else typedef std::string String; inline String ToUpper(std::string s) { String t; std::transform(s.begin(), s.end(), t.begin(), std::toupper); return t; } inline String ToLower(String s) { String t; std::transform(s.begin(), s.end(), t.begin(), std::tolower); return t; } #endif } // end namespace Qui #endif
b71bc16cbcfb7b2144aade58863e6444b682fa8a
c4270321848d8da394f171e907a9246f9ac48cdf
/2019/poo/interface/enfermeiro.h
a9a618aaef25820e5854c72a71c8725bf83ce772
[]
no_license
marlovi/aulas
99a83d2364a3e5573fd3fb8d58b696fb1d835ae4
a8b22d506105217b196e9354a2b06fdd74758203
refs/heads/master
2023-01-08T03:22:24.067025
2019-11-12T00:23:44
2019-11-12T00:23:44
98,063,832
10
11
null
2023-01-04T12:26:56
2017-07-22T23:41:20
JavaScript
UTF-8
C++
false
false
162
h
enfermeiro.h
#ifndef ENFERMEIRO_H #define ENFERMEIRO_H #include "acoes.h" class Enfermeiro : public Acoes{ public: float receberSalario(); bool baterPonto(); }; #endif
8a07bb5787b24f0b3b48e8d1f95ec8f508a9f28a
fd3f6fabd11cbdf2af9ba5f98a56d7c6f99d28ef
/OnlineJudgeUVa/C++/12xxx/12279 - Emoogle Balance/main.cpp
6120ab9212d1e5219b3c71b172f4777586fb4278
[ "MIT" ]
permissive
DVRodri8/Competitive-programs
07e3ef71cb37b7b4b8cfc35ed9a594276f686b10
db90c63aea8fa4403ae7ec735c7f7ce73c842be4
refs/heads/master
2021-01-19T00:33:37.506503
2017-07-19T17:05:14
2017-07-19T17:05:14
87,185,395
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
main.cpp
#include <iostream> #include <string> using namespace std; int main(){ int n, x, res, c = 1; cin >> n; while(n!=0){ res = 0; for(n; n>0 ; n--){ cin >> x; if(x == 0) res--; else res++; } cout << "Case " << c << ": " << res << endl; c++; cin >> n; } cout << endl; return 0; }
e301ba732363eecea874df39517aa850b56cb40e
86dcea4619590879ad9b1938d80ffe0a035cd041
/NeuroData/reader/AbstractReader.cpp
38d0da36280e2b83489159134850ac241708baa1
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
smmzhang/NeuroStudio
aaa4826ef732963e4f748a46625a468a1ae810d3
f505065d694a8614587e7cc243ede72c141bd80b
refs/heads/master
2022-01-08T23:37:52.361831
2019-01-07T11:29:45
2019-01-07T11:29:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
632
cpp
AbstractReader.cpp
#include "stdafx.h" #include "AbstractReader.h" #include "BinaryReader.h" #include "TextReader.h" using namespace np::dp; using namespace np::dp::preprocessor; AbstractReader* AbstractReader::CreateInstance(DataReaderSet& reader_set, const model::AbstractReaderModel& model) { AbstractReader* reader = NULL; if (model.GetReaderType() == model::_reader_type::binary) reader = new BinaryReader(model); else if (model.GetReaderType() == model::_reader_type::text) reader = new TextReader(model); if (reader == NULL) return NULL; if (!reader->Create(reader_set)) { delete reader; return NULL; } return reader; }
c5db3481cb77d66c2b5e74deadbbcab5f27dc790
f16af0daae3d88df06fe45b57d762fe0ed0da6d6
/INLib/inc/GELib/Ui/UiHitArea.h
b86355b1721ded7480788108c51a3017581fbf1b
[]
no_license
lop-dev/lop-lib
1f15d48beca11dd7e4842b96780adecab186bea5
ae22a29c82e31cbca53155fb0a1155569dfe2681
refs/heads/master
2023-06-23T09:45:43.317656
2021-07-25T02:11:19
2021-07-25T02:11:19
131,691,063
16
13
null
null
null
null
UTF-8
C++
false
false
1,342
h
UiHitArea.h
////////////////////////////////////////////////////////////////////// // created: 2010/06/06 // filename: GELib/Ui/UiHitArea.h // author: League of Perfect /// @brief /// ////////////////////////////////////////////////////////////////////// #ifndef __GELIB_UI_UIHITAREA_H__ #define __GELIB_UI_UIHITAREA_H__ #include <vector> #include <GELib/Math/GeMath.h> #include "UiAlignment.h" namespace GELib { class IPlotter2D; class CIOStream; class CUiHitArea { public: CUiHitArea() {} ~CUiHitArea() {} bool Save(CIOStream &stream); bool Load(CIOStream &stream); bool IsHit(const CVector2 &p, const CVector2 &baseSize, int *hitCode=0); void Draw(const CVector2 &absPos, const CVector2 &baseSize, IPlotter2D &canvas); class Shape { public: Shape(); ~Shape(); bool Save(CIOStream &stream); bool Load(CIOStream &stream); bool IsHit(const CVector2 &p, const CVector2 &baseSize, int *hitCode=0); void Draw(int index, const CVector2 &absPos, const CVector2 &baseSize, IPlotter2D &canvas); void SetPolygon(const CVector2 *v, int sides); int m_iCode; CVector2 m_Position; CVector2 m_Size; std::vector<CVector2> m_Polygon; CUiAlignment m_Alignment; }; std::vector<Shape> m_Shapes; }; }//GELib #endif//__GELIB_UI_UIHITAREA_H__
297e972a258bb143717fba4960fe346ccddaad78
a822c8510279f9a09cf1e81ea1d94fdf1952a24a
/ardumower/imu.cpp
9dcf55fb0bd0eff8048927f93daa65f6211917a7
[]
no_license
Boilevin/AzuritBer
44b9584399d852133dd2b9702e2e55912c4bdd31
19fd14705ba3a814a1cddccf4482dce4f3ffa64a
refs/heads/master
2023-02-22T12:13:16.598315
2023-02-12T18:17:38
2023-02-12T18:17:38
186,164,418
13
17
null
2021-08-30T14:14:19
2019-05-11T17:48:31
C
UTF-8
C++
false
false
22,442
cpp
imu.cpp
/* License Copyright (c) 2013-2017 by Alexander Grau Private-use only! (you need to ask for a commercial-use) The code is open: you can 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. The code 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/>. Private-use only! (you need to ask for a commercial-use) */ #include "imu.h" #include "helper_3dmath.h" #include "MPU6050_6Axis_MotionApps20.h" #include "mower.h" #include "i2c.h" #include "robot.h" #include "flashmem.h" /////////////////////////////////// CONFIGURATION FOR ACCEL GYRO MPU6050 CALIBRATION ///////////////////////////// //Change this 3 variables if you want to fine tune the skecth to your needs. int buffersize = 1000; //Amount of readings used to average, make it higher to get more precision but sketch will be slower (default:1000) int acel_deadzone = 8; //Acelerometer error allowed, make it lower to get more precision, but sketch may not converge (default:8) int giro_deadzone = 1; //Giro error allowed, make it lower to get more precision, but sketch may not converge (default:1) MPU6050 mpu(0x69); boolean blinkState = false; float nextTimeLoop; float nextSendPitchRollError; // MPU control/status vars boolean dmpReady = false; // set true if DMP init was successful uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer //for accelgyro calib int16_t ax, ay, az, gx, gy, gz; int mean_ax, mean_ay, mean_az, mean_gx, mean_gy, mean_gz, state = 0; int ax_offset, ay_offset, az_offset, gx_offset, gy_offset, gz_offset; float yprtest[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector #define ADDR 600 #define MAGIC 6 #define HMC5883L (0x1E) // HMC5883L compass sensor (GY-80 PCB) #define QMC5883L (0x0D) // HMC5883L compass sensor (GY-80 PCB) void IMUClass::begin() { if (!robot.imuUse) return; //initialisation of Compass if (robot.CompassUse) { if (COMPASS_IS == HMC5883L) { Console.println(F("--------------------------------- COMPASS HMC5883L INITIALISATION ---------------")); uint8_t data = 0; //while (true) { I2CreadFrom(HMC5883L, 10, 1, &data, 1); Console.print(F("COMPASS HMC5883L ID NEED TO BE 72 IF ALL IS OK ------> ID=")); Console.println(data); if (data != 72) Console.println(F("COMPASS HMC5883L FAIL")); delay(1000); //} comOfs.x = comOfs.y = comOfs.z = 0; comScale.x = comScale.y = comScale.z = 2; useComCalibration = true; I2CwriteTo(HMC5883L, 0x00, 0x70); // config A: 8 samples averaged, 75Hz frequency, no artificial bias. I2CwriteTo(HMC5883L, 0x01, 0x20); // config B: gain I2CwriteTo(HMC5883L, 0x02, 00); // mode: continuous delay(2000); // wait 2 second before doing the first reading } if (COMPASS_IS == QMC5883L) { Console.println(F("--------------------------------- COMPASS QMC5883L INITIALISATION ---------------")); comOfs.x = comOfs.y = comOfs.z = 0; comScale.x = comScale.y = comScale.z = 2; useComCalibration = true; I2CwriteTo(QMC5883L, 0x0b, 0x01); /* osr512 00 rng 8g 01 odr 100hz 10 mode continous 01 so 00011001 = 0x19 */ I2CwriteTo(QMC5883L, 0x09, 0x19); delay(500); // wait before doing the first reading } } loadCalib(); printCalib(); //initialisation of MPU6050 Console.println(F("--------------------------------- GYRO ACCEL INITIALISATION ---------------")); mpu.initialize(); Console.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed")); Console.println(mpu.getDeviceID()); Console.println(F("Initializing DMP...")); devStatus = mpu.dmpInitialize(); mpu.setXAccelOffset(ax_offset); //-1929 mpu.setYAccelOffset(ay_offset); //471 mpu.setZAccelOffset(az_offset); // 1293 mpu.setXGyroOffset(gx_offset);//-1 mpu.setYGyroOffset(gy_offset);//-3 mpu.setZGyroOffset(gz_offset);//-2 CompassGyroOffset = 0; // make sure it worked (returns 0 if so) if (devStatus == 0) { Console.print(F("Enabling DMP... ")); mpu.setDMPEnabled(true); packetSize = mpu.dmpGetFIFOPacketSize(); Console.print(F("Packet size ")); Console.println(packetSize); } else Console.println(F("DMP Initialization failed ")); nextTimeAdjustYaw = millis(); Console.println(F("Wait 3 secondes to stabilize the Drift")); delay(3000); // wait 3 sec to help DMP stop drift // read the AccelGyro and the CompassHMC5883 to find the initial CompassYaw run(); Console.print(F("AccelGyro Yaw: ")); Console.println(ypr.yaw); if (robot.CompassUse) { Console.print(F(" Compass Yaw: ")); Console.print(comYaw); CompassGyroOffset = distancePI(ypr.yaw, comYaw); Console.print(F(" Diff between compass and accelGyro in Radian and Deg")); Console.print(CompassGyroOffset); Console.print(" / "); Console.println(CompassGyroOffset * 180 / PI); } else { CompassGyroOffset = 0; } } // weight fusion (w=0..1) of two radiant values (a,b) float IMUClass::fusionPI(float w, float a, float b) { float c; if ((b >= PI / 2) && (a <= -PI / 2)) { c = w * a + (1.0 - w) * (b - 2 * PI); } else if ((b <= -PI / 2) && (a >= PI / 2)) { c = w * (a - 2 * PI) + (1.0 - w) * b; } else c = w * a + (1.0 - w) * b; return scalePI(c); } // first-order complementary filter // newAngle = angle measured with atan2 using the accelerometer // newRate = angle measured using the gyro // looptime = loop time in millis() float Complementary2(float newAngle, float newRate, int looptime, float angle) { float k = 10; float dtc2 = float(looptime) / 1000.0; float x1 = (newAngle - angle) * k * k; float y1 = dtc2 * x1 + y1; float x2 = y1 + (newAngle - angle) * 2 * k + newRate; angle = dtc2 * x2 + angle; return angle; } // scale setangle, so that both PI angles have the same sign float scalePIangles(float setAngle, float currAngle) { if ((setAngle >= PI / 2) && (currAngle <= -PI / 2)) return (setAngle - 2 * PI); else if ((setAngle <= -PI / 2) && (currAngle >= PI / 2)) return (setAngle + 2 * PI); else return setAngle; } float IMUClass::distance180(float x, float w) { float d = scale180(w - x); if (d < -180) d = d + 2 * 180; else if (d > 180) d = d - 2 * 180; return d; } //bb float IMUClass::scale180(float v) { float d = v; while (d < 0) d += 2 * 180; while (d >= 2 * 180) d -= 2 * 180; if (d >= 180) return (-2 * 180 + d); else if (d < -180) return (2 * 180 + d); else return d; } float IMUClass::rotate360(float x) { x += 360; if (x >= 360) x -= 360; if (x < 0) x += 360; return x; } void IMUClass::calibration() { ax_offset = -mean_ax / 8; ay_offset = -mean_ay / 8; az_offset = (16384 - mean_az) / 8; gx_offset = -mean_gx / 4; gy_offset = -mean_gy / 4; gz_offset = -mean_gz / 4; while (1) { int ready = 0; mpu.setXAccelOffset(ax_offset); mpu.setYAccelOffset(ay_offset); mpu.setZAccelOffset(az_offset); mpu.setXGyroOffset(gx_offset); mpu.setYGyroOffset(gy_offset); mpu.setZGyroOffset(gz_offset); watchdogReset(); meansensors(); watchdogReset(); Console.print("Wait until accel 3 val are < 8 : "); Console.print(abs(mean_ax)); Console.print(" "); Console.print(abs(mean_ay)); Console.print(" "); Console.print(abs(16384 - mean_az)); Console.print(" and Gyro 3 val are < 1 : "); Console.print(abs(mean_gx)); Console.print(" "); Console.print(abs(mean_gy)); Console.print(" "); Console.print(abs(mean_gz)); Console.println(" "); if (abs(mean_ax) <= acel_deadzone) ready++; else ax_offset = ax_offset - mean_ax / acel_deadzone; if (abs(mean_ay) <= acel_deadzone) ready++; else ay_offset = ay_offset - mean_ay / acel_deadzone; if (abs(16384 - mean_az) <= acel_deadzone) ready++; else az_offset = az_offset + (16384 - mean_az) / acel_deadzone; if (abs(mean_gx) <= giro_deadzone) ready++; else gx_offset = gx_offset - mean_gx / (giro_deadzone + 1); if (abs(mean_gy) <= giro_deadzone) ready++; else gy_offset = gy_offset - mean_gy / (giro_deadzone + 1); if (abs(mean_gz) <= giro_deadzone) ready++; else gz_offset = gz_offset - mean_gz / (giro_deadzone + 1); if (ready == 6) break; } } void IMUClass::meansensors() { long i = 0, buff_ax = 0, buff_ay = 0, buff_az = 0, buff_gx = 0, buff_gy = 0, buff_gz = 0; while (i < (buffersize + 101)) { //default buffersize=1000 // read raw accel/gyro measurements from device mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); watchdogReset(); if (i > 100 && i <= (buffersize + 100)) { //First 100 measures are discarded buff_ax = buff_ax + ax; buff_ay = buff_ay + ay; buff_az = buff_az + az; buff_gx = buff_gx + gx; buff_gy = buff_gy + gy; buff_gz = buff_gz + gz; } if (i == (buffersize + 100)) { mean_ax = buff_ax / buffersize; mean_ay = buff_ay / buffersize; mean_az = buff_az / buffersize; mean_gx = buff_gx / buffersize; mean_gy = buff_gy / buffersize; mean_gz = buff_gz / buffersize; } i++; delay(2); //Needed so we don't get repeated measures } } void IMUClass::run() { if (!robot.imuUse) return; if (devStatus != 0) return; if (state == IMU_CAL_COM) { //don't read the MPU6050 if compass calibration if (COMPASS_IS == HMC5883L) { calibComUpdate(); } if (COMPASS_IS == QMC5883L) { calibComQMC5883Update(); } return; } //-------------------read the mpu6050 DMP into yprtest array-------------------------------- mpu.resetFIFO(); while (fifoCount < packetSize) { //leave time to the DMP to fill the FIFO fifoCount = mpu.getFIFOCount(); } while (fifoCount >= packetSize) { //Immediatly read the fifo and verify that it's not filling during reading mpu.getFIFOBytes(fifoBuffer, packetSize); fifoCount -= packetSize; } if (fifoCount != 0) { //Console.println("//////MPU6050 DMP fill the fifo during the reading IMU value are skip //////////////"); ypr.yaw = scalePI(gyroAccYaw + CompassGyroOffset) ; return; ///the DMP fill the fifo during the reading , all the value are false but without interrupt it's the only way i have find to make it work ???certainly i am wrong } mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(yprtest, &q, &gravity); //bber4 //filter to avoid bad reading, not a low pass one because error are only one on 1000 reading and need fast react on blade safety if (((abs(yprtest[1]) - abs(ypr.pitch)) > 0.3490) && useComCalibration && millis() > nextSendPitchRollError) //check only after startup finish , avoid trouble if iMU not calibrate { nextSendPitchRollError = millis() + 2000; Console.print("Last pitch : "); Console.print(ypr.pitch / PI * 180); Console.print(" Actual pitch : "); Console.println(yprtest[1] / PI * 180); Console.println("pitch change 20 deg in less than 50 ms ????????? value is skip"); } else { ypr.pitch = yprtest[1]; } if (((abs(yprtest[2]) - abs(ypr.roll)) > 0.3490) && useComCalibration && millis() > nextSendPitchRollError) //check only after startup finish , avoid trouble if iMU not calibrate { nextSendPitchRollError = millis() + 2000; Console.print("Last roll : "); Console.print(ypr.roll / PI * 180); Console.print(" Actual roll : "); Console.println(yprtest[2] / PI * 180); Console.println("roll change 20 deg in less than 50 ms ????????? value is skip"); } else { ypr.roll = yprtest[2]; } gyroAccYaw = yprtest[0]; // the Gyro Yaw very accurate but drift if (robot.CompassUse) { // ------------------put the CompassHMC5883 value into comYaw------------------------------------- if (COMPASS_IS == HMC5883L) readHMC5883L(); if (COMPASS_IS == QMC5883L) readQMC5883L(); //tilt compensed yaw ???????????? comTilt.x = com.x * cos(ypr.pitch) + com.z * sin(ypr.pitch); comTilt.y = com.x * sin(ypr.roll) * sin(ypr.pitch) + com.y * cos(ypr.roll) - com.z * sin(ypr.roll) * cos(ypr.pitch); comTilt.z = -com.x * cos(ypr.roll) * sin(ypr.pitch) + com.y * sin(ypr.roll) + com.z * cos(ypr.roll) * cos(ypr.pitch); comYaw = scalePI( atan2(comTilt.y, comTilt.x) ); // the compass yaw not accurate but reliable } // / CompassGyroOffset=distancePI( scalePI(ypr.yaw-CompassGyroOffset), comYaw); ypr.yaw = scalePI(gyroAccYaw + CompassGyroOffset) ; } void IMUClass::readQMC5883L() { uint8_t buf[6]; if (I2CreadFrom(QMC5883L, 0x00, 6, (uint8_t*)buf) != 6) { Console.println("error when read compass"); robot.addErrorCounter(ERR_IMU_COMM); return; } float x = (int16_t) (((uint16_t)buf[1]) << 8 | buf[0]); float y = (int16_t) (((uint16_t)buf[3]) << 8 | buf[2]); float z = (int16_t) (((uint16_t)buf[5]) << 8 | buf[4]); if (useComCalibration) { x -= comOfs.x; y -= comOfs.y; z -= comOfs.z; x /= comScale.x * 0.5; y /= comScale.y * 0.5; z /= comScale.z * 0.5; com.x = x; com.y = y; com.z = z; } else { com.x = x; com.y = y; com.z = z; } } void IMUClass::readHMC5883L() { uint8_t buf[6]; if (I2CreadFrom(HMC5883L, 0x03, 6, (uint8_t*)buf) != 6) { Console.println("error when read compass"); robot.addErrorCounter(ERR_IMU_COMM); return; } // scale +1.3Gauss..-1.3Gauss (*0.00092) float x = (int16_t) (((uint16_t)buf[0]) << 8 | buf[1]); float y = (int16_t) (((uint16_t)buf[4]) << 8 | buf[5]); float z = (int16_t) (((uint16_t)buf[2]) << 8 | buf[3]); if (useComCalibration) { x -= comOfs.x; y -= comOfs.y; z -= comOfs.z; x /= comScale.x * 0.5; y /= comScale.y * 0.5; z /= comScale.z * 0.5; com.x = x; com.y = y; com.z = z; } else { com.x = x; com.y = y; com.z = z; } } void IMUClass::loadSaveCalib(boolean readflag) { int addr = ADDR; short magic = MAGIC; if (readflag) Console.println(F("Load Calibration")); else Console.println(F("Save Calibration")); eereadwrite(readflag, addr, magic); // magic //accelgyro offset eereadwrite(readflag, addr, ax_offset); eereadwrite(readflag, addr, ay_offset); eereadwrite(readflag, addr, az_offset); eereadwrite(readflag, addr, gx_offset); eereadwrite(readflag, addr, gy_offset); eereadwrite(readflag, addr, gz_offset); //compass offset eereadwrite(readflag, addr, comOfs); eereadwrite(readflag, addr, comScale); Console.print(F("Calibration address Start = ")); Console.println(ADDR); Console.print(F("Calibration address Stop = ")); Console.println(addr); } void IMUClass::printPt(point_float_t p) { Console.print(p.x); Console.print(","); Console.print(p.y); Console.print(","); Console.println(p.z); } void IMUClass::printCalib() { Console.println(F("-------- IMU CALIBRATION --------")); Console.print("ACCEL GYRO MPU6050 OFFSET ax: "); Console.print(ax_offset); Console.print(" ay: "); Console.print(ay_offset); Console.print(" az: "); Console.print(az_offset); Console.print(" gx: "); Console.print(gx_offset); Console.print(" gy: "); Console.print(gy_offset); Console.print(" gz: "); Console.println(gz_offset); Console.println("COMPASS OFFSET X.Y.Z AND SCALE X.Y.Z"); Console.print(F("comOfs=")); printPt(comOfs); Console.print(F("comScale=")); printPt(comScale); Console.println(F(".")); } void IMUClass::loadCalib() { short magic = 0; int addr = ADDR; eeread(addr, magic); if (magic != MAGIC) { Console.println(F("IMU error: no calib data")); ax_offset = 376; ay_offset = -1768; az_offset = 1512; gx_offset = 91; gy_offset = 12; gz_offset = -2; comOfs.x = comOfs.y = comOfs.z = 0; comScale.x = comScale.y = comScale.z = 2; useComCalibration = false; return; } calibrationAvail = true; useComCalibration = true; Console.println(F("IMU: found calib data")); loadSaveCalib(true); } void IMUClass::saveCalib() { loadSaveCalib(false); } void IMUClass::deleteCompassCalib() { int addr = ADDR; eewrite(addr, (short)0); // magic comOfs.x = comOfs.y = comOfs.z = 0; comScale.x = comScale.y = comScale.z = 2; Console.println("Compass calibration deleted"); } void IMUClass::deleteAccelGyroCalib() { int addr = ADDR; eewrite(addr, (short)0); // magic ax_offset = ay_offset = az_offset = 0; gx_offset = gy_offset = gz_offset = 0; mpu.setXAccelOffset(1); //-1929 mpu.setYAccelOffset(1); //471 mpu.setZAccelOffset(1); // 1293 mpu.setXGyroOffset(1);//-1 mpu.setYGyroOffset(1);//-3 mpu.setZGyroOffset(1);//-2 Console.println("AccelGyro calibration deleted "); } // calculate gyro offsets void IMUClass::calibGyro() { Console.println("Reading sensors for first time... without any offset"); watchdogReset(); meansensors(); watchdogReset(); Console.print("Reading ax: "); Console.print(mean_ax); Console.print(" ay: "); Console.print(mean_ay); Console.print(" az: "); Console.print(mean_az); Console.print(" gx: "); Console.print(mean_gx); Console.print(" gy: "); Console.print(mean_gy); Console.print(" gz: "); Console.println(mean_gz); Console.println("\nCalculating offsets..."); watchdogReset(); calibration(); watchdogReset(); meansensors(); watchdogReset(); Console.println("FINISHED reading Value with new offset,If all is OK need to be close 0 exept the az close to 16384"); Console.print(" New reading ax: "); Console.print(mean_ax); Console.print(" ay: "); Console.print(mean_ay); Console.print(" az: "); Console.print(mean_az); Console.print(" gx: "); Console.print(mean_gx); Console.print(" gy: "); Console.print(mean_gy); Console.print(" gz: "); Console.println(mean_gz); watchdogReset(); Console.print("THE NEW OFFSET ax: "); Console.print(ax_offset); Console.print(" ay: "); Console.print(ay_offset); Console.print(" az: "); Console.print(az_offset); Console.print(" gx: "); Console.print(gx_offset); Console.print(" gy: "); Console.print(gy_offset); Console.print(" gz: "); Console.println(gz_offset); watchdogReset(); saveCalib(); } void IMUClass::calibComStartStop() { while ((!robot.RaspberryPIUse) && (Console.available())) Console.read(); //use to stop the calib if (state == IMU_CAL_COM) { // stop Console.println(F("com calib completed")); calibrationAvail = true; float xrange = comMax.x - comMin.x; float yrange = comMax.y - comMin.y; float zrange = comMax.z - comMin.z; comOfs.x = xrange / 2 + comMin.x; comOfs.y = yrange / 2 + comMin.y; comOfs.z = zrange / 2 + comMin.z; comScale.x = xrange; comScale.y = yrange; comScale.z = zrange; //bber18 if ((comScale.x == 0) || (comScale.y == 0) || (comScale.z == 0)) { //jussip bug found div by 0 later Console.println(F("*********************ERROR WHEN CALIBRATE : VALUE ARE TOTALY WRONG CHECK IF COMPASS IS NOT PERTURBATE **************")); comOfs.x = comOfs.y = comOfs.z = 0; comScale.x = comScale.y = comScale.z = 2; } saveCalib(); printCalib(); useComCalibration = true; state = IMU_RUN; } else { // start Console.println(F("com calib...")); Console.println(F("rotate sensor 360 degree around all three axis until NO new data are coming")); watchdogReset(); foundNewMinMax = false; useComCalibration = false; state = IMU_CAL_COM; comMin.x = comMin.y = comMin.z = 99999; comMax.x = comMax.y = comMax.z = -99999; } } void IMUClass::calibComQMC5883Update() { comLast = com; delay(20); readQMC5883L(); watchdogReset(); if (com.x < comMin.x) { comMin.x = com.x; Console.print("NEW min x: "); Console.println(comMin.x); } if (com.y < comMin.y) { comMin.y = com.y; Console.print("NEW min y: "); Console.println(comMin.y); } if (com.z < comMin.z) { comMin.z = com.z; Console.print("NEW min z: "); Console.println(comMin.z); } if (com.x > comMax.x) { comMax.x = com.x; Console.print("NEW max x: "); Console.println(comMax.x); } if (com.y > comMax.y) { comMax.y = com.y; Console.print("NEW max y: "); Console.println(comMax.y); } if (com.z > comMax.z) { comMax.z = com.z; Console.print("NEW max z: "); Console.println(comMax.z); } } void IMUClass::calibComUpdate() { comLast = com; delay(20); readHMC5883L(); watchdogReset(); boolean newfound = false; if ( (abs(com.x - comLast.x) < 10) && (abs(com.y - comLast.y) < 10) && (abs(com.z - comLast.z) < 10) ) { if (com.x < comMin.x) { comMin.x = com.x; newfound = true; } if (com.y < comMin.y) { comMin.y = com.y; newfound = true; } if (com.z < comMin.z) { comMin.z = com.z; newfound = true; } if (com.x > comMax.x) { comMax.x = com.x; newfound = true; } if (com.y > comMax.y) { comMax.y = com.y; newfound = true; } if (com.z > comMax.z) { comMax.z = com.z; newfound = true; } if (newfound) { foundNewMinMax = true; watchdogReset(); Console.print("x:"); Console.print(comMin.x); Console.print(","); Console.print(comMax.x); Console.print("\t y:"); Console.print(comMin.y); Console.print(","); Console.print(comMax.y); Console.print("\t z:"); Console.print(comMin.z); Console.print(","); Console.print(comMax.z); Console.println("\t"); } } }
e9d6d582b0bf3cc0fa9828be3d5cd8be396991cd
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/CommonTools/RecoAlgos/plugins/PtMinMuonSelector.cc
3ff63794c7ba849fee47e9c4d5658304167c11fc
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
512
cc
PtMinMuonSelector.cc
/* \class PtMinMuonSelector * * selects muon above a minumum pt cut * * \author: Luca Lista, INFN * */ #include "FWCore/Framework/interface/MakerMacros.h" #include "CommonTools/UtilAlgos/interface/PtMinSelector.h" #include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" typedef SingleObjectSelector<reco::MuonCollection, PtMinSelector> PtMinMuonSelector; DEFINE_FWK_MODULE(PtMinMuonSelector);
592f2153d5a92244a306385bb491ce158f21cd2b
2190702644f7f5e9dc0c8eade40651dfceaed1cc
/src/Window/Application.cpp
a939c047d0c98e20d549ba8df2f5a7d0d8c552fa
[]
no_license
po2xel/abollo
c5b3fca77af05c303b27a5981c28497db99db67c
f7947cf1936bac9d9f80d51afa0668c51b542d1c
refs/heads/master
2022-03-23T20:33:45.843151
2019-11-23T10:16:49
2019-11-23T10:16:49
209,087,473
0
0
null
null
null
null
UTF-8
C++
false
false
2,143
cpp
Application.cpp
#include "Window/Application.h" #include "Window/EventDispatcher.h" namespace abollo { void Application::Run() const { for (SDL_Event lEvent; SDL_WaitEvent(&lEvent) && lEvent.type != SDL_QUIT;) { try { switch (lEvent.type) { case SDL_WINDOWEVENT: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.window.windowID); lEventDispatcher.OnWindowEvent(lEvent.window); break; } case SDL_MOUSEMOTION: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.motion.windowID); lEventDispatcher.OnMouseMotionEvent(lEvent.motion); break; } case SDL_MOUSEBUTTONDOWN: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.button.windowID); lEventDispatcher.OnMouseButtonDownEvent(lEvent.button); break; } case SDL_MOUSEBUTTONUP: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.button.windowID); lEventDispatcher.OnMouseButtonUpEvent(lEvent.button); break; } case SDL_MOUSEWHEEL: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.wheel.windowID); lEventDispatcher.OnMouseWheelEvent(lEvent.wheel); break; } case SDL_KEYDOWN: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.key.windowID); lEventDispatcher.OnKeyDownEvent(lEvent.key); break; } case SDL_KEYUP: { const auto& lEventDispatcher = mEventDispatchers.at(lEvent.key.windowID); lEventDispatcher.OnKeyUpEvent(lEvent.key); break; } default: break; } } catch (const std::out_of_range&) { } } } } // namespace abollo
2e64db62de2c4212485f74ab069546db2ed53f1a
f8d76935f342abceff51a90a2844110ac57a4d2e
/solution/srm334_extendedhappynumbers.cpp
57ff838aee94975412c085f8e669227e872a6d77
[]
no_license
rick-qiu/topcoder
b36cc5bc571f1cbc7be18fdc863a1800deeb5de1
04adddbdc49e35e10090d33618be90fc8d3b8e7d
refs/heads/master
2021-01-01T05:59:41.264459
2014-05-22T06:14:43
2014-05-22T06:14:43
11,315,215
1
0
null
null
null
null
UTF-8
C++
false
false
73,484
cpp
srm334_extendedhappynumbers.cpp
/******************************************************************************* * Automatically generated code for TopCode SRM Problem * Problem URL: http://community.topcoder.com/stat?c=problem_statement&pm=7244 *******************************************************************************/ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class ExtendedHappyNumbers { public: long calcTheSum(int A, int B, int K); }; long ExtendedHappyNumbers::calcTheSum(int A, int B, int K) { long ret; return ret; } int test0() { int A = 13; int B = 13; int K = 2; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1; if(result == expected) { cout << "Test Case 0: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 0: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test1() { int A = 1; int B = 5; int K = 2; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 14; if(result == expected) { cout << "Test Case 1: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 1: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test2() { int A = 10; int B = 99; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 450; if(result == expected) { cout << "Test Case 2: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 2: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test3() { int A = 535; int B = 538; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 820; if(result == expected) { cout << "Test Case 3: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 3: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test4() { int A = 72637; int B = 74236; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 11789917; if(result == expected) { cout << "Test Case 4: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 4: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test5() { int A = 100000; int B = 400000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5169721292; if(result == expected) { cout << "Test Case 5: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 5: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test6() { int A = 1; int B = 1000000; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 4999996; if(result == expected) { cout << "Test Case 6: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 6: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test7() { int A = 1; int B = 1000000; int K = 2; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3449108; if(result == expected) { cout << "Test Case 7: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 7: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test8() { int A = 1; int B = 1000000; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 160104496; if(result == expected) { cout << "Test Case 8: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 8: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test9() { int A = 1; int B = 1000000; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 662296074; if(result == expected) { cout << "Test Case 9: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 9: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test10() { int A = 1; int B = 1000000; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 6399861874; if(result == expected) { cout << "Test Case 10: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 10: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test11() { int A = 1; int B = 1000000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17031865483; if(result == expected) { cout << "Test Case 11: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 11: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test12() { int A = 1; int B = 1; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1; if(result == expected) { cout << "Test Case 12: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 12: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test13() { int A = 2; int B = 2; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2; if(result == expected) { cout << "Test Case 13: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 13: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test14() { int A = 999999; int B = 999999; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5619; if(result == expected) { cout << "Test Case 14: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 14: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test15() { int A = 999999; int B = 999999; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 309; if(result == expected) { cout << "Test Case 15: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 15: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test16() { int A = 568625; int B = 621730; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 978533935; if(result == expected) { cout << "Test Case 16: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 16: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test17() { int A = 670270; int B = 810950; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 95153223; if(result == expected) { cout << "Test Case 17: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 17: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test18() { int A = 854744; int B = 971170; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2194469088; if(result == expected) { cout << "Test Case 18: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 18: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test19() { int A = 476423; int B = 491337; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2515259; if(result == expected) { cout << "Test Case 19: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 19: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test20() { int A = 242739; int B = 840550; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3872455375; if(result == expected) { cout << "Test Case 20: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 20: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test21() { int A = 222558; int B = 543391; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1970098456; if(result == expected) { cout << "Test Case 21: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 21: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test22() { int A = 112843; int B = 445295; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2009503692; if(result == expected) { cout << "Test Case 22: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 22: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test23() { int A = 822402; int B = 909381; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 14099100; if(result == expected) { cout << "Test Case 23: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 23: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test24() { int A = 943019; int B = 986251; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 28690265; if(result == expected) { cout << "Test Case 24: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 24: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test25() { int A = 772328; int B = 982900; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 33823866; if(result == expected) { cout << "Test Case 25: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 25: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test26() { int A = 664486; int B = 775299; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1955466546; if(result == expected) { cout << "Test Case 26: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 26: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test27() { int A = 984799; int B = 994910; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 62963877; if(result == expected) { cout << "Test Case 27: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 27: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test28() { int A = 176725; int B = 731853; int K = 2; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1913156; if(result == expected) { cout << "Test Case 28: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 28: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test29() { int A = 343782; int B = 559543; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3801037388; if(result == expected) { cout << "Test Case 29: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 29: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test30() { int A = 95563; int B = 615898; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 82927342; if(result == expected) { cout << "Test Case 30: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 30: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test31() { int A = 853244; int B = 963813; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17628851; if(result == expected) { cout << "Test Case 31: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 31: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test32() { int A = 786558; int B = 978964; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3672572090; if(result == expected) { cout << "Test Case 32: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 32: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test33() { int A = 233616; int B = 869623; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 11428330857; if(result == expected) { cout << "Test Case 33: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 33: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test34() { int A = 190015; int B = 738105; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3479382561; if(result == expected) { cout << "Test Case 34: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 34: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test35() { int A = 984572; int B = 986912; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1518223; if(result == expected) { cout << "Test Case 35: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 35: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test36() { int A = 95506; int B = 769624; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 107923684; if(result == expected) { cout << "Test Case 36: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 36: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test37() { int A = 854990; int B = 874785; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3197612; if(result == expected) { cout << "Test Case 37: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 37: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test38() { int A = 713111; int B = 916052; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 33160169; if(result == expected) { cout << "Test Case 38: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 38: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test39() { int A = 103454; int B = 105991; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 37842086; if(result == expected) { cout << "Test Case 39: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 39: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test40() { int A = 940911; int B = 962628; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 393226747; if(result == expected) { cout << "Test Case 40: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 40: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test41() { int A = 720841; int B = 726017; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 25884; if(result == expected) { cout << "Test Case 41: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 41: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test42() { int A = 408088; int B = 628656; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1402436454; if(result == expected) { cout << "Test Case 42: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 42: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test43() { int A = 367107; int B = 695991; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1644426; if(result == expected) { cout << "Test Case 43: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 43: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test44() { int A = 239072; int B = 742764; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 80655956; if(result == expected) { cout << "Test Case 44: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 44: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test45() { int A = 232040; int B = 396659; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 25972811; if(result == expected) { cout << "Test Case 45: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 45: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test46() { int A = 441925; int B = 709354; int K = 2; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 923870; if(result == expected) { cout << "Test Case 46: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 46: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test47() { int A = 288411; int B = 590095; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1894517320; if(result == expected) { cout << "Test Case 47: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 47: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test48() { int A = 835746; int B = 837884; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1331533; if(result == expected) { cout << "Test Case 48: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 48: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test49() { int A = 190918; int B = 261935; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 10742235; if(result == expected) { cout << "Test Case 49: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 49: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test50() { int A = 436115; int B = 500637; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 322610; if(result == expected) { cout << "Test Case 50: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 50: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test51() { int A = 314423; int B = 520705; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 33337440; if(result == expected) { cout << "Test Case 51: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 51: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test52() { int A = 110706; int B = 532823; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 67225380; if(result == expected) { cout << "Test Case 52: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 52: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test53() { int A = 50425; int B = 647687; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 95469633; if(result == expected) { cout << "Test Case 53: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 53: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test54() { int A = 381832; int B = 496887; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2029335895; if(result == expected) { cout << "Test Case 54: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 54: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test55() { int A = 818648; int B = 983398; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 823752; if(result == expected) { cout << "Test Case 55: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 55: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test56() { int A = 811629; int B = 876592; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 449437168; if(result == expected) { cout << "Test Case 56: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 56: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test57() { int A = 402757; int B = 950032; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 367974407; if(result == expected) { cout << "Test Case 57: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 57: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test58() { int A = 577260; int B = 665132; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1609236767; if(result == expected) { cout << "Test Case 58: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 58: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test59() { int A = 753721; int B = 836741; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1553958826; if(result == expected) { cout << "Test Case 59: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 59: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test60() { int A = 125945; int B = 817759; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 4422341415; if(result == expected) { cout << "Test Case 60: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 60: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test61() { int A = 588950; int B = 787112; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 134018239; if(result == expected) { cout << "Test Case 61: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 61: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test62() { int A = 740923; int B = 940171; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3728420695; if(result == expected) { cout << "Test Case 62: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 62: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test63() { int A = 518554; int B = 753707; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 4143643049; if(result == expected) { cout << "Test Case 63: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 63: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test64() { int A = 896686; int B = 958314; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 40923299; if(result == expected) { cout << "Test Case 64: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 64: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test65() { int A = 905439; int B = 909645; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2756821; if(result == expected) { cout << "Test Case 65: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 65: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test66() { int A = 106031; int B = 133842; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17282141; if(result == expected) { cout << "Test Case 66: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 66: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test67() { int A = 197709; int B = 270506; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 10926867; if(result == expected) { cout << "Test Case 67: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 67: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test68() { int A = 757551; int B = 982135; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 36135598; if(result == expected) { cout << "Test Case 68: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 68: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test69() { int A = 6033; int B = 895106; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 590240188; if(result == expected) { cout << "Test Case 69: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 69: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test70() { int A = 743729; int B = 761411; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 12385279; if(result == expected) { cout << "Test Case 70: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 70: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test71() { int A = 640808; int B = 932547; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2005740356; if(result == expected) { cout << "Test Case 71: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 71: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test72() { int A = 338590; int B = 959556; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 4123964502; if(result == expected) { cout << "Test Case 72: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 72: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test73() { int A = 438681; int B = 488244; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 833657679; if(result == expected) { cout << "Test Case 73: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 73: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test74() { int A = 624270; int B = 902896; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 186194394; if(result == expected) { cout << "Test Case 74: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 74: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test75() { int A = 50932; int B = 291683; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3774424464; if(result == expected) { cout << "Test Case 75: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 75: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test76() { int A = 57390; int B = 86673; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 413438186; if(result == expected) { cout << "Test Case 76: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 76: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test77() { int A = 764470; int B = 968857; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1408164454; if(result == expected) { cout << "Test Case 77: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 77: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test78() { int A = 133902; int B = 648198; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 8967071180; if(result == expected) { cout << "Test Case 78: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 78: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test79() { int A = 668710; int B = 768987; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 67997327; if(result == expected) { cout << "Test Case 79: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 79: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test80() { int A = 233089; int B = 880967; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 104160405; if(result == expected) { cout << "Test Case 80: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 80: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test81() { int A = 376023; int B = 799495; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 68335942; if(result == expected) { cout << "Test Case 81: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 81: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test82() { int A = 914477; int B = 921696; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 53547104; if(result == expected) { cout << "Test Case 82: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 82: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test83() { int A = 507348; int B = 831313; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5761884357; if(result == expected) { cout << "Test Case 83: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 83: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test84() { int A = 425434; int B = 817104; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2595407649; if(result == expected) { cout << "Test Case 84: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 84: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test85() { int A = 656264; int B = 978002; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 214593087; if(result == expected) { cout << "Test Case 85: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 85: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test86() { int A = 809028; int B = 970012; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1103920660; if(result == expected) { cout << "Test Case 86: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 86: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test87() { int A = 570006; int B = 653284; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1530539059; if(result == expected) { cout << "Test Case 87: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 87: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test88() { int A = 93836; int B = 389691; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 191564227; if(result == expected) { cout << "Test Case 88: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 88: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test89() { int A = 137067; int B = 282771; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 23019783; if(result == expected) { cout << "Test Case 89: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 89: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test90() { int A = 408112; int B = 998188; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3928835167; if(result == expected) { cout << "Test Case 90: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 90: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test91() { int A = 671649; int B = 713051; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 786593034; if(result == expected) { cout << "Test Case 91: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 91: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test92() { int A = 142632; int B = 998611; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5561378008; if(result == expected) { cout << "Test Case 92: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 92: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test93() { int A = 831133; int B = 987534; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 2976784946; if(result == expected) { cout << "Test Case 93: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 93: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test94() { int A = 222714; int B = 240056; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 90342843; if(result == expected) { cout << "Test Case 94: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 94: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test95() { int A = 590077; int B = 923592; int K = 3; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 54316662; if(result == expected) { cout << "Test Case 95: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 95: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test96() { int A = 25678; int B = 25678; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5619; if(result == expected) { cout << "Test Case 96: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 96: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test97() { int A = 117888; int B = 117888; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 309; if(result == expected) { cout << "Test Case 97: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 97: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test98() { int A = 234556; int B = 234556; int K = 4; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 99; if(result == expected) { cout << "Test Case 98: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 98: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test99() { int A = 3; int B = 3; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 3; if(result == expected) { cout << "Test Case 99: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 99: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test100() { int A = 7; int B = 7; int K = 5; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 7; if(result == expected) { cout << "Test Case 100: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 100: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test101() { int A = 100000; int B = 400000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5169721292; if(result == expected) { cout << "Test Case 101: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 101: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test102() { int A = 1; int B = 1000000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17031865483; if(result == expected) { cout << "Test Case 102: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 102: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test103() { int A = 1234; int B = 926134; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 15675272554; if(result == expected) { cout << "Test Case 103: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 103: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test104() { int A = 1; int B = 999999; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17031865482; if(result == expected) { cout << "Test Case 104: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 104: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test105() { int A = 999999; int B = 999999; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 5619; if(result == expected) { cout << "Test Case 105: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 105: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test106() { int A = 1000000; int B = 1000000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1; if(result == expected) { cout << "Test Case 106: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 106: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test107() { int A = 10; int B = 99; int K = 1; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 450; if(result == expected) { cout << "Test Case 107: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 107: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test108() { int A = 1; int B = 998765; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 17014040712; if(result == expected) { cout << "Test Case 108: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 108: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int test109() { int A = 1; int B = 100000; int K = 6; ExtendedHappyNumbers* pObj = new ExtendedHappyNumbers(); clock_t start = clock(); long result = pObj->calcTheSum(A, B, K); clock_t end = clock(); delete pObj; long expected = 1120996038; if(result == expected) { cout << "Test Case 109: Passed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 0; } else { cout << "Test Case 109: Failed! Time: " << static_cast<double>(end-start)/CLOCKS_PER_SEC << " seconds" << endl; return 1; } } int main(int argc, char* argv[]) { int passed = 0; int failed = 0; test0() == 0 ? ++passed : ++failed; test1() == 0 ? ++passed : ++failed; test2() == 0 ? ++passed : ++failed; test3() == 0 ? ++passed : ++failed; test4() == 0 ? ++passed : ++failed; test5() == 0 ? ++passed : ++failed; test6() == 0 ? ++passed : ++failed; test7() == 0 ? ++passed : ++failed; test8() == 0 ? ++passed : ++failed; test9() == 0 ? ++passed : ++failed; test10() == 0 ? ++passed : ++failed; test11() == 0 ? ++passed : ++failed; test12() == 0 ? ++passed : ++failed; test13() == 0 ? ++passed : ++failed; test14() == 0 ? ++passed : ++failed; test15() == 0 ? ++passed : ++failed; test16() == 0 ? ++passed : ++failed; test17() == 0 ? ++passed : ++failed; test18() == 0 ? ++passed : ++failed; test19() == 0 ? ++passed : ++failed; test20() == 0 ? ++passed : ++failed; test21() == 0 ? ++passed : ++failed; test22() == 0 ? ++passed : ++failed; test23() == 0 ? ++passed : ++failed; test24() == 0 ? ++passed : ++failed; test25() == 0 ? ++passed : ++failed; test26() == 0 ? ++passed : ++failed; test27() == 0 ? ++passed : ++failed; test28() == 0 ? ++passed : ++failed; test29() == 0 ? ++passed : ++failed; test30() == 0 ? ++passed : ++failed; test31() == 0 ? ++passed : ++failed; test32() == 0 ? ++passed : ++failed; test33() == 0 ? ++passed : ++failed; test34() == 0 ? ++passed : ++failed; test35() == 0 ? ++passed : ++failed; test36() == 0 ? ++passed : ++failed; test37() == 0 ? ++passed : ++failed; test38() == 0 ? ++passed : ++failed; test39() == 0 ? ++passed : ++failed; test40() == 0 ? ++passed : ++failed; test41() == 0 ? ++passed : ++failed; test42() == 0 ? ++passed : ++failed; test43() == 0 ? ++passed : ++failed; test44() == 0 ? ++passed : ++failed; test45() == 0 ? ++passed : ++failed; test46() == 0 ? ++passed : ++failed; test47() == 0 ? ++passed : ++failed; test48() == 0 ? ++passed : ++failed; test49() == 0 ? ++passed : ++failed; test50() == 0 ? ++passed : ++failed; test51() == 0 ? ++passed : ++failed; test52() == 0 ? ++passed : ++failed; test53() == 0 ? ++passed : ++failed; test54() == 0 ? ++passed : ++failed; test55() == 0 ? ++passed : ++failed; test56() == 0 ? ++passed : ++failed; test57() == 0 ? ++passed : ++failed; test58() == 0 ? ++passed : ++failed; test59() == 0 ? ++passed : ++failed; test60() == 0 ? ++passed : ++failed; test61() == 0 ? ++passed : ++failed; test62() == 0 ? ++passed : ++failed; test63() == 0 ? ++passed : ++failed; test64() == 0 ? ++passed : ++failed; test65() == 0 ? ++passed : ++failed; test66() == 0 ? ++passed : ++failed; test67() == 0 ? ++passed : ++failed; test68() == 0 ? ++passed : ++failed; test69() == 0 ? ++passed : ++failed; test70() == 0 ? ++passed : ++failed; test71() == 0 ? ++passed : ++failed; test72() == 0 ? ++passed : ++failed; test73() == 0 ? ++passed : ++failed; test74() == 0 ? ++passed : ++failed; test75() == 0 ? ++passed : ++failed; test76() == 0 ? ++passed : ++failed; test77() == 0 ? ++passed : ++failed; test78() == 0 ? ++passed : ++failed; test79() == 0 ? ++passed : ++failed; test80() == 0 ? ++passed : ++failed; test81() == 0 ? ++passed : ++failed; test82() == 0 ? ++passed : ++failed; test83() == 0 ? ++passed : ++failed; test84() == 0 ? ++passed : ++failed; test85() == 0 ? ++passed : ++failed; test86() == 0 ? ++passed : ++failed; test87() == 0 ? ++passed : ++failed; test88() == 0 ? ++passed : ++failed; test89() == 0 ? ++passed : ++failed; test90() == 0 ? ++passed : ++failed; test91() == 0 ? ++passed : ++failed; test92() == 0 ? ++passed : ++failed; test93() == 0 ? ++passed : ++failed; test94() == 0 ? ++passed : ++failed; test95() == 0 ? ++passed : ++failed; test96() == 0 ? ++passed : ++failed; test97() == 0 ? ++passed : ++failed; test98() == 0 ? ++passed : ++failed; test99() == 0 ? ++passed : ++failed; test100() == 0 ? ++passed : ++failed; test101() == 0 ? ++passed : ++failed; test102() == 0 ? ++passed : ++failed; test103() == 0 ? ++passed : ++failed; test104() == 0 ? ++passed : ++failed; test105() == 0 ? ++passed : ++failed; test106() == 0 ? ++passed : ++failed; test107() == 0 ? ++passed : ++failed; test108() == 0 ? ++passed : ++failed; test109() == 0 ? ++passed : ++failed; cout << "Total Test Case: " << passed + failed << "; Passed: " << passed << "; Failed: " << failed << endl; return failed == 0 ? 0 : 1; } /******************************************************************************* * Top Submission URL: * http://community.topcoder.com/stat?c=problem_solution&cr=144400&rd=10658&pm=7244 ******************************************************************************** #include <algorithm> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <iostream> #include <sstream> #include <string> #include <utility> #include <vector> using namespace std; #define REP(i,n) for(int _n=n, i=0;i<_n;++i) #define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;++i) #define MAX(f,w) ({ int _mm=(1<<31); f _mm>?=(w); _mm; }) typedef long long LL; const int MAX = 4000000; int POW[10]; int cache[MAX]; int f(int x) { int res = 0; while(x) { res += POW[x%10]; x/=10; } return res; } int happy(int x) { if(cache[x]>=0) return cache[x]; if(cache[x]==-2) { int y = x; int m = x; do { y = f(y); m = min(m,y); } while(y!=x); cache[x]=m; return m; } cache[x]=-2; int y = f(x); int mm = happy(y); mm = min(mm, x); cache[x]=mm; return mm; } struct ExtendedHappyNumbers { long long calcTheSum(int A, int B, int K) { REP(i,10) POW[i]=int(pow(double(i),double(K))); memset(cache,-1,sizeof(cache)); LL res = 0; FOR(i,A,B) res += happy(i); return res; } }; // Powered by FileEdit // Powered by TomekAI // Powered by TZTester 1.01 [25-Feb-2003] // Powered by CodeProcessor ******************************************************************************** *******************************************************************************/
44822afcbd8c348ce1668475819e5151517e37b5
3e03bd443c3b0d26bd0dcaa4de677c7ceb975a71
/Valid Parentheses.cpp
f81999075cb961d3de7362a98c544d9d6b966723
[]
no_license
moophis/leetcode_solutions
00fa2062657fdaee586b1b6e8d57da56b2ad7a17
da99a4e512afc3c452dff29a89da7ec905f7add5
refs/heads/master
2020-05-02T12:08:19.144092
2014-10-20T03:23:52
2014-10-20T03:23:52
13,548,528
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
cpp
Valid Parentheses.cpp
// https://oj.leetcode.com/problems/valid-parentheses/ class Solution { public: bool isValid(string s) { size_t size = s.size(); if (size == 0) { return true; } stack<char> stk; for (size_t i = 0; i < size; i++) { char c = s[i]; switch (c) { case '(': case '{': case '[': stk.push(c); break; case ')': { if (stk.size() == 0 || stk.top() != '(') { return false; } stk.pop(); break; } case '}': { if (stk.size() == 0 || stk.top() != '{') { return false; } stk.pop(); break; } case ']': { if (stk.size() == 0 || stk.top() != '[') { return false; } stk.pop(); break; } default: return false; } } return stk.size() == 0; } };
78b56014b7450d6bafafa8eccaab3317bd234a0c
03eb29c69423912741f7cf96a9403aa2cfba723e
/src/cml/Renderer.cpp
eb7e37402d46790fef48343ae72f915e812525e9
[]
no_license
angeelgarr/ofxCamaraLucida
e9ab5b6130714cd00d1964964f96ca235717720e
435fa8f6da0e7eb554ecf3c47f62d1fb2291af40
refs/heads/master
2021-09-03T01:14:42.776974
2018-01-04T14:02:40
2018-01-04T14:02:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,909
cpp
Renderer.cpp
#include "cml/Renderer.h" namespace cml { Renderer::Renderer( cml::Config config, OpticalDevice* proj, OpticalDevice* depth ) //OpticalDevice* rgb ) { this->proj = proj; this->depth = depth; //this->rgb = rgb; _debug = false; _viewpoint = V_DEPTH; ofFbo::Settings s; s.width = config.tex_width; s.height = config.tex_height; s.numSamples = config.tex_nsamples; s.numColorbuffers = 1; s.internalformat = GL_RGBA; fbo.allocate(s); //shader.load("camara_lucida/glsl/render"); render_shader.init( shader ); init_gl_scene_control(); } Renderer::~Renderer() { dispose(); } void Renderer::dispose() { proj = NULL; depth = NULL; //rgb = NULL; } void Renderer::render( cml::Events *ev, Mesh *mesh, ofTexture& depth_ftex, bool gpu, bool wireframe ) { // texture fbo.bind(); //ofEnableAlphaBlending(); float w = fbo.getWidth(); float h = fbo.getHeight(); ofClear(0,1); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, 0, h, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,1,1); ofNotifyEvent( ev->render_texture, ev->void_args ); fbo.unbind(); //ofDisableAlphaBlending(); // gl init ofClear(0,1); // 3d ofEnableDepthTest(); glPushAttrib( GL_POLYGON_BIT ); if ( wireframe ) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); else { glCullFace( GL_FRONT ); glEnable( GL_CULL_FACE ); glPolygonMode( GL_FRONT, GL_FILL ); } ofPushStyle(); ofSetColor( ofColor::white ); ofViewport(); //gl_ortho(); gl_projection(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glScalef( 1., -1., -1. ); if ( _debug ) { glPushMatrix(); gl_scene_control(); render_depth_CS(); render_proj_CS(); //render_rgb_CS(); //ofDrawGrid( 3000.0f, 8.0f, false, false, true, false ); glPopMatrix(); } glPushMatrix(); gl_viewpoint(); gl_scene_control(); //ofEnableAlphaBlending(); ofTexture& render_tex = fbo.getTextureReference(0); if ( gpu ) { shader.begin(); render_tex.bind(); render_shader.update(shader, ((cml::DepthCamera*)depth), render_tex, depth_ftex); mesh->render(); render_tex.unbind(); shader.end(); } else { render_tex.bind(); mesh->render(); render_tex.unbind(); } glPopMatrix(); //ofDisableAlphaBlending(); //FIXME ofNotifyEvent( ev->render_3d, ev->void_args ); glPopMatrix(); // 2d hud glPopAttrib();//GL_POLYGON_BIT glDisable( GL_CULL_FACE ); glPolygonMode( GL_FRONT, GL_FILL ); ofDisableDepthTest(); ofSetColor( ofColor::white ); gl_ortho(); ofNotifyEvent( ev->render_2d, ev->void_args ); ofPopStyle(); } // gl void Renderer::gl_ortho() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( 0, ofGetWidth(), ofGetHeight(), 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void Renderer::gl_projection() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); OpticalDevice::Frustum& frustum = device()->gl_frustum(); glFrustum( frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far ); //glMultMatrixf( device()->gl_projection_matrix() ); } void Renderer::gl_viewpoint() { glMultMatrixf( device()->gl_modelview_matrix() ); //OpticalDevice* dev = device(); //ofVec3f& loc = dev->loc(); //ofVec3f& trg = dev->trg(); //ofVec3f& up = dev->up(); //gluLookAt( //loc.x, loc.y, loc.z, //trg.x, trg.y, trg.z, //up.x, up.y, up.z //); } // scene control void Renderer::gl_scene_control() { //float *RT=proj->gl_modelview_matrix(); //float *RT=depth->gl_modelview_matrix(); float *RT = device()->gl_modelview_matrix(); rot_pivot = ofVec3f( RT[12], RT[13], RT[14] ); glTranslatef( 0, 0, tZ ); glTranslatef( rot_pivot.x, rot_pivot.y, rot_pivot.z ); glRotatef( rotX, 1, 0, 0); glRotatef( rotY, 0, 1, 0); glRotatef( rotZ, 0, 0, 1); glTranslatef( -rot_pivot.x, -rot_pivot.y, -rot_pivot.z ); } void Renderer::init_gl_scene_control() { pmouse = ofVec2f(); tZ_delta = -50.; //mm units rot_delta = -0.2; tZini = 0; rotXini = 0; rotYini = 0; rotZini = 0; reset_scene(); } void Renderer::reset_scene() { tZ = tZini; rotX = rotXini; rotY = rotYini; rotZ = rotZini; } void Renderer::next_view() { ++_viewpoint; _viewpoint = _viewpoint == V_LENGTH ? 0 : _viewpoint; } void Renderer::prev_view() { --_viewpoint; _viewpoint = _viewpoint == -1 ? V_LENGTH-1 : _viewpoint; } void Renderer::render_depth_CS() { glPushMatrix(); glMultMatrixf( depth->gl_modelview_matrix() ); ofPushStyle(); ofSetColor( ofColor::magenta ); ofSetLineWidth(1); render_frustum(depth->gl_frustum()); render_axis(50); ofPopStyle(); glPopMatrix(); } void Renderer::render_proj_CS() { glPushMatrix(); glMultMatrixf( proj->gl_modelview_matrix() ); //glScalef( 1., -1., 1. ); //glRotatef( 180, 0, 0, 1); ofPushStyle(); ofSetLineWidth(1); ofSetColor( ofColor::yellow ); render_frustum(proj->gl_frustum()); render_axis(50); //ppal point //float len = 100; //ofSetColor( ofColor::yellow ); //ofLine( 0,0,0, 0,0, len ); //glBegin(GL_POINTS); //glVertex3f(0, 0, len); //glEnd(); ofPopStyle(); glPopMatrix(); } //void Renderer::render_rgb_CS() //{ //glPushMatrix(); //glMultMatrixf(rgb->gl_modelview_matrix()); //render_axis(50); //glPopMatrix(); //} //see of3dUtils#ofDrawAxis void Renderer::render_axis(float size) { ofPushStyle(); ofSetLineWidth(2); // draw x axis ofSetColor(ofColor::red); ofLine(0, 0, 0, size, 0, 0); // draw y axis ofSetColor(ofColor::green); ofLine(0, 0, 0, 0, size, 0); // draw z axis ofSetColor(ofColor::blue); ofLine(0, 0, 0, 0, 0, size); ofPopStyle(); } void Renderer::render_frustum( OpticalDevice::Frustum& F ) { float plane = F.near; //pyramid ofLine( 0,0,0, F.left, F.top, plane ); ofLine( 0,0,0, F.right, F.top, plane ); ofLine( 0,0,0, F.left, F.bottom, plane ); ofLine( 0,0,0, F.right, F.bottom, plane ); //plane ofLine( F.left, F.bottom, plane, F.left, F.top, plane ); ofLine( F.left, F.top, plane, F.right, F.top, plane ); ofLine( F.right, F.top, plane, F.right, F.bottom, plane ); ofLine( F.right, F.bottom, plane, F.left, F.bottom, plane ); }; string Renderer::get_viewpoint_info() { switch( _viewpoint ) { case V_PROJ: return "projector viewpoint"; break; case V_DEPTH: return "depth camera viewpoint"; break; //case V_RGB: //return "rgb camera viewpoint"; //break; //case V_WORLD: //return "world viewpoint"; //break; default: return "no viewpoint selected"; } } // ui void Renderer::mouseDragged(int x, int y, bool zoom) { if ( ! _debug) return; ofVec2f m = ofVec2f( x, y ); ofVec2f dist = m - pmouse; if ( zoom ) { tZ += -dist.y * tZ_delta; } else { rotX -= dist.y * rot_delta; rotY += dist.x * rot_delta; } pmouse.set( x, y ); } void Renderer::mousePressed(int x, int y) { pmouse.set( x, y ); } };
a78015bd5b77f25d961cced2ea393ebbe037b8e5
1a0bbe995438570ac8a2947e5ae7f7289428b335
/include/merge_sort.h
43001edec689791e1cc3e92aea09332fbd87056c
[ "MIT" ]
permissive
Algorithms-and-Data-Structures-2021/semester-work-merge-and-insertion-sort-DL
227f833b04aa8e71f1e07d18d9478cbaea4141b6
2d6e5fe89eeab5a2897183b27358a23dff23b2d1
refs/heads/main
2023-04-25T11:37:18.163155
2021-05-24T16:20:54
2021-05-24T16:20:54
369,618,926
0
0
null
null
null
null
UTF-8
C++
false
false
235
h
merge_sort.h
#pragma once #include <vector> using namespace std; namespace itis { int min(int x, int y); void merge(std::vector<int> arr, int start, int mid, int end); void merge_sort(std::vector<int> arr, int l, int r); } // namespace itis
f3e457e67dfe317756115fc1ed3dc46b4452b92a
097f23019557d17ca70e75222d54b26ca322c50d
/compte.cpp
43ecf246f800f79ba9b63bc147faf38811bcd56a
[]
no_license
patrick-lainesse/Comptes-bancaires
075524403c721ca626e8f9c807ed829787119e5e
a1e0cfb6cb01fd6334ed222b0b3837f9ac87fa84
refs/heads/master
2021-02-11T18:01:55.585505
2020-03-03T16:48:03
2020-03-03T16:48:03
244,517,460
1
0
null
null
null
null
ISO-8859-1
C++
false
false
12,431
cpp
compte.cpp
/* * Auteur: Patrick Lainesse * Cours: IFT1166 - A19 - Mardi 16h30 * * compte.cpp * Classes et methodes implementant une classe abstraite pour gerer * des operations bancaires. */ #include "compte.h" // On declare globalement l'iteration des numeros de comptes pour qu'ils soient modifies a l'exterieur des classes // afin d'eviter d'attribuer le meme numero a deux comptes differents. On debute a 1001 pour faire plus serieux. // J'ai d'abord essaye avec le mot-cle "static" a l'interieur de comptBanq, tel que suggére, par Audrey, mais cela // n'accomplissait pas l'effet désire (tous les comptes se retrouvaient alors avec le meme numero), et il fallait tout // de même initialiser globalement pour que cela fonctionne, donc c'est la solution que j'ai privilégiee. int iteration = 1001; comptBanq::comptBanq() { numero = iteration; iteration++; } comptBanq::comptBanq(double montant):solde(montant) { numero = iteration; iteration++; } int comptBanq::getNumero() const { return numero; } double comptBanq::getSolde() const { return solde; } void comptBanq::depot(double montant) { solde += montant; } void comptBanq::retrait(double montant) { double test = 0; test = solde - montant; if(test < 0) { cout << "\nCher client, votre compte #" << getNumero() << " n'a pas suffisamment de fonds. Impossible d'effectuer un retrait. " << "Allez directement en prison et si vous passez Go, NE RECLAMEZ PAS 200$.\n"; } else solde -= montant; return; } comptCheq::comptCheq(double montant) : comptBanq(montant) { fraisService(); // eh oui, nos radins de patrons chargent des frais meme a l'ouverture des comptes } comptCheq::comptCheq(double montant, double minimum): comptBanq(montant), soldeMinimum(minimum) { fraisService(); } comptCheq::comptCheq() : comptBanq() {} // constructeur avec valeurs par defaut void comptCheq::setSoldeMinimum(double minimum) { soldeMinimum = minimum; fraisService(); } double comptCheq::getSoldeMinimum() const { return soldeMinimum; } /* Il me semble necessaire de definir une methode pour les frais de service a appliquer a chaque transaction dans le cas ou le client a un solde inferieur au solde minimum */ void comptCheq::fraisService() { if (getSolde() - soldeMinimum <= 0) { cout << "Cher client, votre compte #" << getNumero() << " contient moins que le solde minimum prevu a votre contrat. " << "Des frais de 50 sous ont ete debites a votre compte pour cette transaction. Veuillez agreer de nos sentiments les plus distingues.\n"; comptBanq::retrait(0.50); // utilise le retrait de la classe mere pour eviter une boulce infinie avec le retrait de comptCheq } } double comptCheq::fraisMensuels() const // ces frais seront appliques a toute transaction autre que les interrogations de compte { if (getSolde() - getSoldeMinimum() <= 0) return (getSoldeMinimum() - getSolde()) * 0.0025; else return 0; // si le compte a un solde superieur au minimum, pas de frais } void comptCheq::retrait(double montant) { fraisService(); comptBanq::retrait(montant); } void comptCheq::depot(double montant) { fraisService(); comptBanq::depot(montant); } void comptCheq::afficher() const { cout << "Compte cheque #" << comptBanq::getNumero() << ":\n"; cout << "Solde: " << getSolde() << "$\n"; cout << "Solde minimum a respecter: " << getSoldeMinimum() << "$\n"; cout << "Frais mensuels: " << fraisMensuels() << "$\n"; cout << "Frais de service: 0.50$\n"; } comptEpargn::comptEpargn(): comptBanq() {} comptEpargn::comptEpargn(double montant, double tauxInteret): comptBanq(montant) { taux = tauxInteret; } comptEpargn::comptEpargn(double montant): comptBanq(montant) {} void comptEpargn::setTaux(double tauxInteret) { taux = tauxInteret; } double comptEpargn::getTaux() const { return taux; } void comptEpargn::afficher() const { cout << "Compte epargne #" << comptBanq::getNumero() << ":\n"; cout << "Solde: " << getSolde() << "$\n"; cout << "Taux d'interet: " << getTaux() * 100 << "%\n"; cout << "A la fin du mois, vous recolterez " << getSolde() * taux / 12 << "$\n"; } /* int main() { comptEpargn test1; comptCheq test2(300); comptCheq test3(3); comptCheq test4(200.672, 850); comptEpargn test5(2000); cout << fixed << setprecision(2); // montants s'affichent avec format usuel pour l'argent test1.afficher(); //cout << test1.getTaux() << endl << endl; test2.afficher(); //cout << test2.getSoldeMinimum() << endl << endl; test3.afficher(); //cout << test3.getSoldeMinimum() << endl << endl; test4.afficher(); //cout << test4.getSoldeMinimum(); //cout << "\n"; cout << "getSolde test3: " << test3.getSolde() << endl; test3.retrait(35); cout << "getSolde test3 apres retrait: " << test3.getSolde() << endl; cout << "frais mensuels test2: " << test2.fraisMensuels() << endl; cout << "frais mensuels test3: " << test3.fraisMensuels() << endl; cout << "frais mensuels test4: " << test4.fraisMensuels() << endl; test5.afficher(); }*/ /* EXECUTION Cher client, votre compte #1001 contient moins que le solde minimum prevu a votre contrat. Des frais de 50 sous ont ete debites a votre compte pour cette transaction. Veuillez agreer de nos sentiments les plus distingues. Affichage des comptes a l'initialisation: ====================================================== Bienvenue chez Despotagers. Bunton, Emma Client #162018 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1001: Solde: 99.50$ Solde minimum a respecter: 1000.00$ Frais mensuels: 2.25$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1002: Solde: 0.00$ Taux d'interet: 1.50% A la fin du mois, vous recolterez 0.00$ ------------------------------------------------------ ====================================================== ====================================================== Bienvenue chez Despotagers. B, Mel Client #162019 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1003: Solde: 5.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 2.49$ Frais de service: 0.50$ ------------------------------------------------------ ====================================================== ====================================================== Bienvenue chez Despotagers. Chisholm, Melanie Client #162020 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1004: Solde: 2500.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1005: Solde: 4000.00$ Taux d'interet: 2.20% A la fin du mois, vous recolterez 7.33$ ------------------------------------------------------ ====================================================== ====================================================== Bienvenue chez Despotagers. Halliwell, Geri Client #162021 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1006: Solde: 300000.00$ Solde minimum a respecter: 12000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1007: Solde: 700000.00$ Taux d'interet: 0.20% A la fin du mois, vous recolterez 116.67$ ------------------------------------------------------ ====================================================== ====================================================== Bienvenue chez Despotagers. Beckham, Victoria Client #162022 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1008: Solde: 1000000.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte cheque #1009: Solde: 500000.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte cheque #1010: Solde: 6400000.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1011: Solde: 48000000.00$ Taux d'interet: 1.50% A la fin du mois, vous recolterez 60000.00$ ------------------------------------------------------ Compte epargne #1012: Solde: 34000000.00$ Taux d'interet: 1.50% A la fin du mois, vous recolterez 42500.00$ ------------------------------------------------------ ====================================================== Emma garde les enfants de Victoria et se fait payer 20$ pour la soiree. Cher client, votre compte #1001 contient moins que le solde minimum prevu a votre contrat. Des frais de 50 sous ont ete debites a votre compte pour cette transaction. Veuillez agreer de nos sentiments les plus distingues. Victoria est recompensee pour ce genereux salaire et se voit offrir un taux avantageux de notre banque pour son compte epargne. Affichage des comptes apres ces operations: ====================================================== Bienvenue chez Despotagers. Bunton, Emma Client #162018 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1001: Solde: 119.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 2.20$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1002: Solde: 0.00$ Taux d'interet: 1.50% A la fin du mois, vous recolterez 0.00$ ------------------------------------------------------ ====================================================== ====================================================== Bienvenue chez Despotagers. Beckham, Victoria Client #162022 Voici la liste de vos comptes dans notre institution: ------------------------------------------------------ Compte cheque #1008: Solde: 999980.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte cheque #1009: Solde: 500000.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte cheque #1010: Solde: 6400000.00$ Solde minimum a respecter: 1000.00$ Frais mensuels: 0.00$ Frais de service: 0.50$ ------------------------------------------------------ Compte epargne #1011: Solde: 48000000.00$ Taux d'interet: 1.50% A la fin du mois, vous recolterez 60000.00$ ------------------------------------------------------ Compte epargne #1012: Solde: 34000000.00$ Taux d'interet: 3.00% A la fin du mois, vous recolterez 85000.00$ ------------------------------------------------------ ====================================================== Sous forte pression financiere, Mel B tente de retirer plus que ce qu'elle a dans son compte. Cher client, votre compte #1003 contient moins que le solde minimum prevu a votre contrat. Des frais de 50 sous ont ete debites a votre compte pour cette transaction. Veuillez agreer de nos sentiments les plus distingues. Cher client, votre compte #1003 n'a pas suffisamment de fonds. Impossible d'effectuer un retrait. Allez directement en prison et si vous passez Go, NE RECLAMEZ PAS 200$. Compte cheque #1003: Solde: 4.50$ Solde minimum a respecter: 1000.00$ Frais mensuels: 2.49$ Frais de service: 0.50$ Mel B est punie pour sa tentative et notre banque lui impose un solde minimum plus eleve dans son compte: Cher client, votre compte #1003 contient moins que le solde minimum prevu a votre contrat. Des frais de 50 sous ont ete debites a votre compte pour cette transaction. Veuillez agreer de nos sentiments les plus distingues. Compte cheque #1003: Solde: 4.00$ Solde minimum a respecter: 10000.00$ Frais mensuels: 24.99$ Frais de service: 0.50$ I'll tell you what I want, what I really, really want So tell me what you want, what you really, really want I wanna, (ha)I wanna, (ha)I wanna, (ha)I wanna, (ha) I wanna really, really, really wanna zigazig ah C:\Users\admin\Desktop\1166\tp3\191213\lafin\Debug\lafin.exe (process 2140) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . . */
9f48fd7c95e687042bc47a1543353a13ce14a24d
b67704525ef4b87e596ecc270bf40bc59df37e96
/201821010211/Ex12_13/Ex12_13.cpp
3209d6fa47791cd5a4ca233b263eb07645dc6320
[]
no_license
201821010211/Assignment_07
9bf7d6124161c18056b5050af9f24a149466bd70
e38cdd760e7194a879de76d7129d29741716595d
refs/heads/master
2020-11-27T16:31:33.103846
2019-12-22T07:45:24
2019-12-22T07:45:24
229,529,688
0
0
null
2019-12-22T06:49:04
2019-12-22T06:49:03
null
UTF-8
C++
false
false
519
cpp
Ex12_13.cpp
#include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; #include "Package.h" #include "OvernightPackage.h" #include "TwoDayPackage.h" int main() { vector <Package*>packages(2); packages[0]=new OvernightPackage("Z","L",300,0.5,0.1); packages[1]=new TwoDayPackage("Z","L",300,0.5,30); cout << fixed << setprecision( 2 ); for ( size_t i = 0; i < packages.size(); i++ ) { cout<<"adress "<<i+1<<": "; packages[i]->print(); } }
4e0184ec88c09cc4961520904b4487a29a75730d
f3562b1fd70da5883b2d5f851c3303c0e684ba92
/pep_coding_ip/tue_nov_12/pow-x-n.cpp
cf664dc6ddecbc00650fd9f4c07164458e95724c
[]
no_license
himanish-star/cp_codes
d12581bbadf6063d085778e8e78686e30c149c91
5d13d537ed744ce783cf7f7188b058b7a44631a3
refs/heads/master
2021-07-13T04:44:46.872056
2020-07-13T11:57:40
2020-07-13T11:57:40
162,413,025
1
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
pow-x-n.cpp
class Solution { public: double myPowUtil(double x, int n) { cout<<n<<" "<<n%2<<endl; if(n==1) { return x; } if(n==-1) { return (double)(1/x); } if(n==0) { return 1; } double pow = myPowUtil(x,n/2); if(n%2==0) { return pow * pow; } else if(n%2==1) { return x * pow * pow; } else { return pow * double(pow/x); } } double myPow(double x, int n) { return myPowUtil(x,n); } };
edd4448a20db5a79ec8ee8e5032f5d0575dffb31
eae7d60af2e7b7cd5a335ed371860462a5698cb8
/Neural Network/NNLM.h
2d0bf9fe9d4309cf5660a6088c896fc72dd15fd0
[]
no_license
nom-de-guerre/Matrices
965828d1d737c7e6067c2946de595f5777b5866d
65f7c0202c27cfb5f80abf1bd44ca192c6da0375
refs/heads/master
2021-09-05T21:52:04.468418
2021-08-26T09:31:59
2021-08-26T09:31:59
53,346,139
2
1
null
null
null
null
UTF-8
C++
false
false
6,378
h
NNLM.h
#ifndef __LEVENBERG_MARQUARDT__NN_H__ #define __LEVENBERG_MARQUARDT__NN_H__ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <data.h> #include <matrix.h> typedef Matrix_t<double> Md_t; #define RECTIFIER(X) log (1 + exp (X)) #define SIGMOID_FN(X) (1 / (1 + exp (-X))) // derivative of rectifier #ifdef __TANH_ACT_FN #define ACTIVATION_FN(X) tanh(X) #define DERIVATIVE_FN(Y) (1 - Y*Y) #else #define ACTIVATION_FN(X) SIGMOID_FN(X) #define DERIVATIVE_FN(Y) (Y * (1 - Y)) #endif // RPROP+ update parameters #define DELTA0 1e-2 #define DELTA_MIN 1e-8 #define DELTA_MAX 50 #define ETA_PLUS 1.2 #define ETA_MINUS 0.5 // Levenberg-Marquardt parameters for dilating the spectrum #define MU_INIT 0.01 #define MU_THETA 10 #ifndef SIGN #define SIGN(X) (signbit (X) != 0 ? -1.0 : 1.0) #endif typedef double weight_t; struct ModelSLP_t; struct perceptron_t { int p_N; double *p_weights; double *p_Ei; double *p_error; double *p_deltaW; double p_delta; double p_iprod; double p_output; #ifdef __RELU bool p_RELU; #endif perceptron_t (void) : p_weights(NULL), p_Ei (NULL), p_deltaW (NULL) #ifdef __RELU , p_RELU (false) #endif { } perceptron_t (int N) { init (N); } ~perceptron_t (void) { if (p_weights == NULL) return; delete [] p_weights; delete [] p_Ei; delete [] p_error; delete [] p_deltaW; } #ifdef __RELU void setRELU (void) { p_RELU = true; } bool RELU (void) { return p_RELU; } #endif void init (int N) { // N accounts for the bias, so + 1 if (p_weights == NULL) { p_N = N; p_weights = new double [N]; p_Ei = new double [N]; p_error = new double [N]; p_deltaW = new double [N]; } else assert (p_N == N); // Glorot for sigmoid: W ~ U[-r, r], r = (6/(f_in + f_out))^0.5 double r = sqrt (6 / ((double) 2 * N + 1)); for (int i = 0; i < p_N; ++i) { double w = (double) rand () / RAND_MAX; p_weights[i] = 2 * r * w - r; p_Ei[i] = 0; p_error[i] = 0; p_deltaW[i] = DELTA0; } } void rprop (void) { for (int i = 0; i < p_N; ++i) rprop (i); } void rprop (int index); void bprop (perceptron_t *, perceptron_t *, const int, const int, const int, const int, Md_t &); double signal (double *xi) { p_iprod = 0; for (int i = 0; i < p_N; ++i) p_iprod += xi[i] * p_weights[i]; #ifdef __RELU if (p_RELU) p_output = RECTIFIER (p_iprod); else p_output = ACTIVATION_FN (p_iprod); #else p_output = ACTIVATION_FN (p_iprod); #endif return (p_output); } double signal (void) { return p_output; } void reset_weight (void) { double w = (double) rand () / RAND_MAX; double r = sqrt (6 / (p_N + 1)); double error = 0; int weight = -1; for (int i = 0; i < p_N; ++i) if (fabs (p_error[i]) > error) { error = p_error[i]; weight = i; } if (weight < 0) assert (error == 0.0); assert (weight < p_N); // int weight = rand () % p_N; p_weights[weight] = 2 * r * w - r; p_Ei[weight] = 0.0; p_error[weight] = 0.0; p_deltaW[weight] = DELTA0; } }; template<typename T> class NNet_t { protected: int n_steps; // morphology of the net int n_Nin; int n_Nout; int n_levels; int *n_width; // array of lengths of n_nn perceptron_t **n_nn; // array of perceptron_t vectors double *n_buffers[2]; // scratch space for compute () int n_RPROP_pending; int n_modes; double n_switch; // RPROP+ threshold, switch to LM int n_RPROP_pending_steps; int n_LM_steps; double n_mu; int n_Nweights; Md_t n_J; // Jacobian for LM Md_t n_Results; // results double n_halt; // solution accuracy (sumsq, not derivs) double n_error; int n_me; enum e_tcodes { WORKING, FINISHED, STALLED }; void PresentExamples (const DataSet_t * const, bool); double PresentExamplesLoss (const DataSet_t * const, bool); void UpdateWeights (Md_t &); bool Step (const DataSet_t * const training, double &); void Reset (const int); void RPROPStep (const DataSet_t * const training, double &); void LMStep (const DataSet_t * const training, double &); void InflectWeightSpace (void); double ComputeDerivative (const TrainingRow_t, const int); void Start (void); bool Halt (DataSet_t const * const); public: /* * levels is the number of layers, including the output. width is an * arrays specifying the width of each level. e.g., { 1, 4, 1 }, is an SLP * with a single input, 4 hidden and 1 output perceptron. * */ NNet_t (int *width, int levels) : n_steps (0), n_Nin (width[0]), n_Nout (width[levels - 1]), n_levels (levels - 1), // no state for input n_RPROP_pending (0), n_modes (0), n_switch (0.8), n_RPROP_pending_steps (0), n_LM_steps (0), n_mu (MU_INIT), n_halt (9e-20), n_error (nan (NULL)), n_me (-1) { int max = 0; n_Nweights = 0; // width = # inputs, width 1, ..., # outputs for (int i = levels - 1; i > 0; --i) n_Nweights += width[i] * (width[i - 1] + 1); // + 1 for bias n_nn = new perceptron_t * [n_levels]; n_width = new int [n_levels]; printf ("CONFIG:\t%d\t%d\t%d\n", n_Nin, n_Nout, n_Nweights); for (int i = 0; i <= n_levels; ++i) { if (width[i] > max) max = width[i]; if (i == 0) continue; // ignore the inputs n_width[i - 1] = width[i]; n_nn[i - 1] = new perceptron_t [width[i]]; } n_buffers[0] = new double [max + 1]; // signal propigation n_buffers[0][0] = 1.0; // Bias n_buffers[1] = new double [max + 1]; // signal propigation n_buffers[1][0] = 1.0; // Bias } ~NNet_t (void) { delete [] n_buffers[0]; delete [] n_buffers[1]; for (int i = 0; i < n_levels; ++i) delete [] n_nn[i]; delete n_nn; delete [] n_width; } void setMSE (double mse) { n_halt = mse; } double whatIsHalt (void) { return n_halt; } void setRPROP (int RPROP) { n_RPROP_pending = RPROP; } bool TrainLifeSign (const DataSet_t * const, int, int); bool Train (const DataSet_t * const, int); bool UpdateTrain (const DataSet_t * const, int); void DisplayCurve (const DataSet_t * const); void DisplayWeights (void); double error (void) { return n_error; } double Compute (double *); inline double Loss (DataSet_t const *); }; #include <NNLM.tcc> #endif // header inclusion
5efd0c9609d35da2aaa63349ff506cce7b5c07b3
b645aaf9822bca5bb7c6008e0765ff56dd3c571f
/c++/tests/main.cpp
3c02e95b183355e7450dc72505361b6f72b421c6
[]
no_license
juli1/design-patterns
4925e024041747b3371bee9cd8cb4b2b356bdf79
fde7f99c64b99927e1791ffc072042efa3b95ed4
refs/heads/master
2021-01-12T01:50:19.200998
2017-02-06T05:54:34
2017-02-06T05:54:34
78,436,946
0
0
null
null
null
null
UTF-8
C++
false
false
3,794
cpp
main.cpp
#include <iostream> #include "Singleton.hpp" #include "Factory.hpp" #include "Builder.hpp" #include "Adapter.hpp" #include "Composite.hpp" #include "Decorator.hpp" #include "Facade.hpp" #include "Bridge.hpp" #include "Command.hpp" #include "ChainOfResponsibility.hpp" #include "Mediator.hpp" #include "Observer.hpp" #include "State.hpp" #include "Template.hpp" #include "Visitor.hpp" #include "model/SoundSystem.hpp" #include "model/Html.hpp" #include "model/Key.hpp" using namespace std; int main (int argc __attribute__((unused)), char** argv __attribute__((unused))) { /* * Show use of singleton */ Singleton* sing1 = Singleton::getInstance(); Singleton* sing2 = Singleton::getInstance(); cout << "sing1=" << sing1 << endl; cout << "sing2=" << sing2 << endl; /* * Use of factory */ ToyotaFactory myfactory; CarToyota* newToyotaCar = myfactory.createCar(); cout << "new car" << newToyotaCar << endl; /** * Use of builder pattern now */ ToyotaBuilder toyotaBuilder; TeslaBuilder teslaBuilder; toyotaBuilder.buildCar(); teslaBuilder.buildCar(); Car* toyotaCar = toyotaBuilder.getCar(); cout << "Toyota car" << toyotaCar << endl; Car* teslaCar = teslaBuilder.getCar(); cout << "Tesla car" << teslaCar << endl; /** * Use of Adapter */ Adapter dviToHdmi; std::string adapterOutput = dviToHdmi.sendHdmiSignal(); cout << adapterOutput << endl; /** * Use of composite */ SoundSystem soundSystem; toyotaCar->addElement (&soundSystem); soundSystem.addElement (new Speaker()); soundSystem.addElement (new Speaker()); soundSystem.addElement (new Stereo()); cout << "Price of the car (with only stereo) " << toyotaCar->getPrice() << endl; /** * Decorator */ FancyDecorator fd(toyotaCar, "**"); cout << fd.showCar() << std::endl; /** * Facade */ FacadeDriving facade; facade.startTrip(); delete toyotaCar; delete teslaCar; // Use the Bridge now ToyotaKey toyotaKey; toyotaKey.openCar(); TeslaKey teslaKey; teslaKey.openCar(); // Use Chain Of Reponsibility CarStartingRemotely* carRemote = new CarStartingRemotely(NULL); KeyReceiverStarter* keyReceiver = new KeyReceiverStarter(carRemote); KeyRemoteStarter* keyRemote = new KeyRemoteStarter (keyReceiver); keyRemote->startCar(); //Command Client myClient; Receiver myReceiver; Invoker myInvoker; myClient.createCommand (myReceiver, myInvoker); myInvoker.run(); //Mediator Supplier supplier1(10, 100); Supplier supplier2(5, 50); Mediator mediator; mediator.addSupplier (&supplier1); mediator.addSupplier (&supplier2); OEM oem1 (mediator, 10); oem1.negotiate(); OEM oem2 (mediator, 5); oem2.negotiate(); //Observer GasStation station1; GasStation station2; GasStation station3; PriceObserver po1; PriceObserver po2; station1.addObserver (&po1); station2.addObserver (&po1); station2.addObserver (&po2); station3.addObserver (&po2); station1.updatePrice (30); station2.updatePrice (50); station3.updatePrice (10); cout << "Min price observer1 = " << po1.getMinPrice() << endl; cout << "Min price observer2 = " << po2.getMinPrice() << endl; // State Person p; p.goToSleep(); p.wakeUp(); p.run(); p.work(); p.drink(); p.speak(); // Template NoisyAlarm na; QuietAlarm qa; na.alarm(); qa.alarm(); // Visitor Head* head = new Head(); head->setTitle (new Title ("hello")); Body* body = new Body(); body->addHtmlElement (new P("Hello, world")); body->addHtmlElement (new P("Hello, world2")); Document* d = new Document (head, body); PrinterVisitor pv; pv.visit (d); cout << "HTML version:\n" << pv.getText() << endl; TextOnlyVisitor tov; tov.visit (d); cout << "Text version:\n" << tov.getText() << endl; }
550fa6b184246567dc134e3f5a77ae2311c7ae39
cef6aa553e47bc17eb8d88c6afcc47cd71914488
/Megaton Hammer/src/robot.hpp
5cbc93e1b2b2d0d937b4d45c335f7254dd1cf1ea
[]
no_license
sAbhay/XCode-Projects
95085b4cf3f3198c2bb08892d1c9a2a6e58e6dfc
3614f676aca1b13b1f21bb204bae18dfb913327b
refs/heads/master
2020-04-17T21:24:33.585121
2019-01-22T09:46:19
2019-01-22T09:46:19
163,640,802
0
0
null
null
null
null
UTF-8
C++
false
false
846
hpp
robot.hpp
// // robot.hpp // Megaton Hammer // // Created by Abhay Singhal on 27/03/18. // #ifndef robot_hpp #define robot_hpp #include <stdio.h> #include "ofMain.h" #include "camera.hpp" #include "ofxAssimpModelLoader.h" #include "ofVboMesh.h" class Robot { private: CeasyCam cam; ofMesh mesh; ofxAssimpModelLoader model; ofVec3f center; ofVec3f size; ofVec3f pos; ofVec3f forward; float speed; vector<ofVec3f> ofxBBox(ofMesh mesh); public: Robot(); ~Robot(); void update(); void display(); void moveForward(); void moveBack(); void turnLeft(); void turnRight(); void beginCamera() {cam.begin();} void endCamera() {cam.end();} }; #endif /* robot_hpp */
333652ee7c98a3d1741806028b4422378724cfca
0905e1941724f66835985784e61bc60096365384
/UVA/Old_Code/10935 - Throwing cards away I.cpp
29e722672a1620cae20a46f54d75113c6582a822
[]
no_license
smafjal/AcmOnlinePractice
eba75da039adf93c7f5c63ce76c5598c3fc32c94
ecc1188256b598583d1334b1bef2588476426815
refs/heads/master
2020-04-09T21:25:13.519119
2016-02-21T11:39:47
2016-02-21T11:39:47
52,203,554
2
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
10935 - Throwing cards away I.cpp
#include<stdio.h> #define sz 600 int queue[sz]; int f=1;int r; int check(void) { if(r==f)return 1; return 0; } int pop() { int p; p=queue[f]; f++; return p; } void pushintial(int i) { queue[1]=1; } void push(int i) { queue[++r]=i; } int main() { int i,j,n; int arr[sz]; int k; while(scanf("%d",&n)==1) { if(!n)break; if(n==1) { printf("Discarded cards:\n"); printf("Remaining card: 1\n"); continue; } r=n; for(i=1;i<=n;i++)queue[i]=i; k=0; while(!check()) { arr[k++]=pop(); push(pop()); } for(i=0;i<k;i++) { if(i==0) { printf("Discarded cards: 1"); continue; } printf(","); printf(" %d",arr[i]); } printf("\n"); printf("Remaining card: %d\n",queue[r]); f=1; } return 0; }
988a0a2769146b11e0b1d108ef7e37aacc60c65b
88a14a13d7cba8d9f722d102f1065cf838c880e3
/CS486 - HW1/CS486 - HW1/main.cpp
bdcd1c801ea24788604fd9ac5e6abe1337cc0a03
[]
no_license
lavahot/Computer-Vision-Coursework
94fe1ca42864648e4b67a5a25cb5e17630c43ec6
0902ad1fdc49e6b4404b42a4bc922b0e5da282c8
refs/heads/master
2020-04-11T08:44:10.526328
2013-02-26T06:35:44
2013-02-26T06:35:44
8,243,451
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
main.cpp
// // main.cpp // CS486 - HW1 // // Created by Taylor Mansfield on 2/16/13. // Copyright (c) 2013 Taylor Mansfield. All rights reserved. // #include <iostream> //#include "ReadImage.cpp" //#include "WriteImage.cpp" #include "Gauss2D.h" #include "Image.h" using namespace std; int main() { char filename[30]; int Width = 0; int Height = 0; int Depth = 0; float Sigma = 0; int Mask = 0; int **image;//pointer to array cout<<"Please enter the filename of the image: "; cin>>filename; ReadImage(filename, &image, Width, Height, Depth); do{ cout<<"Set an odd mask size: "; cin>>Mask; if (Mask%2==0 || Mask>Width || Mask>Height) { cout<<"Sorry, that is an even size or bigger than one of the image dimensions."<<endl <<"Please try again."<<endl; } }while ((Mask%2==0 || Mask>Width || Mask>Height)); cout<<"Set sigma for smoothing: "; cin>>Sigma; Gauss2D *Gaussian = new Gauss2D(Height, Width, Sigma, Mask, Depth, &image); Gaussian->smooth(); WriteImage("result.pgm", image, Width, Height, Depth); cout<<"/nSmoothing completed."; return 0; }
72efb1f6c4636504370ad7e27ccef551c5605470
bb2f2e85ca676f3756af4ed0bef9171304fcd058
/Lab1_Templates/Lab1_Templates/complex_number.h
a65cd27be3d986a59ca7ef28dcc4a0d6930b94e2
[]
no_license
MaslennikovaDaria/Lab1_Templates
655486be20a6f5541dd2563e0f17ca66c4397a88
6f15fa9bad7747f6534fa145020f27115890496b
refs/heads/master
2020-05-27T04:24:13.074585
2019-05-24T20:35:30
2019-05-24T20:35:30
188,482,003
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
complex_number.h
#pragma once #include <iostream> using namespace std; class complex { private: int re, im; public: complex() { re = 0; im = 0; } complex(int re1, int im1) //constructor { re = re1; im = im1; } friend ostream& operator<<(ostream& out, const complex &numb) { out << numb.re;//works but error if (numb.im) if (numb.im > 0) out << '+' << numb.im << 'j'; else out << numb.im; return out; } };
9fb40dd94c57662b62e570fde67615342203736d
beeca2af3256ecc03b6820d3fd12b988e2e0eada
/communication/mavlink_stream.hpp
5d098722a4049fde965a784016f1474cf288e188
[ "BSD-3-Clause" ]
permissive
robert-b/MAVRIC_Library
55f058c9c5570f1554d3adb82f6c419780e97a02
56281851da7541d5c1199490a8621d7f18482be1
refs/heads/master
2020-03-29T03:46:39.320069
2017-02-02T14:22:53
2017-02-02T14:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,576
hpp
mavlink_stream.hpp
/******************************************************************************* * Copyright (c) 2009-2016, MAV'RIC Development Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /******************************************************************************* * \file mavlink_stream.hpp * * \author MAV'RIC Team * \author Julien Lecoeur * * \brief A wrapper for MAVLink to use the stream interface * ******************************************************************************/ #ifndef MAVLINK_STREAM_HPP_ #define MAVLINK_STREAM_HPP_ #include <cstdint> #include <cstdbool> #include "hal/common/serial.hpp" extern "C" { #include "hal/common/mavric_endian.h" } #ifdef __MAVRIC_ENDIAN_BIG__ #define NATIVE_BIG_ENDIAN #endif extern "C" { #include "libs/mavlink/include/mavric/mavlink.h" } #define MAVLINK_BASE_STATION_ID 255 /** * \brief Main structure for the MAVLink stream module */ class Mavlink_stream { public: /** * \brief Mavlink structures for the receive message and its status */ typedef struct { mavlink_message_t msg; ///< Mavlink message mavlink_status_t status; ///< Status on the message } msg_received_t; /** * \brief Configuration structure for the module MAVLink stream */ struct conf_t { uint32_t sysid; ///< System ID uint32_t compid; ///< System Component ID bool debug; ///< Debug flag }; /** * \brief Default config of MAVLink stream */ static conf_t default_config(void); /** * \brief Constructor */ Mavlink_stream(Serial& serial, const conf_t& config = default_config()); /** * \brief Send Mavlink stream * * \param msg msg to stream * * \return success */ bool send(mavlink_message_t* msg) const; /** * \brief Mavlink parsing of message; the message is not available in this module afterwards * * \param rec Address where to store the received message * * \return Success True if a message was successfully decoded, false else */ bool receive(msg_received_t* rec); /** * \brief Flushing MAVLink stream */ void flush(); /** * \brief Return sysid of this stream * * \return sysid */ inline uint32_t sysid() const {return sysid_;}; // inline for higher exec speed /** * \brief Return sysid of this stream * * \return sysid */ inline uint32_t compid() const {return compid_;}; // inline for higher exec speed uint32_t sysid_; ///< System ID private: uint32_t compid_; ///< System Component ID Serial& serial_; uint8_t mavlink_channel_; ///< Channel number used internally by mavlink to retrieve incomplete incoming message bool debug_; ///< Debug flag }; #endif /* MAVLINK_STREAM_H */
390d7412d71750fdc16639b3ae519c7d5c51ac27
c8b8ebdc916cd5bccc1c9fc64fae3a282ac8f90f
/Kinect2Win32App/featurePoint.h
69de3a8c2a67f63d4379d8cf78d4db293d25b9d0
[]
no_license
roylu007/kinectv2W32appVirtualTryon
f870a2f268b7303587fd8af50cfcd3e799e2dd9a
b82b3a1f278a41c8882fbbe6d0931374dcc56b11
refs/heads/master
2020-07-31T01:03:36.394405
2017-04-12T14:03:08
2017-04-12T14:03:08
73,612,614
1
1
null
null
null
null
UTF-8
C++
false
false
4,594
h
featurePoint.h
#ifndef FEATUREPOINT_H #define FEATUREPOINT_H #include <iostream> #include <vector> #include "include_opencv/opencv2/opencv.hpp" #define ABS_FLOAT_0 0.000001 using namespace std; using namespace cv; template<class T> class Compare { public: int operator()(const T& A, const T& B)const { if (A.x > B.x) return 0; if (A.x == B.x && A.y > B.y) return 0; return 1; } }; static const Scalar color[] = { CV_RGB(255, 0, 0), CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), CV_RGB(255, 255, 0), CV_RGB(255, 0, 255), CV_RGB(0, 255, 255), CV_RGB(128, 0, 0), CV_RGB(0, 128, 0), CV_RGB(0, 0, 128), CV_RGB(128, 128, 0), CV_RGB(128, 0, 128), CV_RGB(0, 128, 128), CV_RGB(64, 0, 0), CV_RGB(0, 0, 0) }; class featurePoint{ public: featurePoint(); ~featurePoint(); featurePoint(const featurePoint& fpt); featurePoint& operator = (const featurePoint& fpt); void featurepointInit(); //void getSpecialPoint27(vector<Point>contoursPoints); double getDistance(Point p1, Point p2); double getCosAngle2(Point pt1, Point pt2, Point pt3, Point pt4); double getCosAngle(Point pt1, Point pt2, Point pt0); float GetTriangleSquar(Point pt0, Point pt1, Point pt2); bool isInTriangle(Point A, Point B, Point C, Point D); bool PtInAnyRect(Point pCur, Point pLT, Point pLB, Point pRB, Point pRT); Point getPointP0(vector<Point>contoursPoint, Point v0); Point getPointP26(vector<Point>contoursPoint, Point v0); Point getPointP25(vector<Point>contoursPoint, Point p26); Point getPointP1(vector<Point>contoursPoint, Point p0); Point getPointV0(vector<Point>contoursPoint); Point getPointV1(vector<Point>contoursPoint, Point p1); Point getPointV2(vector<Point>contoursPoint, Point p25); Point getPointP2(vector<Point>contoursPoint, Point p1, Point v1); Point getPointP24(vector<Point>contoursPoint, Point v2, Point p25); Point getPointP3(vector<Point>contoursPoint, Point p1, Point p2, Point v1); Point getPointP23(vector<Point>contoursPoint, Point p24, Point p25, Point v2); Point getPointP4(vector<Point>contoursPoint, Point p2, Point p3, Point v1, Point p6); Point getPointP5(vector<Point>contoursPoint, Point p1, Point p2, Point v1, Point p6); Point getPointP21(vector<Point>contoursPoint, Point p25, Point p24, Point p20, Point v2); Point getPointP7(vector<Point>contoursPoint, Point p5, Point p6, Point v3); Point getPointP19(vector<Point>contoursPoint, Point p21, Point p20, Point v4); Point getPointP8(vector<Point>contoursPoint, Point p6, Point p7, Point v3); Point getPointP9(vector<Point>contoursPoint, Point p6, Point p8, Point v3); Point getPointP10(vector<Point>contoursPoint, Point p8, Point p9, Point v3); Point getPointP11(vector<Point>contoursPoint, Point p9, Point p10, Point v3, Point p13); Point getPointP12(vector<Point>contoursPoint, Point p8, Point p9, Point v3, Point p13); Point getPointP18(vector<Point>contoursPoint, Point p20, Point p19, Point v4); Point getPointP17(vector<Point>contoursPoint, Point p20, Point p18, Point v4); Point getPointP16(vector<Point>contoursPoint, Point p18, Point p17, Point v4); Point getPointP15(vector<Point>contoursPoint, Point p17, Point p16, Point p13, Point v4); Point getPointP14(vector<Point>contoursPoint, Point p18, Point p17, Point p13, Point v4); Point getPointP22(vector<Point>contoursPoint, Point p24, Point p23, Point p20, Point v2); Point getPointP6(vector<Point>contoursPoint, Point v1); Point getPointP20(vector<Point>contoursPoint, Point v2); Point getPointV3(vector<Point>contoursPoint, Point p6); Point getPointV4(vector<Point>contoursPoint, Point p20); Point getPointP13(vector<Point>contoursPoint, Point v3); void on_mouse(int event, int x, int y, int flags, void* img); void fillHole(const Mat srcBw, Mat &dstBw); void getSizeContours(vector<vector<Point>> &contours); vector<vector<Point>> getMaxSizeContours(vector<vector<Point>> &contours); void getBodyContoursPoint(vector<vector<Point>> &contours); //vector<Point> getBodyContoursPoint(vector<vector<Point>> &contours); void getCircle200(Mat srcBw, vector<Point> &contours); void getSpecialPoint27(Mat srcBw, vector<Point>&contoursPoint); int getRegion(Point p); void getBodyRegion(Mat& pic, IplImage *srcBw); void getUpGarmentRegion(Mat& upgarment, Mat srcBw); vector<Point>contours; vector<Point>featurePt; vector<Point>contoursPoint1; vector<Point>contoursPoint2; //vector<Point>featurePoints; vector<Point>auxiliaryPoints; map<Point, int, Compare<Point> >mapBodyRegion; map<Point, int, Compare<Point> >mapUpGarmentRegion; //Scalar color[14]; int threshval; int pointinterval; int M; private: }; #endif
3ff66395f68e3e6a94b3f49f77b4b951cf01a856
023922d39d2dc2db93d153fe3116724430510015
/OnlineGaming_Project1/BasePlayer.h
e9049c9fde0be8efe66d7168d4cacac1fd62f436
[]
no_license
francis-carroll/OnlineGaming_Project1
25eb890a294538c86bb39ed2ac521a00690b72a7
7ad4ff3419d536909843675b619e09c0fa2f7bf4
refs/heads/master
2023-02-25T07:59:52.547153
2021-01-28T16:42:43
2021-01-28T16:42:43
319,598,270
0
0
null
null
null
null
UTF-8
C++
false
false
586
h
BasePlayer.h
#pragma once #include <Client.h> #include <Player.h> class Play; class BasePlayer : public Player { public: BasePlayer(int t_id, string t_ip); BasePlayer(int t_id, string t_ip, Identifier t_identifier); BasePlayer(int t_id, string t_ip, Vector2f t_position, float t_radius); BasePlayer(int t_id, string t_ip, Vector2f t_position, float t_radius, Identifier t_identifier); ~BasePlayer(); void setupClient(Play* t_game); void update(Time t_deltaTime); shared_ptr<Client> getClient(); protected: void movement(Time t_deltaTime); shared_ptr<Client> m_client; string m_ip; };
1f7515e0f0e1d92c501886c73c2ca3060960e18c
9be573b87220a3f9c02f17b987b16dc90ac6b048
/build-train-Desktop_Qt_5_8_0_clang_64bit-Debug/ui_message.h
6117de27b4a3318d96aa2a77e6ced2fa07e84e05
[]
no_license
shuai1126/keshe
c72aeae176aa947f49a2a3fe8778acabbe10a365
fab075306412c645a5746b8812db26608b055a54
refs/heads/master
2020-03-22T10:42:50.991682
2018-07-13T01:30:18
2018-07-13T01:30:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,077
h
ui_message.h
/******************************************************************************** ** Form generated from reading UI file 'message.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MESSAGE_H #define UI_MESSAGE_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Message { public: QLabel *label; QWidget *verticalLayoutWidget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label_2; QLineEdit *lineEdit_3; QHBoxLayout *horizontalLayout_2; QLabel *label_4; QLineEdit *lineEdit; QHBoxLayout *horizontalLayout_3; QLabel *label_5; QLineEdit *lineEdit_2; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_3; QPushButton *pushButton_4; void setupUi(QWidget *Message) { if (Message->objectName().isEmpty()) Message->setObjectName(QStringLiteral("Message")); Message->resize(960, 540); label = new QLabel(Message); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(50, 30, 161, 51)); QFont font; font.setPointSize(40); label->setFont(font); verticalLayoutWidget = new QWidget(Message); verticalLayoutWidget->setObjectName(QStringLiteral("verticalLayoutWidget")); verticalLayoutWidget->setGeometry(QRect(70, 100, 821, 161)); verticalLayout = new QVBoxLayout(verticalLayoutWidget); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); label_2 = new QLabel(verticalLayoutWidget); label_2->setObjectName(QStringLiteral("label_2")); QFont font1; font1.setPointSize(20); label_2->setFont(font1); horizontalLayout->addWidget(label_2); lineEdit_3 = new QLineEdit(verticalLayoutWidget); lineEdit_3->setObjectName(QStringLiteral("lineEdit_3")); lineEdit_3->setFont(font1); horizontalLayout->addWidget(lineEdit_3); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); label_4 = new QLabel(verticalLayoutWidget); label_4->setObjectName(QStringLiteral("label_4")); label_4->setFont(font1); horizontalLayout_2->addWidget(label_4); lineEdit = new QLineEdit(verticalLayoutWidget); lineEdit->setObjectName(QStringLiteral("lineEdit")); lineEdit->setFont(font1); horizontalLayout_2->addWidget(lineEdit); verticalLayout->addLayout(horizontalLayout_2); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3")); label_5 = new QLabel(verticalLayoutWidget); label_5->setObjectName(QStringLiteral("label_5")); label_5->setFont(font1); horizontalLayout_3->addWidget(label_5); lineEdit_2 = new QLineEdit(verticalLayoutWidget); lineEdit_2->setObjectName(QStringLiteral("lineEdit_2")); lineEdit_2->setFont(font1); horizontalLayout_3->addWidget(lineEdit_2); verticalLayout->addLayout(horizontalLayout_3); pushButton = new QPushButton(Message); pushButton->setObjectName(QStringLiteral("pushButton")); pushButton->setGeometry(QRect(380, 330, 221, 71)); pushButton->setFont(font1); pushButton_2 = new QPushButton(Message); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); pushButton_2->setGeometry(QRect(620, 330, 221, 71)); pushButton_2->setFont(font1); pushButton_3 = new QPushButton(Message); pushButton_3->setObjectName(QStringLiteral("pushButton_3")); pushButton_3->setGeometry(QRect(160, 330, 201, 71)); pushButton_3->setFont(font1); pushButton_4 = new QPushButton(Message); pushButton_4->setObjectName(QStringLiteral("pushButton_4")); pushButton_4->setGeometry(QRect(730, 30, 151, 61)); retranslateUi(Message); QMetaObject::connectSlotsByName(Message); } // setupUi void retranslateUi(QWidget *Message) { Message->setWindowTitle(QApplication::translate("Message", "Form", Q_NULLPTR)); label->setText(QApplication::translate("Message", "\345\237\272\346\234\254\344\277\241\346\201\257", Q_NULLPTR)); label_2->setText(QApplication::translate("Message", "\347\224\250\346\210\267\345\220\215\357\274\232", Q_NULLPTR)); label_4->setText(QApplication::translate("Message", "\346\211\213\346\234\272\345\217\267\357\274\232", Q_NULLPTR)); label_5->setText(QApplication::translate("Message", "\351\202\256\347\256\261\357\274\232", Q_NULLPTR)); pushButton->setText(QApplication::translate("Message", "\346\267\273\345\212\240/\345\210\240\351\231\244\344\271\230\345\256\242", Q_NULLPTR)); pushButton_2->setText(QApplication::translate("Message", "\344\277\235\345\255\230\344\277\241\346\201\257", Q_NULLPTR)); pushButton_3->setText(QApplication::translate("Message", "\344\277\256\346\224\271\345\257\206\347\240\201", Q_NULLPTR)); pushButton_4->setText(QApplication::translate("Message", "\350\277\224\345\233\236", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Message: public Ui_Message {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MESSAGE_H
ceeb80e2d3de524713391ecb418e2952a6132a34
7a4005182f6cac348283f2120c34e722627d8ae9
/callable_object.cpp
93f2517d3820b890db7007b37e305ad8740d6a61
[]
no_license
Abdullah-Al-Zishan/C-Multi-threading
41feacaceeea5cc8e7e465c2517fdafa53f06b9e
5df119dc591318edf73eaebd9d9374fef0caf52b
refs/heads/master
2022-07-31T12:34:16.059344
2020-03-20T18:00:00
2020-05-19T21:57:50
260,241,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
cpp
callable_object.cpp
#include <thread> #include <mutex> #include <iostream> /* Simple functor with no purpose for demonstartion */ class Functor { public: Functor() { } ~Functor() { } void foo(int n, char ch) { std::cout << "Foo function called: " << n << ", " << ch << std::endl; } long bar(double n) { std::cout << "Bar function called: " << n << std::endl; return (0); } int operator()(int n) { std::cout << "operator() called: " << n << std::endl; return (0); } }; void func(void) { } int main() { Functor functor; std::thread thread_1(functor, 1); // called a copy_of_functor() in a different thread std::thread thread_2(std::ref(functor), 2); // called functor() in a different thread std::thread thread_3(Functor(), 3); // called temp Functor() std::thread thread_4([](int x) { return (x * x); }, 4); // calling a lambda function in the thread std::thread thread_5(func); // calling a user function in a thread std::thread thread_6(&Functor::foo, functor, 6, 'a'); // calling copy_of_functor.foo() in a thread std::thread thread_7(&Functor::foo, &functor, 6, 'a'); // calling of the functor.foo() in a thread std::thread thread_8(std::move(functor), 8); // functor is no longer available thread_1.join(); thread_2.join(); thread_3.join(); thread_4.join(); thread_5.join(); thread_6.join(); thread_7.join(); thread_8.join(); std::cin.get(); return (0); }
bda6e70f1e58776ff79c56645d7947a751bc3fb9
8b8bbaf6a44fb301df2157709b1dff0faf640523
/tests/widget_callbacks.cpp
d676a9b83c926a2c351b4dcc88ad0c7fb87e3b31
[]
no_license
Manewing/todo
b5fa249b38a5e21978ff158ef7121f36fb71bbc0
a45d12ad144ae8c6c2b1a9727d1132b776134849
refs/heads/master
2021-01-10T17:04:01.777145
2017-05-06T12:56:36
2017-05-06T12:56:36
51,470,606
0
0
null
null
null
null
UTF-8
C++
false
false
3,901
cpp
widget_callbacks.cpp
#include <iostream> #include <string> #include <td-defs.h> #include <td-widget.h> #include <td-except.h> #include <td-update.h> class test_widget : public todo::widget, public todo::update_if { public: test_widget(std::string name) : todo::widget(), m_name(name) { set_update(new todo::urecall_exception(this)); } virtual ~test_widget() {} virtual void callback_handler(int input) { std::cout << m_name << " got input: 0x" << std::hex << input << std::dec; if(CMDK_VALID_START <= input && input <= CMDK_VALID_END) std::cout << " = '" << (char)input << "'"; switch(input) { case CMDK_ESCAPE: std::cout << " = CMDK_ESCAPE; returning focus" << std::endl; return_focus(); // throws exception break; case 'r': case 'R': std::cout << "; reprint" << std::endl; // R eprint update(); break; } // this might be not executed! > std::cout << std::endl; } virtual int print(WINDOW * win = NULL) { (void)win; std::cout << m_name << " " << this << std::endl; return 1; } std::string name() const { return m_name; } private: std::string m_name; }; class test_deep_widget : public test_widget { public: test_deep_widget(std::string name): test_widget(name), m_test(name+".test") {} virtual ~test_deep_widget() {} virtual int print(WINDOW * win = NULL) { test_widget::print(); std::cout << " -> "; m_test.print(); return 2; } virtual void callback(int input) { m_test.callback(input); } private: test_widget m_test; }; class test_system : public test_widget { public: test_system(): test_widget("system"), m_test1("test1"), m_test2("test2"), m_test3("test3") { update(); } virtual ~test_system() {} virtual int print(WINDOW * win = NULL) { int lines = test_widget::print(); std::cout << " -> "; lines += m_test1.print(); std::cout << " -> "; lines += m_test2.print(); std::cout << " -> "; lines += m_test3.print(); return lines; } virtual void update() { int lines = print(); std::cout << "---- lines: " << lines << " ----" << std::endl; } virtual void callback_handler(int input) { try { test_widget::callback_handler(input); } catch(todo::exception * except) { std::cout << name() << " catched exception" << std::endl; except->handle(this); } switch(input) { case '1': std::cout << " -> set focus to: "; m_test1.print(); set_focus(&m_test1); break; case '2': std::cout << " -> set focus to: "; m_test2.print(); set_focus(&m_test2); break; case '3': std::cout << " -> set focus to: "; m_test3.print(); set_focus(&m_test3); break; default: std::cout << " -> invalid input, ignored" << std::endl; break; } } private: test_widget m_test1; test_widget m_test2; test_deep_widget m_test3; }; int main() { test_system sys; const int str[] = { 0xCAFECAFE, '1', 0x7E571, CMDK_ESCAPE, 0xCAFECAFE, '2', 0x7E572, CMDK_ESCAPE, 0xCAFECAFE, '3', 0x7E573, 'r', CMDK_ESCAPE, 0xCAFECAFE, CMDK_ESCAPE, 0xCAFECAFE }; const int length = sizeof(str)/sizeof(int); for(int l = 0; l < length; l++) { sys.callback(str[l]); } }
a4ef7ace23b9685e0f5ecf057a2ef5e647067a2b
b5571d53d011154291cd5bfd34f7f374661ffbec
/include/basemodule.h
d543dfbb2309fe995d07052d310da93ded6ad13f
[]
no_license
standlucian/RoGecko
387dff7dd0f97aa16f704e7ba2e5ff59d24c0bdc
2129352c4c42acf5a60786cb6e6bfc3d3ac006aa
refs/heads/master
2021-03-16T05:26:24.759891
2017-05-17T08:14:28
2017-05-17T08:14:28
91,550,573
0
0
null
null
null
null
UTF-8
C++
false
false
4,638
h
basemodule.h
/* Copyright 2011 Bastian Loeher, Roland Wirth This file is part of GECKO. GECKO is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GECKO 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BASEMODULE_H #define BASEMODULE_H #include <QString> #include <QVector> #include "abstractmodule.h" #include "abstractinterface.h" #include "pluginconnector.h" #include "runmanager.h" #include "eventbuffer.h" #include "outputplugin.h" class BaseUI; class ModuleManager; /*! base class for all modules. * Each module is registered with the module manager to allow generalised access. * To implement a new DAQ module inherit from this class. * You will need to call #setUI in your constructor because the main window needs the UI right after construction of the module. * * The OutputPlugin created by the #createOutputPlugin method uses the registered EventSlots to derive the naming and * number of its output connectors. Therefore you should register all EventSlots (using #addSlot) prior to calling #createOutputPlugin. * This should also happen inside the constructor. */ class BaseModule : public AbstractModule { Q_OBJECT public: BaseModule(int _id, QString _name) : iface (NULL) , output (NULL) , id (_id) , name (_name) , ui (NULL) { } virtual ~BaseModule() { EventBuffer *evbuf = RunManager::ref ().getEventBuffer (); QList<EventSlot*> s (*evbuf->getEventSlots(this)); for (QList<EventSlot*>::const_iterator i = s.begin (); i != s.end (); ++i) evbuf->destroyEventSlot (*i); if (output) delete output; output = NULL; } int getId () const { return id; } const QString& getName() const { return name; } QString getTypeName () const {return typename_; } BaseUI* getUI() const { return ui; } virtual void saveSettings(QSettings*) {} virtual void applySettings(QSettings*) {} AbstractInterface *getInterface () const { return iface; } void setInterface (AbstractInterface *ifa) { if (iface) disconnect (iface, SIGNAL (destroyed()), this, SLOT (interfaceRemoved ())); iface = ifa; connect (iface, SIGNAL (destroyed()), SLOT (interfaceRemoved ())); } /*! Returns a list of all slots belonging to this module. */ QList<const EventSlot*> getSlots () const { const QList<EventSlot*>* s = RunManager::ref ().getEventBuffer ()->getEventSlots(this); QList<const EventSlot*> out; #if QT_VERSION >= 0x040700 out.reserve (s->size ()); #endif for (QList<EventSlot*>::const_iterator i = s->begin (); i != s->end (); ++i) out.append (*i); return out; } OutputPlugin* getOutputPlugin () const { return output; } virtual void runStartingEvent () {} public slots: virtual void prepareForNextAcquisition () {} private slots: void interfaceRemoved () { iface = NULL; } protected: /*! Adds an event buffer slot to the module. */ const EventSlot* addSlot (QString name, PluginConnector::DataType dtype) { return RunManager::ref ().getEventBuffer()->registerSlot (this, name, dtype); } /*! Create the output plugin for this module. The output plugin forms the conduit between the module and the plugin part of the program. It makes the slots exported by the module available to other plugins. It also handles the transition between the run thread and the plugin thread. \remarks only call this function after registering all the slots the module will export as the number and names of connectors are derived from them. The plugin will be deleted when the module is destroyed. */ void createOutputPlugin () { output = new OutputPlugin (this); } void setUI (BaseUI *_ui) { ui = _ui; } void setName (QString newName) { name = newName; } void setTypeName (QString newTypeName) { typename_ = newTypeName; } private: AbstractInterface *iface; OutputPlugin *output; int id; QString name; QString typename_; BaseUI *ui; }; #endif // BASEMODULE_H
3c58910246bcba7304dd86e80ff58a616cde15a9
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-glue/source/model/ResourceUri.cpp
af669d0035a20ae71f290eb456880475ca8392de
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,405
cpp
ResourceUri.cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/glue/model/ResourceUri.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Glue { namespace Model { ResourceUri::ResourceUri() : m_resourceType(ResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_uriHasBeenSet(false) { } ResourceUri::ResourceUri(JsonView jsonValue) : m_resourceType(ResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_uriHasBeenSet(false) { *this = jsonValue; } ResourceUri& ResourceUri::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ResourceType")) { m_resourceType = ResourceTypeMapper::GetResourceTypeForName(jsonValue.GetString("ResourceType")); m_resourceTypeHasBeenSet = true; } if(jsonValue.ValueExists("Uri")) { m_uri = jsonValue.GetString("Uri"); m_uriHasBeenSet = true; } return *this; } JsonValue ResourceUri::Jsonize() const { JsonValue payload; if(m_resourceTypeHasBeenSet) { payload.WithString("ResourceType", ResourceTypeMapper::GetNameForResourceType(m_resourceType)); } if(m_uriHasBeenSet) { payload.WithString("Uri", m_uri); } return payload; } } // namespace Model } // namespace Glue } // namespace Aws
50455d6c22eb0090a064660cc0f2e95976d7281c
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/xmltransport/soap/server/opdelcs.cpp
d54b2ea477f3129104eb9760ac2509a2b346669c
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
opdelcs.cpp
//*************************************************************************** // // Copyright (c) 2000-2001 Microsoft Corporation // // OPDELCS.CPP // // alanbos 07-Nov-00 Created. // // WMI Delete Class operation implementation. // //*************************************************************************** #include "precomp.h" HRESULT WMIDeleteClassOperation::BeginRequest ( CComPtr<IWbemServices> & pIWbemServices ) { return pIWbemServices->DeleteClass (m_bsClassName, 0, GetContext(), NULL); } bool WMIDeleteClassOperation::ProcessElement( const wchar_t __RPC_FAR *pwchNamespaceUri, int cchNamespaceUri, const wchar_t __RPC_FAR *pwchLocalName, int cchLocalName, const wchar_t __RPC_FAR *pwchRawName, int cchRawName, ISAXAttributes __RPC_FAR *pAttributes) { bool result = false; if (0 == wcscmp(WMI_DELETECLASS_PARAMETER_NAME, pwchLocalName)) { // following content will be the value of the classname SetParseState (Name); result = true; } return result; } bool WMIDeleteClassOperation::ProcessContent ( const unsigned short * pwchChars, int cchChars ) { if (Name == GetParseState ()) m_bsClassName = SysAllocStringLen (pwchChars, cchChars); return true; }
4e9ccf69c3a0de008ac551028694ac3d341cc67f
51cc2aa23688d2d6df1511d316e312eacc5b1192
/SDK/RC_SceneComponentPools_classes.hpp
434a33118cd1d2411a96a38026639219eefc03e9
[]
no_license
hinnie123/RogueCompany_SDK
eb5e17a03f733efdad99c64357d22b715b7c9879
b6382f4b38626ff5c2929067f8ee2664c4bf92c4
refs/heads/master
2023-07-09T16:35:49.736981
2021-08-15T12:04:10
2021-08-15T12:04:10
250,232,865
4
3
null
null
null
null
UTF-8
C++
false
false
7,238
hpp
RC_SceneComponentPools_classes.hpp
#pragma once // RogueCompany (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class SceneComponentPools.BasePoolComponent // 0x0020 (0x0118 - 0x00F8) class UBasePoolComponent : public UActorComponent { public: int MaxPoolSize; // 0x00F8(0x0004) (Edit, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData) int StartingPoolSize; // 0x00FC(0x0004) (Edit, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData) struct FString ComponentClassName; // 0x0100(0x0010) (Edit, ZeroConstructor, Config, DisableEditOnInstance) EPoolOverflowHandling OverflowType; // 0x0110(0x0001) (Edit, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x0111(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.BasePoolComponent"); return ptr; } }; // Class SceneComponentPools.DecalPoolComponent // 0x0078 (0x0190 - 0x0118) class UDecalPoolComponent : public UBasePoolComponent { public: unsigned char UnknownData00[0x8]; // 0x0118(0x0008) MISSED OFFSET class UClass* PooledDecalComponentClass; // 0x0120(0x0008) (ZeroConstructor, Transient, IsPlainOldData) TArray<class UPoolableDecalComponent*> UnusedComponentsArray; // 0x0128(0x0010) (ExportObject, ZeroConstructor) unsigned char UnknownData01[0x50]; // 0x0138(0x0050) UNKNOWN PROPERTY: SetProperty SceneComponentPools.DecalPoolComponent.UsedComponentsSet class UPoolableDecalComponent* PeekedDecalComponent; // 0x0188(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.DecalPoolComponent"); return ptr; } }; // Class SceneComponentPools.ParticleSystemPoolComponentBase // 0x0080 (0x0198 - 0x0118) class UParticleSystemPoolComponentBase : public UBasePoolComponent { public: unsigned char UnknownData00[0x8]; // 0x0118(0x0008) MISSED OFFSET class UClass* PooledParticleSystemComponentClass; // 0x0120(0x0008) (ZeroConstructor, Transient, IsPlainOldData) TArray<class UParticleSystemComponent*> UnusedComponentsArray; // 0x0128(0x0010) (ExportObject, ZeroConstructor) unsigned char UnknownData01[0x50]; // 0x0138(0x0050) UNKNOWN PROPERTY: SetProperty SceneComponentPools.ParticleSystemPoolComponentBase.UsedComponentsSet class UParticleSystemComponent* PeekedParticleSystemComponent; // 0x0188(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData) bool bClearTemplateWhenReturnedToPool; // 0x0190(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData02[0x7]; // 0x0191(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.ParticleSystemPoolComponentBase"); return ptr; } void OnPSCFinished(class UParticleSystemComponent** InPSC); }; // Class SceneComponentPools.ParticleSystemPoolComponent // 0x0000 (0x0198 - 0x0198) class UParticleSystemPoolComponent : public UParticleSystemPoolComponentBase { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.ParticleSystemPoolComponent"); return ptr; } }; // Class SceneComponentPools.PoolableDecalComponent // 0x0030 (0x02E0 - 0x02B0) class UPoolableDecalComponent : public UDecalComponent { public: unsigned char UnknownData00[0x18]; // 0x02B0(0x0018) MISSED OFFSET struct FScriptMulticastDelegate OnDecalReturnedToPoolDelegate; // 0x02C8(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) bool bInUse; // 0x02D8(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x7]; // 0x02D9(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.PoolableDecalComponent"); return ptr; } void ForceReturnToPool(); }; // Class SceneComponentPools.SceneComponentPoolStatics // 0x0000 (0x0028 - 0x0028) class USceneComponentPoolStatics : public UBlueprintFunctionLibrary { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class SceneComponentPools.SceneComponentPoolStatics"); return ptr; } class UParticleSystemComponent* STATIC_SpawnEmitterAttached(class UParticleSystem** EmitterTemplate, class USceneComponent** AttachToComponent, struct FName* AttachPointName, struct FVector* Location, struct FRotator* Rotation, struct FVector* Scale, TEnumAsByte<EAttachLocation>* LocationType); class UParticleSystemComponent* STATIC_SpawnEmitterAtLocation(class UObject** WorldContextObject, class UParticleSystem** EmitterTemplate, struct FVector* Location, struct FRotator* Rotation, struct FVector* Scale); class UPoolableDecalComponent* STATIC_SpawnDecalAttached(class UMaterialInterface** DecalMaterial, struct FVector* DecalSize, class USceneComponent** AttachToComponent, struct FName* AttachPointName, struct FVector* Location, struct FRotator* Rotation, TEnumAsByte<EAttachLocation>* LocationType, float* LifeSpan); class UPoolableDecalComponent* STATIC_SpawnDecalAtLocation(class UObject** WorldContextObject, class UMaterialInterface** DecalMaterial, struct FVector* DecalSize, struct FVector* Location, struct FRotator* Rotation, float* LifeSpan); void STATIC_ReleaseSpawnedEmitters(class UObject** WorldContextObject); void STATIC_ReleaseSpawnedDecals(class UObject** WorldContextObject); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
e08580d2fb0ec4a21c30cda224accb9f57cef736
e7a918f81acb6eeda6166b06637f520ca314d80b
/BabyYodaAdventures/BabyYodaAdventures/BabyYoda.hpp
008ef56273136894ca4c913b4f024dc3fde230b2
[]
no_license
larvailor/BabyYodaAdventures
1bee5100302c6966102e17a72c83701c278a2f18
8aca4d4bad97715348e5326c2cad21a8ca6983c3
refs/heads/master
2020-12-03T19:43:37.002929
2020-02-07T14:17:35
2020-02-07T14:17:35
231,459,728
0
1
null
2020-01-04T10:37:34
2020-01-02T21:07:29
C++
UTF-8
C++
false
false
1,441
hpp
BabyYoda.hpp
#ifndef BABY_YODA_HPP #define BABY_YODA_HPP #include "Entity.hpp" class BabyYoda : public Entity { private: ///////////////////////////////////////////////// // // Methods // ///////////////////////////////////////////////// //----------------------------------------------- // Initialization // void initSprite(const float& startX, const float& startY); //----------------------------------------------- // Update // void updateComponents(const float& frameTime); void updateComponentMovement(const float& frameTime); void updateComponentHitbox(); void updateComponentAnimation(const float& frameTime); public: // TODO: move to the attribute component unsigned int m_hp; unsigned int m_killsCounter; ///////////////////////////////////////////////// // // Methods // ///////////////////////////////////////////////// //----------------------------------------------- // Constructors // BabyYoda(const float& startX, const float& startY, shared<sf::Texture>& textureSheet); //----------------------------------------------- // Destructors // ~BabyYoda(); //----------------------------------------------- // Update // void update(const float& frameTime); void move(const DirectionX& dirX, const DirectionY& dirY, const float& frameTime); //----------------------------------------------- // Render // void render(shared<sf::RenderTarget> renderTarget = nullptr); }; #endif
69280ea919fe2475007c280ecbbf9cb95e61ec05
2b5b76f4a98fdba78d89c3b286b107ba51550f10
/2-2/Game/qt_game/mainwindow/GeneratedFiles/ui_multiplaywindow.h
2f802d7217afc473cc1f22c85077516512a21c4a
[]
no_license
Darkseidddddd/project
7e2f3adc6f47188f062a9e1235016752860086dc
9376fd84c0438e5c4dc3d5a8d3cf02b492d5d7ae
refs/heads/master
2020-05-30T10:49:21.209581
2020-02-17T09:49:33
2020-02-17T09:49:33
189,682,072
0
0
null
null
null
null
UTF-8
C++
false
false
16,629
h
ui_multiplaywindow.h
/******************************************************************************** ** Form generated from reading UI file 'multiplaywindow.ui' ** ** Created by: Qt User Interface Compiler version 5.12.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MULTIPLAYWINDOW_H #define UI_MULTIPLAYWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLCDNumber> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QProgressBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QTabWidget> #include <QtWidgets/QTableView> #include <QtWidgets/QTextBrowser> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_multiplaywindow { public: QHBoxLayout *horizontalLayout; QTabWidget *table; QWidget *tab_play; QVBoxLayout *play; QHBoxLayout *horizontalLayout_6; QVBoxLayout *verticalLayout_2; QHBoxLayout *horizontalLayout_9; QLabel *lab_checkpoint; QLCDNumber *lcdNumber; QSpacerItem *verticalSpacer_6; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout_2; QSpacerItem *horizontalSpacer; QLabel *lab_name; QLabel *lab_level; QSpacerItem *horizontalSpacer_2; QHBoxLayout *horizontalLayout_4; QSpacerItem *horizontalSpacer_10; QProgressBar *pg_ex; QSpacerItem *horizontalSpacer_11; QHBoxLayout *horizontalLayout_5; QSpacerItem *horizontalSpacer_12; QTextBrowser *lab_word; QSpacerItem *horizontalSpacer_13; QSpacerItem *verticalSpacer; QLabel *lab_display; QSpacerItem *verticalSpacer_2; QProgressBar *pg_time; QSpacerItem *verticalSpacer_3; QHBoxLayout *horizontalLayout_3; QSpacerItem *horizontalSpacer_3; QLineEdit *le_word; QSpacerItem *horizontalSpacer_4; QPushButton *btn_confirm; QSpacerItem *horizontalSpacer_5; QSpacerItem *verticalSpacer_4; QHBoxLayout *horizontalLayout_7; QSpacerItem *horizontalSpacer_7; QPushButton *btn_start; QSpacerItem *horizontalSpacer_6; QPushButton *btn_restart; QSpacerItem *horizontalSpacer_8; QPushButton *btn_exit; QSpacerItem *horizontalSpacer_9; QSpacerItem *verticalSpacer_5; QWidget *tab_online; QVBoxLayout *verticalLayout_3; QVBoxLayout *verticalLayout_4; QHBoxLayout *horizontalLayout_14; QSpacerItem *horizontalSpacer_22; QPushButton *btn2_update; QTableView *tableView; void setupUi(QDialog *multiplaywindow) { if (multiplaywindow->objectName().isEmpty()) multiplaywindow->setObjectName(QString::fromUtf8("multiplaywindow")); multiplaywindow->resize(700, 650); multiplaywindow->setMaximumSize(QSize(700, 650)); multiplaywindow->setSizeIncrement(QSize(700, 650)); horizontalLayout = new QHBoxLayout(multiplaywindow); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); table = new QTabWidget(multiplaywindow); table->setObjectName(QString::fromUtf8("table")); tab_play = new QWidget(); tab_play->setObjectName(QString::fromUtf8("tab_play")); play = new QVBoxLayout(tab_play); play->setObjectName(QString::fromUtf8("play")); horizontalLayout_6 = new QHBoxLayout(); horizontalLayout_6->setObjectName(QString::fromUtf8("horizontalLayout_6")); verticalLayout_2 = new QVBoxLayout(); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); horizontalLayout_9 = new QHBoxLayout(); horizontalLayout_9->setObjectName(QString::fromUtf8("horizontalLayout_9")); lab_checkpoint = new QLabel(tab_play); lab_checkpoint->setObjectName(QString::fromUtf8("lab_checkpoint")); horizontalLayout_9->addWidget(lab_checkpoint); lcdNumber = new QLCDNumber(tab_play); lcdNumber->setObjectName(QString::fromUtf8("lcdNumber")); horizontalLayout_9->addWidget(lcdNumber); verticalLayout_2->addLayout(horizontalLayout_9); verticalSpacer_6 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_2->addItem(verticalSpacer_6); horizontalLayout_6->addLayout(verticalLayout_2); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); lab_name = new QLabel(tab_play); lab_name->setObjectName(QString::fromUtf8("lab_name")); horizontalLayout_2->addWidget(lab_name); lab_level = new QLabel(tab_play); lab_level->setObjectName(QString::fromUtf8("lab_level")); horizontalLayout_2->addWidget(lab_level); horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer_2); verticalLayout->addLayout(horizontalLayout_2); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); horizontalSpacer_10 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer_10); pg_ex = new QProgressBar(tab_play); pg_ex->setObjectName(QString::fromUtf8("pg_ex")); pg_ex->setValue(24); horizontalLayout_4->addWidget(pg_ex); horizontalSpacer_11 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer_11); verticalLayout->addLayout(horizontalLayout_4); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5")); horizontalSpacer_12 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_5->addItem(horizontalSpacer_12); lab_word = new QTextBrowser(tab_play); lab_word->setObjectName(QString::fromUtf8("lab_word")); lab_word->setEnabled(true); lab_word->setMinimumSize(QSize(350, 100)); lab_word->setMaximumSize(QSize(350, 100)); QFont font; font.setFamily(QString::fromUtf8("Arial")); font.setPointSize(22); font.setBold(false); font.setWeight(50); lab_word->setFont(font); lab_word->setFocusPolicy(Qt::NoFocus); lab_word->setLayoutDirection(Qt::LeftToRight); lab_word->setAutoFillBackground(true); lab_word->setFrameShape(QFrame::StyledPanel); lab_word->setFrameShadow(QFrame::Sunken); lab_word->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); lab_word->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); lab_word->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); lab_word->setTextInteractionFlags(Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse); horizontalLayout_5->addWidget(lab_word); horizontalSpacer_13 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_5->addItem(horizontalSpacer_13); horizontalLayout_5->setStretch(0, 1); horizontalLayout_5->setStretch(2, 1); verticalLayout->addLayout(horizontalLayout_5); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer); lab_display = new QLabel(tab_play); lab_display->setObjectName(QString::fromUtf8("lab_display")); QFont font1; font1.setFamily(QString::fromUtf8("Arial")); font1.setPointSize(11); font1.setBold(true); font1.setWeight(75); lab_display->setFont(font1); lab_display->setLayoutDirection(Qt::LeftToRight); verticalLayout->addWidget(lab_display); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_2); pg_time = new QProgressBar(tab_play); pg_time->setObjectName(QString::fromUtf8("pg_time")); pg_time->setValue(100); verticalLayout->addWidget(pg_time); verticalSpacer_3 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_3); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer_3); le_word = new QLineEdit(tab_play); le_word->setObjectName(QString::fromUtf8("le_word")); le_word->setMinimumSize(QSize(200, 0)); le_word->setMaximumSize(QSize(500, 16777215)); horizontalLayout_3->addWidget(le_word); horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer_4); btn_confirm = new QPushButton(tab_play); btn_confirm->setObjectName(QString::fromUtf8("btn_confirm")); horizontalLayout_3->addWidget(btn_confirm); horizontalSpacer_5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer_5); horizontalLayout_3->setStretch(0, 2); horizontalLayout_3->setStretch(1, 2); horizontalLayout_3->setStretch(2, 2); horizontalLayout_3->setStretch(3, 1); horizontalLayout_3->setStretch(4, 2); verticalLayout->addLayout(horizontalLayout_3); verticalSpacer_4 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_4); horizontalLayout_7 = new QHBoxLayout(); horizontalLayout_7->setObjectName(QString::fromUtf8("horizontalLayout_7")); horizontalSpacer_7 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_7->addItem(horizontalSpacer_7); btn_start = new QPushButton(tab_play); btn_start->setObjectName(QString::fromUtf8("btn_start")); btn_start->setMinimumSize(QSize(100, 30)); horizontalLayout_7->addWidget(btn_start); horizontalSpacer_6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_7->addItem(horizontalSpacer_6); btn_restart = new QPushButton(tab_play); btn_restart->setObjectName(QString::fromUtf8("btn_restart")); btn_restart->setMinimumSize(QSize(100, 30)); horizontalLayout_7->addWidget(btn_restart); horizontalSpacer_8 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_7->addItem(horizontalSpacer_8); btn_exit = new QPushButton(tab_play); btn_exit->setObjectName(QString::fromUtf8("btn_exit")); btn_exit->setMinimumSize(QSize(100, 30)); horizontalLayout_7->addWidget(btn_exit); horizontalSpacer_9 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_7->addItem(horizontalSpacer_9); horizontalLayout_7->setStretch(0, 1); horizontalLayout_7->setStretch(1, 2); horizontalLayout_7->setStretch(2, 4); horizontalLayout_7->setStretch(3, 2); horizontalLayout_7->setStretch(4, 1); horizontalLayout_7->setStretch(5, 2); horizontalLayout_7->setStretch(6, 1); verticalLayout->addLayout(horizontalLayout_7); verticalSpacer_5 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_5); verticalLayout->setStretch(2, 2); verticalLayout->setStretch(3, 2); verticalLayout->setStretch(4, 2); verticalLayout->setStretch(5, 2); verticalLayout->setStretch(6, 2); verticalLayout->setStretch(7, 2); verticalLayout->setStretch(8, 2); verticalLayout->setStretch(9, 2); verticalLayout->setStretch(10, 2); verticalLayout->setStretch(11, 2); horizontalLayout_6->addLayout(verticalLayout); play->addLayout(horizontalLayout_6); table->addTab(tab_play, QString()); tab_online = new QWidget(); tab_online->setObjectName(QString::fromUtf8("tab_online")); verticalLayout_3 = new QVBoxLayout(tab_online); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); verticalLayout_4 = new QVBoxLayout(); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); horizontalLayout_14 = new QHBoxLayout(); horizontalLayout_14->setObjectName(QString::fromUtf8("horizontalLayout_14")); horizontalSpacer_22 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_14->addItem(horizontalSpacer_22); btn2_update = new QPushButton(tab_online); btn2_update->setObjectName(QString::fromUtf8("btn2_update")); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(btn2_update->sizePolicy().hasHeightForWidth()); btn2_update->setSizePolicy(sizePolicy); btn2_update->setMinimumSize(QSize(0, 20)); horizontalLayout_14->addWidget(btn2_update); horizontalLayout_14->setStretch(0, 4); horizontalLayout_14->setStretch(1, 2); verticalLayout_4->addLayout(horizontalLayout_14); tableView = new QTableView(tab_online); tableView->setObjectName(QString::fromUtf8("tableView")); verticalLayout_4->addWidget(tableView); verticalLayout_3->addLayout(verticalLayout_4); table->addTab(tab_online, QString()); horizontalLayout->addWidget(table); retranslateUi(multiplaywindow); table->setCurrentIndex(1); QMetaObject::connectSlotsByName(multiplaywindow); } // setupUi void retranslateUi(QDialog *multiplaywindow) { multiplaywindow->setWindowTitle(QApplication::translate("multiplaywindow", "Dialog", nullptr)); lab_checkpoint->setText(QApplication::translate("multiplaywindow", "\345\205\263\345\215\241:", nullptr)); lab_name->setText(QString()); lab_level->setText(QString()); lab_word->setHtml(QApplication::translate("multiplaywindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'Arial'; font-size:22pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>", nullptr)); lab_display->setText(QString()); btn_confirm->setText(QApplication::translate("multiplaywindow", "\347\241\256\345\256\232", nullptr)); btn_start->setText(QApplication::translate("multiplaywindow", "\345\207\206\345\244\207", nullptr)); btn_restart->setText(QApplication::translate("multiplaywindow", "\350\277\224\345\233\236", nullptr)); btn_exit->setText(QApplication::translate("multiplaywindow", "\351\200\200\345\207\272", nullptr)); table->setTabText(table->indexOf(tab_play), QApplication::translate("multiplaywindow", "play", nullptr)); btn2_update->setText(QApplication::translate("multiplaywindow", "\345\210\267\346\226\260", nullptr)); table->setTabText(table->indexOf(tab_online), QApplication::translate("multiplaywindow", "\345\275\223\345\211\215\345\234\250\347\272\277", nullptr)); } // retranslateUi }; namespace Ui { class multiplaywindow: public Ui_multiplaywindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MULTIPLAYWINDOW_H
378bce2282584940592760447c314e61849d0626
228812957d65d1bdbb55261d5e6cecbdd4b7631c
/TopCoderSeason3/CrazyBot20161209.cpp
e66c285a160141cb05612e9153c1de8f043ccb8e
[]
no_license
eungmo/Algorithms
33136b4e3ca61fa0289b68e3ebb34bc4f1cfbafc
568b34721f68917055a68eb2945818098db9632b
refs/heads/master
2020-06-10T04:19:00.661650
2017-01-12T09:19:14
2017-01-12T09:19:14
76,089,106
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
CrazyBot20161209.cpp
#include <iostream> using namespace std; bool matrix[29][29] = {false, }; double dProb[4]; int vx[4] = {1, -1, 0, 0}; int vy[4] = {0, 0, -1, 1}; class CrazyBot { public: double getProbability(int n, int east, int west, int south, int north) { double probaility = 0.0; // caculate direction's probabilities; dProb[0] = east / 100.0; dProb[1] = west / 100.0; dProb[2] = south / 100.0; dProb[3] = north / 100.0; // caculate all probability probaility = dfs(n, 14, 14); return probaility; } double dfs(int n, int x, int y) { double probability = 0.0; // fail condition if (x < 0 || y < 0 || x > 28 || y > 28 || matrix[y][x] == true) { return 0; } // success condition if (n == 0) return 1; // step current step matrix[y][x] = true; // sum 4 direction of probability for (int i=0; i<4; i++) { probability += dProb[i] * dfs(n-1, x + vx[i], y + vy[i]); } // remove step matrix[y][x] = false; return probability; } }; int main(void) { int n, east, west, south, north; CrazyBot cb; //n = 1; east = 25, west = 25, south = 25, north = 25; //n = 2; east = 25, west = 25, south = 25, north = 25; //n = 7; east = 50, west = 0, south = 0, north = 50; //n = 14; east = 50, west = 50, south = 0, north = 0; n = 14; east = 25, west = 25, south = 25, north = 25; cout << cb.getProbability(n, east, west, south,north) << endl; return 0; }
ed863d209b0919d04d92c6d3526557c44aa86141
dacff6ccba4a485ffff6edea6cdfed94bb17f0cf
/source.h
65645b9d3f99bda49747e4cfe93897df6aa55297
[ "MIT" ]
permissive
mras0/solve
9c4f43d28e37b766e25896ea874a9dcf88cb2569
b9081c1e1f532511f38ceea696d52601a12d7342
refs/heads/master
2021-01-01T17:15:43.654797
2014-11-30T22:29:49
2014-11-30T22:34:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,332
h
source.h
#ifndef SOLVE_SOURCE_H #define SOLVE_SOURCE_H #include <string> #include <iosfwd> namespace source { class file { public: explicit file(const std::string& filename, const std::string& contents) : filename_(filename), contents_(contents) { } const std::string& filename() const { return filename_; } const char* data() const { return contents_.c_str(); } size_t length() const { return contents_.length(); } private: const std::string filename_; const std::string contents_; file(const file& s) = delete; file& operator=(const file& s) = delete; }; class position { public: position(const file& source); position(const file& source, size_t line, size_t col, size_t index); const file& source() const { return *source_; } size_t line() const { return line_; } size_t col() const { return col_; } size_t index() const { return index_; } const char* data() const { return source().data() + index(); } position advanced_n(size_t n) const; position advanced_ws(char ch) const; private: const file* source_; size_t line_; size_t col_; size_t index_; }; bool operator<(const position& a, const position& b); std::ostream& operator<<(std::ostream& os, const position& pos); } // namespace source #endif
60688a235e0a1c1b77ff7d825cc6886bf4d2ce7f
c6114798112d8c4c6b7fd8e7c8dbf31d11301bf0
/洛谷代码存放/新手村/P1909.cpp
6a53513df35bf5f71a3eb3a45f5ae1d80961f7a6
[]
no_license
jiangtao1234ji/ACM-code
fb2b321d116a5f61b7771a8086862f886ed61935
b549bbdf0aae7214e840ab0e15f9e484c5494781
refs/heads/master
2020-04-16T02:58:47.307497
2019-03-10T05:53:00
2019-03-10T05:53:00
165,215,632
1
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
P1909.cpp
#include<iostream> #include<string> #include<algorithm> #include<cmath> using namespace std; int main() { int num; cin>>num; int a, b, ans = 100000000, c; for(int i=0; i<3; ++i) { cin>>a>>b; c = ceil(num*1.0/a)*b; ans = min(c, ans); } cout<<ans<<endl; return 0; }
e85b19de92da22e84499bd318bfa20ff02a91107
96c36c3e498ee48cf42176a76c2505003cedb609
/lab12/processHistory.cpp
1c643e5e3157ccb0f8b31af1069c381944228f50
[]
no_license
pawelrosada/PO
133ab180a5c7a238883498ede20ac5e3dd554066
00eca9ce538ac3c41aef4c01de1b56102912309f
refs/heads/master
2021-01-01T05:44:01.847073
2016-04-19T15:09:50
2016-04-19T15:09:50
56,606,880
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
cpp
processHistory.cpp
#include <iostream> #include <map> using namespace std; #include "process.h" #include "processManager.h" #include "processHistory.h" extern std::string intToStr(int n); void ProcessHistory::addProcessHistory(unsigned int processID, ProcessState state) { std::map<int,string>::iterator it = processesHistory.begin(); while(it != processesHistory.end()) { if(it->first == processID) { switch(state) { case PROCESS_WORKING: it->second += "W"; break; case PROCESS_STOPPED: it->second += "S"; break; case PROCESS_FINISHED: it->second += "F"; break; } } else { if(it->second.empty() == false && (/*it->second.back() == 'W' ||*/ it->second.back() == 'F')) it->second += "F"; else it->second += "S"; } ++it; } } bool ProcessHistory::createProcessHistory(unsigned int processID) { std::map<int,string>::iterator it = processesHistory.find(processID); if(it != processesHistory.end()) { cout << "ProcessHistory::Error - can't create process history, allready exist, pid: " << processID << endl; return false; } else processesHistory.insert(std::pair<int,string>(processID,"")); return true; } string ProcessHistory::getAllEntries() { std::string entries = ""; std::map<int,string>::iterator it = processesHistory.begin(); while(it != processesHistory.end()) { if(it->first < 10) entries += "0"; entries += intToStr(it->first); entries += ": "; entries += it->second; entries += "\n"; ++it; } return entries; } void ProcessHistory::clear() { processesHistory.clear(); }
519a18ecdf8c886b1c3e9249cbb186095a145945
7bc99add5ba003f810885a8bde96c5b0f3dc5d0c
/examples/tcp-example/echo-client.cpp
8ad2e88ee3a873f24c50394e875b6a435accf89c
[ "Apache-2.0" ]
permissive
Dnnd/cpp-tp-advanced
5b64496d949f87341b47c42e571183ff5cfd23cb
21bbf539b9c935810300dabb9136098899b5eedf
refs/heads/master
2022-10-01T17:18:59.569132
2020-06-01T19:13:41
2020-06-01T19:13:41
247,796,585
2
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
echo-client.cpp
#include "cli.hpp" #include "tcp/connection.hpp" #include <cstdlib> #include <iostream> int main(int argc, char **argv) { Config cfg = parse_cli_opts(argc, argv); tcp::Connection con{cfg.hostname, cfg.port}; std::string out_buffer; std::string in_buffer; while (std::cin) { std::getline(std::cin, out_buffer); con.writeExact(out_buffer.c_str(), out_buffer.size()); in_buffer.resize(out_buffer.size(), '\0'); con.readExact(in_buffer.data(), in_buffer.size()); std::cout << "Read: " << in_buffer << '\n'; } return EXIT_SUCCESS; }
09b3cbde857cc28c6392c56e361ab4fa81f008d9
f703bebbc497e6c91b8da9c19d26cbcc98a897fb
/CodeForces.com/regular_rounds/#345/C/b.cpp
9705df0075326a3f6af64eef171da8c85447205c
[ "MIT" ]
permissive
mstrechen/competitive-programming
1dc48163fc2960c54099077b7bfc0ed84912d2c2
ffac439840a71f70580a0ef197e47479e167a0eb
refs/heads/master
2021-09-22T21:09:24.340863
2018-09-16T13:48:51
2018-09-16T13:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
b.cpp
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstring> #include <set> #include <fstream> using namespace std; #define ll long long #define type int type min(type a, type b) { return (a>b)?b:a; } type max(type a, type b) { return (a>b)?a:b; } void swap(type &a, type &b) { type t=a; a=b; b=t; return; } type gcd (type a, type b) { while(b) { a%=b; swap(a,b); } return a; } type lcm(type a, type b) { return (a/gcd(a,b))*b; } type abs(type a) { return (a>0)?a:-a; } void files() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); } int main() { freopen("a.txt", "r", stdin); int n; scanf("%d",&n); vector<int>a(n,0); int x; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } sort(a.begin(),a.end()); int res=0,temp=0,te=1; while(a.size()>0) { temp=a[0]; te=1; a.erase(a.begin()); for(int i=0;i<a.size();i++) { if(a[i]>temp) { temp=a[i]; a.erase(a.begin()+i); i--; te++; } } res+=te-1; } printf("%d",res); }
e15222c718b48974b5bfcb1479e833ef7b91dda6
ec98c3ff6cf5638db5c590ea9390a04b674f8f99
/components/HaplotypeFrequencyComponent/src/HaplotypeFrequencyLogLikelihood.cpp
07ed6d47fa75b287530691b4fe0e9b3c5a5f0a75
[ "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
gavinband/qctool
37e1122d61555a39e1ae6504e4ca1c4d75f371e9
8d8adb45151c91f953fe4a9af00498073b1132ba
refs/heads/master
2023-06-22T07:16:36.897058
2021-11-13T00:12:26
2021-11-13T00:12:26
351,933,501
6
2
BSL-1.0
2023-06-12T14:13:57
2021-03-26T23:04:52
C++
UTF-8
C++
false
false
5,360
cpp
HaplotypeFrequencyLogLikelihood.cpp
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <string> #include <iomanip> #include <boost/math/distributions/binomial.hpp> #include <boost/function.hpp> #include <Eigen/Core> #include "genfile/Error.hpp" #include "components/HaplotypeFrequencyComponent/HaplotypeFrequencyComponent.hpp" // #define DEBUG_HAPLOTYPE_FREQUENCY_LL 1 HaplotypeFrequencyLogLikelihood::HaplotypeFrequencyLogLikelihood( Matrix const& genotype_table, Matrix const& haplotype_table ): m_genotype_table( genotype_table ), m_haplotype_table( haplotype_table ), m_D_ll( 3 ), m_DDt_ll( 3, 3 ) { if( m_genotype_table.array().maxCoeff() == 0 && m_haplotype_table.array().maxCoeff() == 0 ) { throw genfile::BadArgumentError( "HaplotypeFrequencyLogLikelihood::HaplotypeFrequencyLogLikelihood()", "genotype_table, haplotype_table" ) ; } // store derivatives of elements of the parameters pi with respect to pi. m_dpi.push_back( std::vector< RowVector >( 2, RowVector::Zero( 3 ) )) ; m_dpi.push_back( std::vector< RowVector >( 2, RowVector::Zero( 3 ) )) ; m_dpi[0][0] = RowVector::Constant( 3, -1 ) ; m_dpi[0][1]( 0 ) = 1 ; m_dpi[1][0]( 1 ) = 1 ; m_dpi[1][1]( 2 ) = 1 ; } HaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::get_MLE_by_EM() const { // // This method treats the number of individuals X in the G(1,1) cell // that have AB/ab genotypes as binomially distributed with some unknown // parameter p that must be estimated. We pick a value of p and sum over // possible values of X to get a new estimate of the four parameters // pi00, pi01, pi10, pi11. Then p is re-computed from the parameter values. // // We stop when the parameter estimate does not change, up to some tolerance. // Matrix const& G = m_genotype_table ; Vector pi = estimate_parameters( 0.5 ) ; #if DEBUG_HAPLOTYPE_FREQUENCY_LL std::cerr << std::resetiosflags( std::ios::floatfield ) << "Maximising likelihood for genotypes:\n" << m_genotype_table << "\nand haplotypes:\n" << m_haplotype_table << "\n" ; std::cerr << "pi = " << pi(0) << " " << pi(1) << " " << pi(2) << " " << pi(3) << " " << ", p = 0.5.\n" ; #endif if( G(1,1) != 0.0 ) { Vector old_pi ; std::size_t count = 0 ; std::size_t const max_count = 100000 ; double const tolerance = 0.0000001 ; do { old_pi = pi ; double p = ( pi(0) * pi( 3 ) ) ; if( p != 0 ) { p = p / ( p + ( pi( 1 ) * pi( 2 )) ) ; } pi = estimate_parameters( p ) ; #if DEBUG_HAPLOTYPE_FREQUENCY_LL std::cerr << "pi = " << pi(0) << " " << pi(1) << " " << pi(2) << " " << pi(3) << " " << ", p = " << p << ".\n" ; #endif } while( ( pi - old_pi ).array().abs().maxCoeff() > tolerance && ++count < max_count ) ; if( count == max_count ) { throw genfile::OperationFailedError( "HaplotypeFrequencyLogLikelihood::maximise_by_EM()", "object of type HaplotypeFrequencyLogLikelihood", "convergence" ) ; } } return pi.tail( 3 ) ; } HaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::estimate_parameters( double const p ) const { Matrix const& G = m_genotype_table ; Matrix const& H = m_haplotype_table ; // p is proportion of het / het genotypes // that are due to 00+11 haplotype combinations. double expected_00_11 = G( 1, 1 ) * p ; double expected_01_10 = G( 1, 1 ) - expected_00_11; // params are pi00 pi01 pi10 pi11 Vector result( 4 ) ; result << H(0,0) + G( 0, 1 ) + 2 * G( 0, 0 ) + G( 1, 0 ) + expected_00_11, H(0,1) + G( 0, 1 ) + 2 * G( 0, 2 ) + G( 1, 2 ) + expected_01_10, H(1,0) + G( 2, 1 ) + 2 * G( 2, 0 ) + G( 1, 0 ) + expected_01_10, H(1,1) + G( 1, 2 ) + 2 * G( 2, 2 ) + G( 2, 1 ) + expected_00_11 ; result /= result.sum() ; return result ; } void HaplotypeFrequencyLogLikelihood::evaluate_at( Vector const& pi ) { double const pi00 = 1.0 - pi.sum() ; double const& pi01 = pi(0) ; double const& pi10 = pi(1) ; double const& pi11 = pi(2) ; using std::log ; double const lpi00 = log( pi00 ) ; double const lpi01 = log( pi01 ) ; double const lpi10 = log( pi10 ) ; double const lpi11 = log( pi11 ) ; double het_probability = pi00 * pi11 + pi01 * pi10 ; Matrix const& G = m_genotype_table ; Matrix const& H = m_haplotype_table ; Matrix VG( 3, 3 ) ; VG << 2.0 * lpi00, lpi00 + lpi01, 2.0 * lpi01, lpi00 + lpi10, log( het_probability ), lpi01 + lpi11, 2.0 * lpi10, lpi10 + lpi11, 2.0 * lpi11 ; Matrix VH( 2, 2 ) ; VG << lpi00, lpi01, lpi10, lpi11 ; // cells with count 0 contribute 0 to the loglikelihood/ // Since log(0) = -inf we have to handle this specially. // We do this by replacing these parameter entries with 0. VG = VG.array() * ( G.array() > 0.0 ).cast< double >() ; VH = VH.array() * ( H.array() > 0.0 ).cast< double >() ; m_ll = ( (G.array() * VG.array()) + (H.array() * VH.array()) ).sum() ; } double HaplotypeFrequencyLogLikelihood::get_value_of_function() const { return m_ll ; } HaplotypeFrequencyLogLikelihood::Vector HaplotypeFrequencyLogLikelihood::get_value_of_first_derivative() { assert(0) ; return m_D_ll ; } HaplotypeFrequencyLogLikelihood::Matrix HaplotypeFrequencyLogLikelihood::get_value_of_second_derivative() { assert(0) ; return m_DDt_ll ; }
629ae775bd42c2f90339e51144dd15d95af10efa
c22b3b90b8979d119640b353ac8725e9d20d3c92
/VKTS_PKG_Scenegraph/include/vkts/scenegraph/scene/IPhongMaterial.hpp
6663382ff4f33eb4bde8c0d127c2a478bfe1fd38
[]
no_license
zomeelee/Vulkan-1
dff543e264f7b4b5e871ebc128fedf3bf605ec9e
f1112926d5a6242769034dd25cf03698fa11c7b4
refs/heads/master
2020-06-19T21:35:37.396104
2016-11-26T10:43:21
2016-11-26T10:43:21
74,829,887
1
0
null
2016-11-26T14:16:57
2016-11-26T14:16:56
null
UTF-8
C++
false
false
3,725
hpp
IPhongMaterial.hpp
/** * VKTS - VulKan ToolS. * * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef VKTS_IPHONGMATERIAL_HPP_ #define VKTS_IPHONGMATERIAL_HPP_ #include <vkts/scenegraph.hpp> namespace vkts { class IPhongMaterial : public ICloneable<IPhongMaterial>, public IDestroyable { public: IPhongMaterial() : ICloneable<IPhongMaterial>(), IDestroyable() { } virtual ~IPhongMaterial() { } virtual VkBool32 getForwardRendering() const = 0; virtual const std::string& getName() const = 0; virtual void setName(const std::string& name) = 0; // virtual const ITextureObjectSP& getAlpha() const = 0; virtual void setAlpha(const ITextureObjectSP& alpha) = 0; virtual const ITextureObjectSP& getDisplacement() const = 0; virtual void setDisplacement(const ITextureObjectSP& displacement) = 0; virtual const ITextureObjectSP& getNormal() const = 0; virtual void setNormal(const ITextureObjectSP& normal) = 0; // virtual const ITextureObjectSP& getAmbient() const = 0; virtual void setAmbient(const ITextureObjectSP& ambient) = 0; virtual const ITextureObjectSP& getEmissive() const = 0; virtual void setEmissive(const ITextureObjectSP& emissive) = 0; virtual const ITextureObjectSP& getDiffuse() const = 0; virtual void setDiffuse(const ITextureObjectSP& diffuse) = 0; virtual const ITextureObjectSP& getSpecular() const = 0; virtual void setSpecular(const ITextureObjectSP& specular) = 0; virtual const ITextureObjectSP& getSpecularShininess() const = 0; virtual void setSpecularShininess(const ITextureObjectSP& specularShininess) = 0; virtual const ITextureObjectSP& getMirror() const = 0; virtual void setMirror(const ITextureObjectSP& mirror) = 0; virtual const ITextureObjectSP& getMirrorReflectivity() const = 0; virtual void setMirrorReflectivity(const ITextureObjectSP& mirrorReflectivity) = 0; // virtual VkBool32 isTransparent() const = 0; virtual void setTransparent(const VkBool32 transparent) = 0; // virtual const IDescriptorPoolSP& getDescriptorPool() const = 0; virtual void setDescriptorPool(const IDescriptorPoolSP& descriptorPool) = 0; virtual IDescriptorSetsSP getDescriptorSets() const = 0; virtual void setDescriptorSets(const IDescriptorSetsSP& descriptorSets) = 0; }; typedef std::shared_ptr<IPhongMaterial> IPhongMaterialSP; } /* namespace vkts */ #endif /* VKTS_IPHONGMATERIAL_HPP_ */
8596ed59c4386b773d33264fb378bcc806642442
a0f0efaaaf69d6ccdc2a91596db29f04025f122c
/install/robot_control_msgs/include/robot_control_msgs/robot_ctrl_alarmHistory.h
57cb86e307000acedea7df700f396ef375f56e8f
[]
no_license
chiuhandsome/ros_ws_test-git
75da2723154c0dadbcec8d7b3b1f3f8b49aa5cd6
619909130c23927ccc902faa3ff6d04ae0f0fba9
refs/heads/master
2022-12-24T05:45:43.845717
2020-09-22T10:12:54
2020-09-22T10:12:54
297,582,735
0
0
null
null
null
null
UTF-8
C++
false
false
8,409
h
robot_ctrl_alarmHistory.h
// Generated by gencpp from file robot_control_msgs/robot_ctrl_alarmHistory.msg // DO NOT EDIT! #ifndef ROBOT_CONTROL_MSGS_MESSAGE_ROBOT_CTRL_ALARMHISTORY_H #define ROBOT_CONTROL_MSGS_MESSAGE_ROBOT_CTRL_ALARMHISTORY_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace robot_control_msgs { template <class ContainerAllocator> struct robot_ctrl_alarmHistory_ { typedef robot_ctrl_alarmHistory_<ContainerAllocator> Type; robot_ctrl_alarmHistory_() : system_id() , alarm_id() , alarm_code() , alarm_level() , alarm_occure_time() , update_time() { } robot_ctrl_alarmHistory_(const ContainerAllocator& _alloc) : system_id(_alloc) , alarm_id(_alloc) , alarm_code(_alloc) , alarm_level(_alloc) , alarm_occure_time(_alloc) , update_time(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _system_id_type; _system_id_type system_id; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _alarm_id_type; _alarm_id_type alarm_id; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _alarm_code_type; _alarm_code_type alarm_code; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _alarm_level_type; _alarm_level_type alarm_level; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _alarm_occure_time_type; _alarm_occure_time_type alarm_occure_time; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _update_time_type; _update_time_type update_time; typedef boost::shared_ptr< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> const> ConstPtr; }; // struct robot_ctrl_alarmHistory_ typedef ::robot_control_msgs::robot_ctrl_alarmHistory_<std::allocator<void> > robot_ctrl_alarmHistory; typedef boost::shared_ptr< ::robot_control_msgs::robot_ctrl_alarmHistory > robot_ctrl_alarmHistoryPtr; typedef boost::shared_ptr< ::robot_control_msgs::robot_ctrl_alarmHistory const> robot_ctrl_alarmHistoryConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> & v) { ros::message_operations::Printer< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator1> & lhs, const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator2> & rhs) { return lhs.system_id == rhs.system_id && lhs.alarm_id == rhs.alarm_id && lhs.alarm_code == rhs.alarm_code && lhs.alarm_level == rhs.alarm_level && lhs.alarm_occure_time == rhs.alarm_occure_time && lhs.update_time == rhs.update_time; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator1> & lhs, const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace robot_control_msgs namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > { static const char* value() { return "9b1377e9612e5919160e7b5630dcb6dc"; } static const char* value(const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x9b1377e9612e5919ULL; static const uint64_t static_value2 = 0x160e7b5630dcb6dcULL; }; template<class ContainerAllocator> struct DataType< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > { static const char* value() { return "robot_control_msgs/robot_ctrl_alarmHistory"; } static const char* value(const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > { static const char* value() { return "string system_id \n" "string alarm_id # module_no(3) + module alarm code(3) \n" "string alarm_code # same as alarm_id,preper for special requirement\n" "string alarm_level # level of ararm: 1:alart 2:alarm \n" "string alarm_occure_time # occure time of alarm\n" "string update_time \n" ; } static const char* value(const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.system_id); stream.next(m.alarm_id); stream.next(m.alarm_code); stream.next(m.alarm_level); stream.next(m.alarm_occure_time); stream.next(m.update_time); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct robot_ctrl_alarmHistory_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::robot_control_msgs::robot_ctrl_alarmHistory_<ContainerAllocator>& v) { s << indent << "system_id: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.system_id); s << indent << "alarm_id: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.alarm_id); s << indent << "alarm_code: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.alarm_code); s << indent << "alarm_level: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.alarm_level); s << indent << "alarm_occure_time: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.alarm_occure_time); s << indent << "update_time: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.update_time); } }; } // namespace message_operations } // namespace ros #endif // ROBOT_CONTROL_MSGS_MESSAGE_ROBOT_CTRL_ALARMHISTORY_H
60645b19cf1f95436684e19da2e0f733aac93afc
5cec8b239e562374c9e70b0e9b2a41b0cee79d02
/Practica 3/Ejer9.cpp
b912215e8204f31d4a7b43f529e7068a5117aab4
[]
no_license
garyDav/SIS100
0731797f46a14f8800e6b092c6e289f2a073f927
e8b8332390a17750b7dc87e79f4c4a8b3459cda2
refs/heads/master
2020-03-19T14:58:37.706097
2018-10-23T14:52:34
2018-10-23T14:52:34
136,649,950
0
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
Ejer9.cpp
#include <iostream> using namespace std; int main() { long int lim_inf = 6, lim_sup = 13, fac = 1; for (long int i=lim_inf;i<=lim_sup;i++) { for (long int j=2;j<=i;j++) { fac *= j; } cout<<i<<"! = "<<fac<<endl; fac = 1; } return 0; }
bd405c8dcf8301eb8445f3dee9c1f2c1cff3de44
a48472ece08835eb158a5ebee3d79bfc4f3d1319
/src/square_empty.cpp
a8d55f60b73ed8ac50816f6f6300f96462827e8b
[]
no_license
Ball-Man/GOP
a8b8a7ebfe55a6b9e073a799120afa07c404e35a
5ecb10f058db4d2c8037f1bbe75745342fe1443a
refs/heads/master
2021-05-03T21:12:44.267204
2018-03-21T14:11:29
2018-03-21T14:11:29
120,378,616
1
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
square_empty.cpp
#include "square_empty.h" #include "screen.h" /// *** PUBLIC *** /// SquareEmpty::SquareEmpty(const String& text) : Square(text) { } // A nothing-card does nothing, logical(?) void SquareEmpty::Do(Gameboard& gameboard) const { screen::Wait(); }
d76f0e65188d2f1fbac68bdc8c148c90a6c5b561
6b09fdc05a6c6c756d6525b5bfe12aa2110f2922
/STUB/STRUCTURE/configStruct.hpp
d9825553a3187a63389ff6e3b4049619aaf67cd5
[]
no_license
roysuman/DatabaseStub
fcf3d4b405f272de521cd016946f133ca3817dfe
c7e07ffe2bdb2fd001d6498398a8918798996030
refs/heads/master
2021-01-18T23:00:38.368321
2016-05-12T05:38:31
2016-05-12T05:38:31
25,222,657
0
2
null
null
null
null
UTF-8
C++
false
false
929
hpp
configStruct.hpp
/* * ===================================================================================== * * Filename: configStruct.hpp * * Description: this file maintains all structures required to handle JSON configuration fiel of TCP stub * * Version: 1.0 * Created: Monday 03 March 2014 03:57:09 IST * Revision: none * Compiler: gcc * * Author: Suman Roy (), * Organization: Cognizant Technological solutions * * ===================================================================================== */ #ifndef CONFIGSTRUCT_HPP_ #define CONFIGSTRUCT_HPP_ #include "iostream" //structure for json.cofig file typedef struct _configTcpStub configTcpStub; struct _configTcpStub { bool traceLog; bool errorLog; bool log; std::string dummyServerIp; int dummyServerPort; std::string sniffingIp; int sniffingPort; }; extern configTcpStub configTcpFile; #endif
fdd3ebe432c2225b1a9c9589fcd35047e0996a17
944ff8d4d0c9ddccdad06bafd9a82c65cb885883
/DXFramework/DXFramework.cpp
7130834dcc6c3d6faa3960e5b640d17c6a13fc42
[]
no_license
zww0815/TinyUI
42076206bef37eb22a076d71a06572d9facb932b
1368f5cd2f7278413201ad2e2f5b7a7c693fcddc
refs/heads/master
2020-06-18T06:34:20.152519
2016-11-29T15:07:32
2016-11-29T15:07:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,119
cpp
DXFramework.cpp
#include "stdafx.h" #include "DXFramework.h" #include "Control/TinyControl.h" namespace DXFramework { typedef HANDLE(WINAPI *CREATEREMOTETHREAD)(HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPTHREAD_START_ROUTINE, LPVOID, DWORD, LPDWORD); typedef BOOL(WINAPI *WRITEPROCESSMEMORY)(HANDLE, LPVOID, LPCVOID, SIZE_T, SIZE_T*); typedef LPVOID(WINAPI *VIRTUALALLOCEX)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD); typedef BOOL(WINAPI *VIRTUALFREEEX)(HANDLE, LPVOID, SIZE_T, DWORD); typedef HANDLE(WINAPI *LOADLIBRARY) (DWORD, BOOL, DWORD); BOOL WINAPI InjectLibrary(HANDLE hProcess, const CHAR *pszDLL) { if (!hProcess || !pszDLL) return FALSE; HMODULE hInstance = NULL; HANDLE hThread = NULL; FARPROC lpStartAddress = NULL; DWORD dwSize = strlen(pszDLL); dwSize = (dwSize + 1) * sizeof(CHAR); WRITEPROCESSMEMORY pfnWriteProcessMemory = NULL; CREATEREMOTETHREAD pfnCreateRemoteThread = NULL; VIRTUALALLOCEX pfnVirtualAllocEx = NULL; VIRTUALFREEEX pfnVirtualFreeEx = NULL; INT obfSize = 12; CHAR pWPMSTR[19], pCRTSTR[19], pVAESTR[15], pVFESTR[14], pLLSTR[13]; memcpy(pWPMSTR, "RvnrdPqmni|}Dmfegm", 19); memcpy(pCRTSTR, "FvbgueQg`c{k]`yotp", 19); memcpy(pVAESTR, "WiqvpekGeddiHt", 15); memcpy(pVFESTR, "Wiqvpek@{mnOu", 14); memcpy(pLLSTR, "MobfImethzr", 12); pLLSTR[11] = 'A'; pLLSTR[12] = 0; obfSize += 6; for (INT i = 0; i < obfSize; i++) pWPMSTR[i] ^= i ^ 5; for (INT i = 0; i < obfSize; i++) pCRTSTR[i] ^= i ^ 5; obfSize -= 4; for (INT i = 0; i < obfSize; i++) pVAESTR[i] ^= i ^ 1; obfSize -= 1; for (INT i = 0; i < obfSize; i++) pVFESTR[i] ^= i ^ 1; obfSize -= 2; for (INT i = 0; i < obfSize; i++) pLLSTR[i] ^= i ^ 1; hInstance = GetModuleHandle(TEXT("KERNEL32")); if (!hInstance) return FALSE; pfnWriteProcessMemory = (WRITEPROCESSMEMORY)GetProcAddress(hInstance, pWPMSTR); pfnCreateRemoteThread = (CREATEREMOTETHREAD)GetProcAddress(hInstance, pCRTSTR); pfnVirtualAllocEx = (VIRTUALALLOCEX)GetProcAddress(hInstance, pVAESTR); pfnVirtualFreeEx = (VIRTUALFREEEX)GetProcAddress(hInstance, pVFESTR); if (!pfnWriteProcessMemory || !pfnCreateRemoteThread || !pfnVirtualAllocEx || !pfnVirtualFreeEx) return FALSE; LPVOID pAlloc = (LPVOID)(*pfnVirtualAllocEx)(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!pAlloc) return FALSE; SIZE_T size = 0; BOOL bRes = (*pfnWriteProcessMemory)(hProcess, pAlloc, (LPVOID)pszDLL, dwSize, &size); if (!bRes) goto error; lpStartAddress = (FARPROC)GetProcAddress(hInstance, pLLSTR); if (!lpStartAddress) { bRes = FALSE; goto error; } hThread = (*pfnCreateRemoteThread)(hProcess, NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(lpStartAddress), pAlloc, 0, 0); if (!hThread) { bRes = FALSE; goto error; } if (WaitForSingleObject(hThread, 200) == WAIT_OBJECT_0) { DWORD dw; GetExitCodeThread(hThread, &dw); bRes = dw != 0; } error: if (hThread) { CloseHandle(hThread); hThread = NULL; } if (pAlloc) { (*pfnVirtualFreeEx)(hProcess, pAlloc, 0, MEM_RELEASE); pAlloc = NULL; } return bRes; } }
fc3c2eb9ec77743ed21f2968b454030a9018865e
5df6820e5a79c5f0965a5aee85e32b4b7ade0e01
/Libnorsim_helpers.cpp
503fd24a62e4b18412ef57cf9b35caabbae40056
[]
no_license
obeny/libnorsim
e8b764f61185ae885171fd0aaee61b2ee8ade5e6
e7222e0e098c49db45be0e6df8a6c096392fb072
refs/heads/master
2020-12-04T01:43:11.482566
2016-10-12T15:00:40
2016-10-12T15:00:40
67,953,718
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
Libnorsim_helpers.cpp
unsigned long get_min(unsigned long g, unsigned long p) { unsigned long t = (0 != p); return ((t<=g)?(t):(g)); } unsigned long get_max(unsigned long g, unsigned long p) { return ((p>g)?(p):(g)); }
ee049abb8cc5c5bc8fd8865781af8901d97085dd
1c582ee9eb4fd2afb7b86d8a2b7bffb43ed1aaf3
/src/Dataset.cpp
6c8c918572c39675dc17de72b79efbc9031d42c1
[]
no_license
hunterluok/my_deeplearning
28229faf17cddae09418dea5d40151768da26862
df912862f382610b147a6da6f5182111aadf6061
refs/heads/master
2020-03-11T12:16:48.104211
2017-07-04T09:14:04
2017-07-04T09:14:04
129,993,012
1
0
null
2018-04-18T02:37:20
2018-04-18T02:37:19
null
UTF-8
C++
false
false
10,413
cpp
Dataset.cpp
#include "Dataset.h" #include <iostream> #include <cstring> #include <cstdlib> using namespace std; Dataset::Dataset(){ numFeature =0; numLabel=0; numTrain=0; numValid=0; trainData=validData=trainLabel=validLabel=NULL; } void Dataset::dumpTrainData(const char * savefile){ dumpData(savefile, numTrain, trainData, trainLabel); } void Dataset::dumpData(const char *savefile, int numData, double*data, double * label){ FILE *fp=fopen(savefile,"wb+"); if(fp == NULL){ printf("file can not open: %s\n", savefile); exit(1); } fwrite(&numData, sizeof(int), 1, fp); fwrite(&numFeature, sizeof(int), 1, fp); fwrite(&numLabel, sizeof(int), 1, fp); if(data != NULL) fwrite(data, sizeof(double), numData*numFeature, fp); if(label != NULL) fwrite(label, sizeof(double), numData*numLabel, fp); fclose(fp); } Dataset::~Dataset(){ delete[] trainData; delete[] trainLabel; delete[] validData; delete[] validLabel; } SubDataset Dataset::getTrainDataset(){ return SubDataset(numTrain, numFeature, numLabel, trainData, trainLabel); } SubDataset Dataset::getValidDataset(){ return SubDataset(numValid, numFeature, numLabel, validData, validLabel); } int BatchIterator::getRealBatchSize(){ if(cur==(size-1)) return data->numSample - batchSize*cur; else return batchSize; } bool BatchIterator::isDone(){ if(cur<size) return 0; else return 1; } void MNISTDataset::loadData(const char* DataFileName, const char* LabelFileName){ int magicNum,numImage, numRow, numCol; uint8_t pixel, label; FILE *dataFile = fopen(DataFileName, "rb"); if(dataFile == NULL){ printf("can not open file : %s\n", DataFileName); exit(1); } printf("load data ...\n"); fread(&magicNum, sizeof(int),1, dataFile); magicNum = changeEndian(magicNum); printf("magic number: %d\n", magicNum); fread(&numImage, sizeof(int),1, dataFile); numImage = changeEndian(numImage); printf("number of image: %d\n", numImage); fread(&numRow, sizeof(int),1, dataFile); numRow = changeEndian(numRow); printf("number of rows: %d\n", numRow); fread(&numCol, sizeof(int),1, dataFile); numCol = changeEndian(numCol); printf("number of cols: %d\n", numCol); numFeature = numRow*numCol; numValid = numImage/6; numTrain = numImage - numValid; trainData = new double[numTrain*numFeature]; validData = new double[numValid*numFeature]; for(int i=0; i<numTrain; ++i){ for(int j=0; j<numFeature; ++j){ fread(&pixel, sizeof(uint8_t),1 ,dataFile); trainData[numFeature*i+j] = double(pixel)/255.0; } } for(int i=0; i<numValid; ++i){ for(int j=0; j<numFeature; ++j){ fread(&pixel, sizeof(uint8_t),1 ,dataFile); validData[numFeature*i+j] = double(pixel)/255.0; } } fclose(dataFile); FILE* labelFile = fopen(LabelFileName, "rb"); if(labelFile == NULL){ printf("can not open file : %s\n", LabelFileName); exit(1); } fread(&magicNum, sizeof(int),1 ,labelFile); magicNum = changeEndian(magicNum); printf("number of magic: %d\n", magicNum); fread(&numImage, sizeof(int),1 ,labelFile); numImage = changeEndian(numImage); printf("number of image: %d\n", numImage); numLabel=10; trainLabel = new double [numTrain*numLabel]; validLabel = new double [numValid*numLabel]; memset(trainLabel, 0, numTrain*numLabel*sizeof(double)); memset(validLabel, 0, numValid*numLabel*sizeof(double)); for(int i=0; i<numTrain; ++i){ fread(&label, sizeof(uint8_t), 1, labelFile); trainLabel[i*numLabel+label]=1.0; } for(int i=0; i<numValid; ++i){ fread(&label, sizeof(uint8_t), 1, labelFile); validLabel[i*numLabel+label]=1.0; } fclose(labelFile); printf("load done\n"); } void BinDataset::loadData(const char *DataFileName, const char *LabelFileName){ uint8_t label; FILE *trainDataFd = fopen(DataFileName, "rb"); printf("loading training data...\n"); fread(&numTrain, sizeof(int), 1, trainDataFd); printf("number of training sample : %d\n", numTrain); fread(&numValid, sizeof(int), 1, trainDataFd); printf("number of validate sample : %d\n", numValid); fread(&numFeature, sizeof(int), 1, trainDataFd); printf("number of feature : %d\n", numFeature); trainData = new double[numTrain*numFeature]; validData = new double[numValid*numFeature]; for(int i = 0; i < numTrain; i++) for(int j = 0; j < numFeature; j++){ fread(&trainData[numFeature*i+j], sizeof(double), 1, trainDataFd); } for(int i = 0; i < numValid; i++) for(int j = 0; j < numFeature; j++){ fread(&validData[numFeature*i+j], sizeof(double), 1, trainDataFd); } fclose(trainDataFd); printf("loading training label...\n"); FILE *trainLabelFd = fopen(LabelFileName, "rb"); fread(&numLabel, sizeof(int), 1, trainLabelFd); printf("number of label : %d\n", numLabel); trainLabel = new double[numTrain*numLabel]; validLabel = new double[numValid*numLabel]; memset(trainLabel, 0, numTrain*numLabel*sizeof(double)); memset(validLabel, 0, numValid*numLabel*sizeof(double)); for(int i = 0; i < numTrain; i++){ fread(&label, sizeof(uint8_t), 1, trainLabelFd); trainLabel[i*numLabel+label] = 1.0; } for(int i = 0; i < numValid; i++){ fread(&label, sizeof(uint8_t), 1, trainLabelFd); validLabel[i*numLabel+label] = 1.0; } fclose(trainLabelFd); printf("loading ok...\n"); } void SVMDataset::loadData(const char* trainDataFileName, const char * validDataFileName){ char line[40000]; char *saveptr1; char *saveptr2; FILE *fp = fopen(trainDataFileName, "r"); fscanf(fp, "%d", &numTrain); fscanf(fp, "%d", &numFeature); fscanf(fp, "%d", &numLabel); printf("numTrain: %d, numFeature: %d, numLabel: %d\n", numTrain, numFeature, numLabel); trainData = new double[numTrain*numFeature]; trainLabel = new double[numTrain*numLabel]; memset(trainData, 0, numTrain*numFeature*sizeof(double)); memset(trainLabel, 0, numTrain*numLabel*sizeof(double)); for(int i=0; i<numTrain; ++i){ fgets(line, 40000, fp); char * token = strtok_r(line, " ", &saveptr1); int label = atoi(token)-1; trainLabel[i*numLabel + label] = 1.0; if(saveptr1[0]!='\n'){ while((token=strtok_r(NULL, " ", &saveptr1))!=NULL){ int index; double value; sscanf(token, "%d:%lf", &index, &value); trainData[i*numFeature + index-1] = value; } } } fclose(fp); fp = fopen(validDataFileName, "r"); fscanf(fp, "%d", &numValid); fscanf(fp, "%d", &numFeature); fscanf(fp, "%d", &numLabel); printf("numValidate: %d, numFeature: %d, numLabel: %d\n", numValid, numFeature, numLabel); validData = new double[numValid*numFeature]; validLabel = new double[numValid*numLabel]; memset(validData, 0, numValid*numFeature*sizeof(double)); memset(validLabel, 0, numValid*numLabel*sizeof(double)); for(int i=0; i<numValid; ++i){ fgets(line, 40000, fp); char * token = strtok_r(line, " ", &saveptr1); int label = atoi(token)-1; validLabel[i*numLabel + label] = 1.0; if(saveptr1[0]!='\n'){ while((token=strtok_r(NULL, " ", &saveptr1))!=NULL){ int index; double value; sscanf(token, "%d:%lf", &index, &value); validData[i*numFeature + index-1] = value; } } } fclose(fp); } TransmissionDataset::TransmissionDataset(Dataset *data, IModel* model){ numTrain = data->getTrainNumber(); numValid = data->getValidNumber(); numFeature = model->getOutputNumber(); numLabel = data->getLabelNumber(); trainData = new double[numTrain*numFeature]; validData = new double[numValid*numFeature]; trainLabel = new double[numTrain*numLabel]; validLabel = new double[numValid*numLabel]; SubDataset tmpData; int batchSize = 10; //train data tmpData = data->getTrainDataset(); BatchIterator *iter = new BatchIterator(&tmpData, batchSize); for( iter->first(); !iter->isDone(); iter->next()){ int theBatchSize = iter->getRealBatchSize(); int maskInd = iter->getCurrentIndex(); model->setBatchSize(theBatchSize); model->setInput(iter->getCurrentDataBatch()); model->runBatch(); memcpy(trainData + maskInd*numFeature*batchSize, model->getOutput(), numFeature*theBatchSize*sizeof(double)); } delete iter; //valid data tmpData = data->getValidDataset(); iter = new BatchIterator(&tmpData, batchSize); for( iter->first(); !iter->isDone(); iter->next()){ int theBatchSize = iter->getRealBatchSize(); int maskInd = iter->getCurrentIndex(); model->setBatchSize(theBatchSize); model->setInput(iter->getCurrentDataBatch()); model->runBatch(); memcpy(validData + maskInd*numFeature*batchSize, model->getOutput(), numFeature*theBatchSize*sizeof(double)); } delete iter; // label memcpy(trainLabel, data->getTrainLabelBatch(0), numTrain*numLabel*sizeof(double)); memcpy(validLabel, data->getValidLabelBatch(0), numValid*numLabel*sizeof(double)); } MergeDataset::MergeDataset(Dataset * originDatas[], int numSets){ numFeature = 0; numLabel = originDatas[0]->getLabelNumber(); numTrain = originDatas[0]->getTrainNumber(); numValid = originDatas[0]->getValidNumber(); for(int i=0; i<numSets; i++){ numFeature += originDatas[i] -> getFeatureNumber(); } trainData = new double[numTrain*numFeature]; trainLabel = new double[numTrain*numLabel]; validData = new double[numValid*numFeature]; validLabel = new double[numValid*numLabel]; memset(trainData, 0, sizeof(double)*numTrain*numFeature); memset(trainLabel, 0, sizeof(double)*numLabel*numTrain); memset(validData, 0, sizeof(double)*numValid*numFeature); memset(validLabel, 0, sizeof(double)*numLabel*numValid); int maskOffset =0; for(int i=0; i<numTrain; i++){ for(int j=0; j<numSets; j++){ memcpy(trainData+maskOffset, originDatas[j]->getTrainDataBatch(i), originDatas[j]->getFeatureNumber()*sizeof(double)); maskOffset += originDatas[j]->getFeatureNumber(); } } maskOffset =0; for(int i=0; i<numValid; i++){ for(int j=0; j<numSets; j++){ memcpy(validData+maskOffset, originDatas[j]->getValidDataBatch(i), originDatas[j]->getFeatureNumber()*sizeof(double)); maskOffset += originDatas[j]->getFeatureNumber(); } } memcpy( trainLabel, originDatas[0]->getTrainLabelBatch(0), numTrain*numLabel*sizeof(double) ); memcpy( validLabel, originDatas[0]->getValidLabelBatch(0), numValid*numLabel*sizeof(double) ); //todo } MergeDataset::~MergeDataset(){}
06c68c12a276a296edc65452c5913588a0085b22
95eca09328bf7f3c787f9003ce679476eddf7481
/chapter10/stock00/stock00/stock00.cpp
b613800642ce608195a03efce171e5f73a87e2ef
[]
no_license
lankuohsing/Cpp-Primer-Plus-6
2a47d1c58344564c4b3de7a460057f2e661d9f9d
dcf7c66ccac3e4bdebd3f415a2c1eb852e16e976
refs/heads/master
2021-01-12T17:50:49.848548
2017-12-20T06:51:16
2017-12-20T06:51:16
71,342,128
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,245
cpp
stock00.cpp
//stock00.coo -- implementing the Stock class //version 00 #include <iostream> #include "stock00.h" using namespace std; void Stock::acquire ( const std::string & co, long n, double pr ) { company = co; if ( n < 0 ) { cout << "Number of shares can't be negative;" << company << " shares set to 0.\n"; shares = 0; } else { shares = n; } share_val = pr; set_tot ( ); } void Stock::buy ( long num, double price ) { if ( num < 0 ) { cout << "Number of shares purchased can't be negative. " << " Transaction is aborted.\n"; } else { shares += num; share_val = price; set_tot ( ); } } void Stock::sell ( long num, double price ) { using std::cout;//ÀûÓÃusingÉùÃ÷ if ( num < 0 ) { cout << "Number of shares sold can't be negative. " << " Transaction is aborted.\n"; } else if ( num>shares ) { cout << "You can't sell more than you have! " << "Transaction is aborted.\n"; } else { shares -= num; share_val = price; set_tot ( ); } } void Stock::update ( double price ) { share_val = price; set_tot ( ); } void Stock::show ( ) { cout << "Company: " << company << " Shares: " << shares << '\n' << " Shares Price: $" << share_val << " Total Worth: $" << total_val << '\n'; }
40cbc84df2d555a65095208b83d63289495c425b
658fa667a52532fbbe624dc42e1b37cbecd415be
/source/controllers/RenderResponseAppMngm.cpp
5b1819eb78d906d7e51adaaa7eadcb06611d3699
[]
no_license
kungyin/tf_cgi
2196f50963c6849387fb3aa7b3e49e4b594dd619
0851a73fcaba03d121c72cb3db72ee7d7e6d5a3f
refs/heads/master
2016-09-16T23:55:48.148318
2015-08-27T06:05:27
2015-08-27T06:05:27
52,253,268
0
0
null
null
null
null
UTF-8
C++
false
false
84,197
cpp
RenderResponseAppMngm.cpp
#include "RenderResponseAppMngm.h" #include "http_ftp_download.h" #include "Databaseobject.h" #include <QDateTime> #include <QDir> #include <QFileInfo> RenderResponseAppMngm::RenderResponseAppMngm(THttpRequest &req, CGI_COMMAND cmd) { m_cmd = cmd; m_pReq = &req; } RenderResponseAppMngm::~RenderResponseAppMngm() { } void RenderResponseAppMngm::preRender() { if(!m_pReq) return; switch(m_cmd) { case CMD_SET_AFP: generateSetAfp(); break; case CMD_NFS_ENABLE: generateNfsEnable(); break; case CMD_CHK_DB: generateCheckDb(); break; case CMD_UPNP_AV_SERVER_PATH_LIST: generateUpnpAvServerPathList(); break; case CMD_UPNP_AV_SERVER_GET_CONFIG: generateUpnpAvServerGetConfig(); break; case CMD_UPNP_AV_SERVER: generateUpnpAvServer(); break; case CMD_UPNP_AV_SERVER_GET_SQLDB_STATE: generateUpnpAvServerGetSqldbState(); break; case CMD_GUI_CODEPAGE_GET_LIST: generateGuiCodepageGetList(); break; case CMD_ITUNES_SERVER_GET_XML: generateItunesServerGetXml(); break; case CMD_ITUNES_SERVER_READY: generateItunesServerReady(); break; case CMD_AV_SERVER_CHECK_PATH: generateUpnpAvServerCheckPath(); break; case CMD_AV_SERVER_PATH_SETTING: generateUpnpAvServerPathSetting(); break; case CMD_SQLDB_STOP_FINISH: generateSqldbStopFinish(); break; case CMD_UPNP_AV_SERVER_PRESCAN: generateUpnpAvServerPrescan(); break; case CMD_UPNP_AV_SERVER_PATH_DEL: generateUpnpAvServerPathDel(); break; case CMD_UPNP_AV_SERVER_SETTING: generateUpnpAvServerSetting(); break; case CMD_GUI_CODEPAGE_ADD: generateGuiCodepageAdd(); break; case CMD_ITUNES_SERVER_SETTING: generateItunesServerSetting(); break; case CMD_ITUNES_SERVER_CHECK_PS: generateItunesServerCheckPs(); break; case CMD_ITUNES_SERVER_REFRESH: generateItunesServerRefresh(); break; case CMD_ITUNES_SERVER_REFRESH_STATE: generateItunesServerRefreshState(); break; case CMD_SYSLOG_SEARCH: generateSyslogSearch(); break; case CMD_GET_VOLUME_INFO: generateGetVolumeInfo(); break; case CMD_SYSLOG_GET_LOG_FILE_OPTION: generateSyslogGetLogFileOption(); break; case CMD_SYSLOG_GET_CONFIG: generateSyslogGetConfig(); break; case CMD_SYSLOG_GET_SELECT_OPTION: generateSyslogGetSelectOption(); break; case CMD_SYSLOG_SET_CONFIG: generateSyslogSetConfig(); break; case CMD_SYSLOG_EXPORT: generateSyslogExport(); break; case CMD_SYSLOG_GET_EXPORT_STATUS: generateSyslogGetExportStatus(); break; case CMD_SYSLOG_CLEAR: generateSyslogClear(); break; case CMD_LOCAL_BACKUP_NOW: generateLocalBackupNow(); break; case CMD_LOCAL_BACKUP_LIST: generateLocalBackupList(); break; case CMD_LOCAL_BACKUP_SAMBA_FORMAT: generateLocalBackupSambaFormat(); break; case CMD_LOCAL_BACKUP_ADD: generateLocalBackupAdd(); break; case CMD_LOCAL_BACKUP_INFO: generateLocalBackupInfo(); break; case CMD_LOCAL_BACKUP_RENEW: generateLocalBackupRenew(); break; case CMD_LOCAL_BACKUP_DEL: generateLocalBackupDel(); break; case CMD_LOCAL_BACKUP_TEST: generateLocalBackupTest(); break; case CMD_LOCAL_BACKUP_START: generateLocalBackupStart(); break; case CMD_LOCAL_BACKUP_STOP: generateLocalBackupStop(); break; case CMD_GET_RSYNC_INFO: generateGetRsyncInfo(); break; case CMD_SET_RSYNC_SERVER: generateSetRsyncServer(); break; case CMD_GET_BACKUP_LIST: generateGetBackupList(); break; case CMD_GET_ALL_TASK_NAME: generateGetAllTaskName(); break; case CMD_SERVER_TEST: generateServerTest(); break; case CMD_CHECK_RSYNC_RW: generateCheckRsyncRw(); break; case CMD_SET_SCHEDULE: generateSetSchedule(); break; case CMD_GET_MODIFY_INFO: generateGetModifyInfo(); break; case CMD_DEL_SCHEDULE: generateDelSchedule(); break; case CMD_ENABLE_DISABLE_SCHEDULE: generateEnableDisableSchedule(); break; case CMD_BACKUP_NOW: generateBackupNow(); break; case CMD_MTP_INFO_GET: generateMtpInfoGet(); break; case CMD_USB_BACKUP_INFO_GET: generateUsbBackupInfoGet(); break; case CMD_MTP_INFO_SET: generateMtpInfoSet(); break; case CMD_USB_BACKUP_INFO_SET: generateUsbBackupInfoSet(); break; case CMD_GET_USB_MAPPING_INFO: generateGetUsbMappingInfo(); break; default: break; } } void RenderResponseAppMngm::generateSetAfp() { QString paraAfp = m_pReq->allParameters().value("afp").toString(); if(setNasCfg("afp", "enable", paraAfp)) QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_AFP_API, true); } void RenderResponseAppMngm::generateNfsEnable() { QDomDocument doc; QString paraNfsStatus = m_pReq->allParameters().value("nfs_status").toString(); QStringList apiOut; if(setNasCfg("nfs", "enable", paraNfsStatus)) apiOut = getAPIStdOut(API_PATH + SCRIPT_NFS_API + " restart", true); QDomElement root = doc.createElement("info"); doc.appendChild(root); QDomElement statusElement = doc.createElement("status"); root.appendChild(statusElement); statusElement.appendChild(doc.createTextNode(apiOut.isEmpty() ? "0" : apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateCheckDb() { QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_check_db", true); m_var = apiOut.value(0); } void RenderResponseAppMngm::generateUpnpAvServerPathList() { QDomDocument doc; QString paraPage = m_pReq->allParameters().value("page").toString(); QString paraRp = m_pReq->allParameters().value("rp").toString(); QString paraQuery = m_pReq->allParameters().value("query").toString(); QString paraQType = m_pReq->allParameters().value("qtype").toString(); QString paraField = m_pReq->allParameters().value("f_field").toString(); QString paraUser = m_pReq->allParameters().value("user").toString(); QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_share_folder_list"); QString cellContent1 = "<a href=javascript:upnp_path_refresh_one('%1');><IMG border='0' " "src='/web/images/refresh_over.png'></a>"; QString cellContent2 = "<IMG border='0' src='/web/images/on.png'>"; QDomElement root = doc.createElement("rows"); doc.appendChild(root); for(int i=0; i < apiOut.size(); i++) { QDomElement rowElement = doc.createElement("row"); root.appendChild(rowElement); QDomElement cellElement1 = doc.createElement("cell"); rowElement.appendChild(cellElement1); cellElement1.appendChild(doc.createTextNode(QString::number(i+1))); QDomElement cellElement2 = doc.createElement("cell"); rowElement.appendChild(cellElement2); cellElement2.appendChild(doc.createTextNode(apiOut.value(i).split(";").value(0))); QDomElement cellElement3 = doc.createElement("cell"); rowElement.appendChild(cellElement3); cellElement3.appendChild(doc.createCDATASection(cellContent1.arg(apiOut.value(i).split(";").value(1)))); QDomElement cellElement4 = doc.createElement("cell"); rowElement.appendChild(cellElement4); cellElement4.appendChild(doc.createCDATASection(cellContent2)); QDomElement cellElement5 = doc.createElement("cell"); rowElement.appendChild(cellElement5); cellElement5.appendChild(doc.createTextNode(apiOut.value(i).split(";").value(2))); rowElement.setAttribute("id", i+1); } QDomElement pageElement = doc.createElement("page"); root.appendChild(pageElement); pageElement.appendChild(doc.createTextNode(paraPage)); QDomElement totalElement = doc.createElement("total"); root.appendChild(totalElement); totalElement.appendChild(doc.createTextNode(QString::number(apiOut.size()))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerGetConfig() { QDomDocument doc; QMap<QString, QString> tuxeraInfo = getNasCfg("tuxera"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement enableElement = doc.createElement("enable"); root.appendChild(enableElement); enableElement.appendChild(doc.createTextNode(tuxeraInfo.value("enable"))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServer() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_upnp_av_server"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerGetSqldbState() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_upnp_sqldb_state"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement dbStateElement = doc.createElement("db_state"); root.appendChild(dbStateElement); dbStateElement.appendChild(doc.createTextNode(apiOut.value(0).split("=").value(1).trimmed())); QDomElement dbFileElement = doc.createElement("db_file"); root.appendChild(dbFileElement); dbFileElement.appendChild(doc.createTextNode(apiOut.value(1).split("=").value(1).trimmed())); m_var = doc.toString(); } void RenderResponseAppMngm::generateGuiCodepageGetList() { QDomDocument doc; char *name = NULL, *desc = NULL; int codepage_cnt = GetCodepageList(1, &name, &desc); free(name); free(desc); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(QString::number(codepage_cnt))); for (int i = 0; i < codepage_cnt; i++) { GetCodepageList(i + 1, &name, &desc); QDomElement itemElement = doc.createElement("item"); root.appendChild(itemElement); QDomElement langElement = doc.createElement("lang"); itemElement.appendChild(langElement); langElement.appendChild(doc.createTextNode(QString(name))); QDomElement descElement = doc.createElement("desc"); itemElement.appendChild(descElement); descElement.appendChild(doc.createTextNode(QString(desc))); free(name); free(desc); } m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerGetXml() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_itunes_config", true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QList<QString> configTagsElement(QList<QString>() << "enable" << "ip" << "root" << "folder" << "passwd" << "lang" << "rescan_interval"); if( configTagsElement.size() == apiOut.size() ) { for(int i=0; i < apiOut.size(); i++) { QDomElement element = doc.createElement(configTagsElement.value(i)); root.appendChild(element); element.appendChild(doc.createTextNode(apiOut.value(i))); } } else { //assert(0); tError("RenderResponseAppMngm::generateItunesServerGetXml() :" "configTagsElement size is not equal to apiOut size."); tDebug(" %d", apiOut.size()); tDebug(" %d", configTagsElement.size()); } m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerReady() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_itunes_status", true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QList<QString> configTagsElement(QList<QString>() << "enable" << "mp3_finish" << "itunes_ready" << "state"); if( configTagsElement.size() == apiOut.size() ) { for(int i=0; i < apiOut.size(); i++) { QDomElement element = doc.createElement(configTagsElement.value(i)); root.appendChild(element); element.appendChild(doc.createTextNode(apiOut.value(i))); } } else { //assert(0); tError("RenderResponseAppMngm::generateItunesServerGetXml() :" "configTagsElement size is not equal to apiOut size."); tDebug(" %d", apiOut.size()); tDebug(" %d", configTagsElement.size()); } m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerCheckPath() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_check_path " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement itemElement = doc.createElement("item"); root.appendChild(itemElement); QDomElement resElement = doc.createElement("res"); itemElement.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.isEmpty() ? "0" : "1")); QDomElement pathElement = doc.createElement("path"); itemElement.appendChild(pathElement); pathElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerPathSetting() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_share_folder " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateSqldbStopFinish() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_sqldb_stop ", true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerPrescan() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_share_folder_prescan " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerPathDel() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_share_folder_delete " + allParametersToString()); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement itemElement = doc.createElement("item"); root.appendChild(itemElement); QDomElement resElement = doc.createElement("res"); itemElement.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.isEmpty() ? "0" : "1")); for(QString e : apiOut) { QDomElement pathElement = doc.createElement("path"); itemElement.appendChild(pathElement); pathElement.appendChild(doc.createTextNode(e)); } m_var = doc.toString(); } void RenderResponseAppMngm::generateUpnpAvServerSetting() { QString paraUpnpAvServer = m_pReq->parameter("f_UPNPAVServer"); if(setNasCfg("tuxera", "enable", paraUpnpAvServer)) getAPIStdOut(API_PATH + SCRIPT_TUXERA_API + " restart"); } void RenderResponseAppMngm::generateGuiCodepageAdd() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_system_codepage " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerSetting() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_itunes_config " + allParametersToString(), true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); QDomElement stateElement = doc.createElement("state"); root.appendChild(stateElement); stateElement.appendChild(doc.createTextNode(apiOut.value(1))); m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerCheckPs() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_itunes_prcess_status " + allParametersToString(), true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); QDomElement typeElement = doc.createElement("type"); root.appendChild(typeElement); typeElement.appendChild(doc.createTextNode(apiOut.value(1))); m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerRefresh() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_set_itunes_refresh " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateItunesServerRefreshState() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " media_get_itunes_refresh_state", true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QList<QString> configTagsElement(QList<QString>() << "state" <<"temp" << "bar" << "mp3_counter" << "total_mp3" << "mp3_finish"); if( configTagsElement.size() == apiOut.size() ) { for(int i=0; i < apiOut.size(); i++) { /* for "temp" tag */ if(i == 1 && apiOut.value(i).isEmpty()) continue; QDomElement element = doc.createElement(configTagsElement.value(i)); root.appendChild(element); element.appendChild(doc.createTextNode(apiOut.value(i))); } } else { //assert(0); tError("RenderResponseAppMngm::generateItunesServerRefreshState() :" "configTagsElement size is not equal to apiOut size."); tDebug(" %d", apiOut.size()); tDebug(" %d", configTagsElement.size()); } m_var = doc.toString(); } void RenderResponseAppMngm::generateSyslogSearch() { QDomDocument doc; QString paraPage = m_pReq->allParameters().value("page").toString(); QString paraRp = m_pReq->allParameters().value("rp").toString(); QString paraSortname = m_pReq->allParameters().value("sortname").toString(); QString paraSortorder = m_pReq->allParameters().value("sortorder").toString(); QString paraQuery = m_pReq->allParameters().value("query").toString(); QString paraQType = m_pReq->allParameters().value("qtype").toString(); QString paraField = m_pReq->allParameters().value("f_field").toString(); QString paraUser = m_pReq->allParameters().value("user").toString(); QString paraLogFile = m_pReq->allParameters().value("log_file").toString(); QString paraDateFrom = m_pReq->allParameters().value("f_date_from").toString(); QString paraDateTo = m_pReq->allParameters().value("f_date_to").toString(); QString paraViewSeverity = m_pReq->allParameters().value("f_view_severity").toString(); QString paraLogHost = m_pReq->allParameters().value("log_host").toString(); QString paraLogFacility = m_pReq->allParameters().value("log_facility").toString(); QString paraLogApplication = m_pReq->allParameters().value("log_application").toString(); QString paraKeyword = m_pReq->allParameters().value("f_keyword").toString(); SyslogDbDataProvider sys; QSqlError err = sys.SelectDataFromPara(paraPage, paraRp, paraSortname, paraSortorder, paraQuery, paraQType, paraField, paraUser, paraLogFile, paraDateFrom, paraDateTo, paraViewSeverity, paraLogHost, paraLogFacility, paraLogApplication, paraKeyword); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } int size = sys.GetSize(); QDomElement root = doc.createElement("rows"); doc.appendChild(root); /*QString cellContent1 = "&amp;nbsp;[origin&amp;nbsp;software=&quot;rsyslogd&quot;&amp;nbsp;swVersion=\ &quot;5.8.6&quot;&amp;nbsp;x-pid=&quot;%1&quot;&amp;nbsp;x-info=&quot;\ http://www.rsyslog.com&quot;]&amp;nbsp;start"; QString cellContent2 = "&amp;nbsp;[origin&amp;nbsp;software=&quot;rsyslogd&quot;&amp;nbsp;swVersion=\ &quot;5.8.6&quot;&amp;nbsp;x-pid=&quot;%1&quot;&amp;nbsp;x-info=&quot;\ http://www.rsyslog.com&quot;]&amp;nbsp;exiting&amp;nbsp;on&amp;nbsp;signal&amp;nbsp;15.";*/ QDomElement rowElement; QDomElement cellElement1; QDomElement cellElement2; QDomElement cellElement3; QDomElement cellElement4; QDomElement cellElement5; QDomElement cellElement6; QDomElement cellElement7; QString deviceReportedTime; QStringList timeList; for (int i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { deviceReportedTime = sys.GetSelectedData()->value("DeviceReportedTime").toString(); if (deviceReportedTime.isEmpty()) continue; timeList = deviceReportedTime.split("T"); if (timeList.count() != 2) continue; rowElement = doc.createElement("row"); root.appendChild(rowElement); cellElement1 = doc.createElement("cell"); rowElement.appendChild(cellElement1); cellElement1.appendChild(doc.createTextNode(timeList.at(0))); cellElement2 = doc.createElement("cell"); rowElement.appendChild(cellElement2); cellElement2.appendChild(doc.createTextNode(timeList.at(1))); cellElement3 = doc.createElement("cell"); rowElement.appendChild(cellElement3); cellElement3.appendChild(doc.createTextNode(sys.GetSelectedData()->value("Facility").toString())); cellElement4 = doc.createElement("cell"); rowElement.appendChild(cellElement4); cellElement4.appendChild(doc.createTextNode(sys.GetSelectedData()->value("FromHost").toString())); cellElement5 = doc.createElement("cell"); rowElement.appendChild(cellElement5); cellElement5.appendChild(doc.createTextNode(sys.GetSelectedData()->value("Priority").toString())); cellElement6 = doc.createElement("cell"); rowElement.appendChild(cellElement6); cellElement6.appendChild(doc.createTextNode(sys.GetSelectedData()->value("SysLogTag").toString())); cellElement7 = doc.createElement("cell"); /*QUrl url(sys.GetSelectedData()->value("Message").toString()); rowElement.appendChild(cellElement7); cellElement7.appendChild(doc.createTextNode(url.toEncoded().data()));*/ rowElement.appendChild(cellElement7); cellElement7.appendChild(doc.createTextNode(sys.GetSelectedData()->value("Message").toString())); rowElement.setAttribute("id", QString::number(i + 1)); } else break; } QDomElement pageElement = doc.createElement("page"); root.appendChild(pageElement); pageElement.appendChild(doc.createTextNode(paraPage)); QDomElement totalElement = doc.createElement("total"); root.appendChild(totalElement); totalElement.appendChild(doc.createTextNode(QString::number(size))); m_var = doc.toString(); } void RenderResponseAppMngm::generateGetVolumeInfo() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_get_volume_info"); QStringList apiArgs; if (!apiOut.isEmpty()) apiArgs = apiOut.at(0).split(";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); //for(int i=0; i < apiOut.size(); i++) { // if(apiOut.at(i).isEmpty()) // continue; // if(apiOut.at(i).split(",").size() < 2) // continue; QDomElement itemElement, optValueElement, guiValueElement; for(int i = 0; i < apiArgs.size(); i++) { itemElement = doc.createElement("item"); root.appendChild(itemElement); optValueElement = doc.createElement("opt_value"); itemElement.appendChild(optValueElement); optValueElement.appendChild(doc.createTextNode(apiArgs.at(i))); guiValueElement = doc.createElement("gui_value"); itemElement.appendChild(guiValueElement); guiValueElement.appendChild(doc.createTextNode(apiArgs.at(i))); } //} m_var = doc.toString(); } void RenderResponseAppMngm::generateSyslogGetLogFileOption() { QDomDocument doc; //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); SyslogDbDataProvider sys; QSqlError err = sys.GetAllDatabase(); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } int size = sys.GetSize(); QDomElement root = doc.createElement("rows"); doc.appendChild(root); QString dbName; QDomElement cellElement; for (int i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { dbName = sys.GetSelectedData()->value(0).toString(); if (dbName.indexOf("Syslog") >= 0) { cellElement = doc.createElement("cell"); root.appendChild(cellElement); cellElement.appendChild(doc.createTextNode(dbName)); } } } m_var = doc.toString(); } void RenderResponseAppMngm::generateSyslogGetConfig() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_get_log_cfg"); QStringList apiArgs; if (!apiOut.isEmpty()) apiArgs = apiOut.at(0).split(";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); if (apiArgs.size() != 15) return; QDomElement syslogEnableElement = doc.createElement("syslog_enable"); root.appendChild(syslogEnableElement); syslogEnableElement.appendChild(doc.createTextNode(apiArgs.at(0))); QDomElement syslogFolderElement = doc.createElement("syslog_folder"); root.appendChild(syslogFolderElement); syslogFolderElement.appendChild(doc.createTextNode(apiArgs.at(1))); QDomElement syslogUdpElement = doc.createElement("syslog_udp"); root.appendChild(syslogUdpElement); syslogUdpElement.appendChild(doc.createTextNode(apiArgs.at(2))); QDomElement archiveSizeEnElement = doc.createElement("archive_size_en"); root.appendChild(archiveSizeEnElement); archiveSizeEnElement.appendChild(doc.createTextNode(apiArgs.at(3))); QDomElement archiveSizeElement = doc.createElement("archive_size"); root.appendChild(archiveSizeElement); archiveSizeElement.appendChild(doc.createTextNode(apiArgs.at(4))); QDomElement archiveNumEnElement = doc.createElement("archive_num_en"); root.appendChild(archiveNumEnElement); archiveNumEnElement.appendChild(doc.createTextNode(apiArgs.at(5))); QDomElement archiveNumElement = doc.createElement("archive_num"); root.appendChild(archiveNumElement); archiveNumElement.appendChild(doc.createTextNode(apiArgs.at(6))); QDomElement archiveCycleEnElement = doc.createElement("archive_cycle_en"); root.appendChild(archiveCycleEnElement); archiveCycleEnElement.appendChild(doc.createTextNode(apiArgs.at(7))); QDomElement archiveCycleElement = doc.createElement("archive_cycle"); root.appendChild(archiveCycleElement); archiveCycleElement.appendChild(doc.createTextNode(apiArgs.at(8))); QDomElement folderQuotaSizeElement = doc.createElement("folder_quota_size"); root.appendChild(folderQuotaSizeElement); folderQuotaSizeElement.appendChild(doc.createTextNode(apiArgs.at(9))); QDomElement emailEnableElement = doc.createElement("email_enable"); root.appendChild(emailEnableElement); emailEnableElement.appendChild(doc.createTextNode(apiArgs.at(10))); QDomElement emailSeverityElement = doc.createElement("email_severity"); root.appendChild(emailSeverityElement); emailSeverityElement.appendChild(doc.createTextNode(apiArgs.at(11))); QDomElement sendMailElement = doc.createElement("send_mail"); root.appendChild(sendMailElement); sendMailElement.appendChild(doc.createTextNode(apiArgs.at(12))); QDomElement syslogStatusElement = doc.createElement("syslog_status"); root.appendChild(syslogStatusElement); syslogStatusElement.appendChild(doc.createTextNode(apiArgs.at(13))); QDomElement archiveStatusElement = doc.createElement("archive_status"); root.appendChild(archiveStatusElement); archiveStatusElement.appendChild(doc.createTextNode(apiArgs.at(14))); m_var = doc.toString(); } void RenderResponseAppMngm::generateSyslogGetSelectOption() { QDomDocument doc; QString paraDatabase = m_pReq->allParameters().value("f_database").toString(); //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); QDomElement root = doc.createElement("config"); doc.appendChild(root); SyslogDbDataProvider sys; QSqlError err = sys.SelectAllServerity(paraDatabase); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } int size = sys.GetSize(), i = 0; QDomElement severityElement; QDomElement severityCellElement; if (size > 0) { severityElement = doc.createElement("severity"); root.appendChild(severityElement); for (i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { severityCellElement = doc.createElement("cell"); severityElement.appendChild(severityCellElement); severityCellElement.appendChild(doc.createTextNode(sys.GetSelectedData()->value(0).toString())); } } } err = sys.SelectAllHost(paraDatabase); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } size = sys.GetSize(); QDomElement hostElement; QDomElement hostCellElement; if (size > 0) { hostElement = doc.createElement("host"); root.appendChild(hostElement); for (i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { hostCellElement = doc.createElement("cell"); hostElement.appendChild(hostCellElement); hostCellElement.appendChild(doc.createTextNode(sys.GetSelectedData()->value(0).toString())); } } } err = sys.SelectAllFacility(paraDatabase); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } size = sys.GetSize(); QDomElement facilityElement; QDomElement facilityCellElement; if (size > 0) { facilityElement = doc.createElement("facility"); root.appendChild(facilityElement); for (i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { facilityCellElement = doc.createElement("cell"); facilityElement.appendChild(facilityCellElement); facilityCellElement.appendChild(doc.createTextNode(sys.GetSelectedData()->value(0).toString())); } } } err = sys.SelectAllApplication(paraDatabase); if (err.isValid()) { tDebug("MYSQL ERROR: [%s]", err.text().toLocal8Bit().data()); return; } size = sys.GetSize(); QDomElement applicationElement; QDomElement applicationCellElement; if (size > 0) { applicationElement = doc.createElement("application"); root.appendChild(applicationElement); for (i = 0; i < size; i++) { if (sys.GetSelectedData()->next()) { applicationCellElement = doc.createElement("cell"); applicationElement.appendChild(applicationCellElement); applicationCellElement.appendChild(doc.createTextNode(sys.GetSelectedData()->value(0).toString())); } } } m_var = doc.toString(); } void RenderResponseAppMngm::generateSyslogSetConfig() { QString paraSyslogEnable = m_pReq->allParameters().value("f_syslog_enable").toString(); QString paraSyslogFolder = m_pReq->allParameters().value("f_syslog_folder").toString(); QString paraSyslogUdp = m_pReq->allParameters().value("f_syslog_udp").toString(); QString paraArchiveSizeEn = m_pReq->allParameters().value("f_archive_size_en").toString(); QString paraArchiveSize = m_pReq->allParameters().value("f_archive_size").toString(); QString paraArchiveNumEn = m_pReq->allParameters().value("f_archive_num_en").toString(); QString paraArchiveCycleEn = m_pReq->allParameters().value("f_archive_cycle_en").toString(); QString paraArchiveCycle = m_pReq->allParameters().value("f_archive_cycle").toString(); QString paraFolderQuotaSize = m_pReq->allParameters().value("f_folder_quota_size").toString(); QString paraEmailSeverity = m_pReq->allParameters().value("f_email_severity").toString(); QString paraEmailEnable = m_pReq->allParameters().value("f_email_enable").toString(); QString paraIsSendmail = m_pReq->allParameters().value("is_sendmail").toString(); QString paraNewLogFolder = m_pReq->allParameters().value("f_new_log_folder").toString(); QString args = QString(" f_syslog_enable=%1#f_syslog_folder=%2#f_syslog_udp=%3#" "f_archive_size_en=%4#f_archive_size=%5#f_archive_num_en=%6#" "f_archive_cycle_en=%7#f_archive_cycle=%8#f_folder_quota_size=%9#" "f_email_severity=%10#f_email_enable=%11#is_sendmail=%12#f_new_log_folder=%13") .arg(paraSyslogEnable) .arg(paraSyslogFolder) .arg(paraSyslogUdp) .arg(paraArchiveSizeEn) .arg(paraArchiveSize) .arg(paraArchiveNumEn) .arg(paraArchiveCycleEn) .arg(paraArchiveCycle) .arg(paraFolderQuotaSize) .arg(paraEmailSeverity) .arg(paraEmailEnable) .arg(paraIsSendmail) .arg(paraNewLogFolder); QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_set_log_cfg" + args); m_var = "<script>location.href='/web/app_mgr/log_server.html?id=8401878'</script>"; } void RenderResponseAppMngm::generateSyslogExport() { QString paraLogFile = m_pReq->allParameters().value("log_file").toString(); QString paraDateFrom = m_pReq->allParameters().value("f_date_from").toString(); QString paraDateTo = m_pReq->allParameters().value("f_date_to").toString(); QString paraViewSeverity = m_pReq->allParameters().value("f_view_severity").toString(); QString paraLogHost = m_pReq->allParameters().value("log_host").toString(); QString paraLogFacility = m_pReq->allParameters().value("log_facility").toString(); QString paraLogApplication = m_pReq->allParameters().value("log_application").toString(); QString paraKeyword = m_pReq->allParameters().value("f_keyword").toString(); QString paraRp = m_pReq->allParameters().value("rp").toString(); SyslogDbDataProvider sys; m_var = sys.DumpDataFromPara(paraLogFile, paraDateFrom, paraDateTo, paraViewSeverity, paraLogHost, paraLogFacility, paraLogApplication, paraKeyword, paraRp); //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); } void RenderResponseAppMngm::generateSyslogGetExportStatus() { QDomDocument doc; //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement statusElement = doc.createElement("status"); root.appendChild(statusElement); QFileInfo f("/tmp/syslogsendok"); if (f.exists()) statusElement.appendChild(doc.createTextNode("1")); else statusElement.appendChild(doc.createTextNode("-1")); QFile::remove("/tmp/syslogsendok"); m_var = doc.toString(); } /* todo */ void RenderResponseAppMngm::generateSyslogClear() { //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); } /* todo */ void RenderResponseAppMngm::generateLocalBackupNow() { QDomDocument doc; QDomElement root = doc.createElement("config"); doc.appendChild(root); QDateTime curDatetime = QDateTime::currentDateTime(); QDomElement dateElement = doc.createElement("date"); root.appendChild(dateElement); dateElement.appendChild(doc.createTextNode(curDatetime.toString("MM/dd/yyyy"))); QDomElement hourElement = doc.createElement("hour"); root.appendChild(hourElement); hourElement.appendChild(doc.createTextNode(curDatetime.toString("hh"))); QDomElement minsElement = doc.createElement("mins"); root.appendChild(minsElement); minsElement.appendChild(doc.createTextNode(curDatetime.toString("mm"))); m_var = doc.toString(); } QString RenderResponseAppMngm::getIcon(QString status) { //0=status_queue, 2=status_queue or status_download, 3=status_ok, 4=status_fail, 6=icon_stop QString img = "/web/images/%1.png"; QString ret; if(status == "0") ret = img.arg("status_queue"); else if(status == "2") ret = img.arg("status_download"); else if(status == "3") ret = img.arg("status_ok"); else if(status == "4") ret = img.arg("status_fail"); else if(status == "5") ret = img.arg("Icon_stop"); return ret; } void RenderResponseAppMngm::generateLocalBackupList() { QDomDocument doc; QString strProgressBar = "<span class='progressBar' id='progressbar_row%1'>%2</span>"; QString strImage = "<IMG src='%1'>"; QString strBackupStart = "<a href=javascript:%1_%2('%3')><IMG border='0' src='/web/images/%2.png'></a>"; DOWNLOAD_LIST *taskList; int total = 0, pageCount = 0; int page = m_pReq->parameter("page").toInt(); int rp = m_pReq->parameter("rp").toInt(); bool is_download = true; if(m_pReq->parameter("cmd").contains("Local_Backup_")) is_download = false; memset(&taskList, 0, sizeof(DOWNLOAD_LIST*)); GetListXmlValue((is_download)?1:0, page, rp, &total, &pageCount, &taskList); QDomElement root = doc.createElement("rows"); doc.appendChild(root); for (int i = 0; i < pageCount; i++) { if (is_download && taskList[i].task_id[0] != '1') continue; if (!is_download && taskList[i].task_id[0] != '0') continue; if (QString(taskList[i].status) == "2") UpdateTaskPercent(taskList[i].task_id); //tDebug("DOWNLOAD_LIST[%s %s %s %s %s %s %s]", // taskList[i].task_id, taskList[i].src, taskList[i].dest, taskList[i].percent, taskList[i].status, taskList[i].speed, taskList[i].execat, taskList[i].comment); QDomElement rowElement1 = doc.createElement("row"); root.appendChild(rowElement1); rowElement1.setAttribute("id", QString::number(i+1)); QDomElement cellElement1 = doc.createElement("cell"); rowElement1.appendChild(cellElement1); cellElement1.appendChild(doc.createTextNode(QString(taskList[i].src))); QString dest = QString(taskList[i].dest); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) dest.replace(list.value(1), list.value(0)); } file.close(); } QDomElement cellElement2 = doc.createElement("cell"); rowElement1.appendChild(cellElement2); cellElement2.appendChild(doc.createTextNode(dest)); QDomElement cellElement3 = doc.createElement("cell"); rowElement1.appendChild(cellElement3); cellElement3.appendChild((QString(taskList[i].status) == "2")?doc.createCDATASection(strProgressBar.arg(QString::number(i+1)) .arg(QString(taskList[i].percent))):doc.createTextNode("--")); QDomElement cellElement4 = doc.createElement("cell"); rowElement1.appendChild(cellElement4); cellElement4.appendChild(doc.createCDATASection(strImage.arg(getIcon(QString(taskList[i].status))))); QDomElement cellElement5 = doc.createElement("cell"); rowElement1.appendChild(cellElement5); cellElement5.appendChild(doc.createTextNode(QString(taskList[i].speed))); QDateTime execat = QDateTime::fromString(QString(taskList[i].execat), "yyyyMMddhhmm"); QDomElement cellElement6 = doc.createElement("cell"); rowElement1.appendChild(cellElement6); cellElement6.appendChild(doc.createTextNode(execat.toString("MM/dd/yy hh:mm"))); QString arg1; if(is_download) arg1 = "downloads"; else arg1 = "localbackup"; QString arg2 = "--"; if (QString(taskList[i].status) == "0") arg2 = "start"; else if(QString(taskList[i].status) == "2") arg2 = "stop"; QDomElement cellElement7 = doc.createElement("cell"); rowElement1.appendChild(cellElement7); cellElement7.appendChild((arg2 == "--")?doc.createTextNode(arg2):doc.createCDATASection(strBackupStart .arg(arg1).arg(arg2).arg(QString(taskList[i].task_id)))); QString comment = "-"; if(!QString(taskList[i].comment).isEmpty()) { QString commentStr = "%1 %2"; QString arg1; if(QString(taskList[i].comment).at(0) == '1') { arg1 = "Fail"; } else if(QString(taskList[i].comment).at(0) == '0') { arg1 = "Success"; } QString subComment = QString(taskList[i].comment).mid(1); QDateTime datetime = QDateTime::fromString(subComment, "yyyyMMddhhmm"); comment = commentStr.arg(arg1).arg(datetime.toString("MM/dd/yy hh:mm")); } QDomElement cellElement8 = doc.createElement("cell"); rowElement1.appendChild(cellElement8); cellElement8.appendChild(doc.createTextNode(comment)); QDomElement cellElement9 = doc.createElement("cell"); rowElement1.appendChild(cellElement9); cellElement9.appendChild(doc.createTextNode(QString(taskList[i].task_id))); QDomElement cellElement10 = doc.createElement("cell"); rowElement1.appendChild(cellElement10); cellElement10.appendChild(doc.createTextNode(QString(taskList[i].speed))); FreeList(&taskList[i]); } QDomElement pageElement = doc.createElement("page"); root.appendChild(pageElement); pageElement.appendChild(doc.createTextNode(m_pReq->parameter("page"))); QDomElement totalElement = doc.createElement("total"); root.appendChild(totalElement); totalElement.appendChild(doc.createTextNode(QString::number(total))); m_var = doc.toString(); } /* todo */ void RenderResponseAppMngm::generateLocalBackupSambaFormat() { QDomDocument doc; //QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_FTP_API + " -g codepage"); QDomElement root = doc.createElement("config"); doc.appendChild(root); //for QDomElement itemElement = doc.createElement("item"); root.appendChild(itemElement); QDomElement volElement = doc.createElement("vol"); itemElement.appendChild(volElement); volElement.appendChild(doc.createTextNode("Volume_1")); m_var = doc.toString(); } /* renew: false add : true */ void RenderResponseAppMngm::renewOrAdd(bool bAdd) { QString paraLoginMethod = m_pReq->parameter("f_login_method"); DOWNLOAD_TASK_INFO taskInfo; taskInfo.is_download = 1; if(m_pReq->parameter("cmd").contains("Local_Backup_")) taskInfo.is_download = 0; taskInfo.is_src_login = paraLoginMethod.toInt() ? 0 : 1; taskInfo.is_dst_login = 0; taskInfo.is_file = (m_pReq->parameter("f_type").toInt() == 1) ? 0 : 1; QByteArray execat = QUrl::fromPercentEncoding(m_pReq->parameter("f_at").toLocal8Bit()).toUtf8(); taskInfo.execat = execat.data(); QByteArray login_id = QUrl::fromPercentEncoding(m_pReq->parameter("f_login_user").toLocal8Bit()).toUtf8(); taskInfo.login_id = login_id.data(); QString src = QUrl::fromPercentEncoding(m_pReq->parameter((taskInfo.is_download == 1)?"f_URL":"f_url").toLocal8Bit()); QFile file_src(SHARE_INFO_FILE); if (file_src.open(QIODevice::ReadOnly)) { QTextStream in(&file_src); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) src.replace(list.value(0), list.value(1)); } file_src.close(); } QByteArray src_b = src.toUtf8(); taskInfo.src = src_b.data(); QByteArray src_user = QUrl::fromPercentEncoding(m_pReq->parameter("f_user").toLocal8Bit()).toUtf8(); taskInfo.src_user = src_user.data(); QByteArray src_pwd = QUrl::fromPercentEncoding(m_pReq->parameter("f_pwd").toLocal8Bit()).toUtf8(); taskInfo.src_pwd = src_pwd.data(); QString dest = QUrl::fromPercentEncoding(m_pReq->parameter("f_dir").toLocal8Bit()); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) dest.replace(list.value(0), list.value(1)); } file.close(); } QByteArray dest_b = dest.toUtf8(); taskInfo.dest = dest_b.data(); taskInfo.dst_user = NULL; taskInfo.dst_pwd = NULL; QMap<QString, int> recurTypeMap; recurTypeMap.insert("none", 0); recurTypeMap.insert("day", 1); recurTypeMap.insert("week", 2); recurTypeMap.insert("month", 3); taskInfo.recur_type = recurTypeMap.value(m_pReq->parameter("f_period")); taskInfo.recur_date = -1; if(taskInfo.recur_type == 2) taskInfo.recur_date = m_pReq->parameter("f_period_week").toInt(); else if(taskInfo.recur_type == 3) taskInfo.recur_date = m_pReq->parameter("f_period_month").toInt(); taskInfo.is_inc = 1; QByteArray rename = QUrl::fromPercentEncoding(m_pReq->parameter("f_rename").toLocal8Bit()).toUtf8(); taskInfo.rename = rename.data(); QByteArray charset = m_pReq->parameter("f_lang").toUtf8(); taskInfo.charset = charset.data(); char *taskId = NULL; QByteArray taskId_b; if(!bAdd) { taskId_b = m_pReq->parameter("f_idx").toUtf8(); taskId = taskId_b.data(); } else { QDateTime curDatetime = QDateTime::currentDateTime(); taskInfo.task_id_date.year = curDatetime.date().year(); taskInfo.task_id_date.month = curDatetime.date().month(); taskInfo.task_id_date.day = curDatetime.date().day(); taskInfo.task_id_date.hour = curDatetime.time().hour(); taskInfo.task_id_date.min = curDatetime.time().minute(); taskInfo.task_id_date.sec = curDatetime.time().second(); } taskInfo.comment = NULL; if(SaveTaskXml(taskInfo, &taskId) != RET_SUCCESS) tDebug("RenderResponseAppMngm::generateLocalBackupAdd() : failed"); if(taskId) free(taskId); } void RenderResponseAppMngm::generateLocalBackupAdd() { renewOrAdd(true); if(m_pReq->parameter("cmd") == QString("Downloads_Schedule_Add")) m_var = "<script>location.href='/web/download_mgr/downloads_setting.html?id=8401878'</script>"; else if(m_pReq->parameter("cmd") == QString("Local_Backup_Add")) m_var = "<script>location.href='/web/backup_mgr/localbackup_setting.html?id=8401878'</script>"; } void RenderResponseAppMngm::generateLocalBackupInfo() { QDomDocument doc; QString idx = m_pReq->parameter("f_idx"); DOWNLOAD_TASK task; memset(&task, 0, sizeof(DOWNLOAD_TASK)); GetTaskXmlValue(idx.toLocal8Bit().data(), TAG_ALL, &task); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement idxElement = doc.createElement("idx"); root.appendChild(idxElement); idxElement.appendChild(doc.createTextNode(idx)); QDomElement statusElement = doc.createElement("status"); root.appendChild(statusElement); statusElement.appendChild(doc.createTextNode(QString(task.status))); QDomElement periodElement = doc.createElement("period"); root.appendChild(periodElement); periodElement.appendChild(doc.createTextNode(QString(task.period))); QDomElement recurDateElement = doc.createElement("recur_date"); root.appendChild(recurDateElement); recurDateElement.appendChild(doc.createTextNode(QString(task.recur_date))); QDomElement fileTypeElement = doc.createElement("file_type"); root.appendChild(fileTypeElement); fileTypeElement.appendChild(doc.createTextNode(QString(task.is_file) == "1" ? "0" : "1")); QDomElement srcElement = doc.createElement("src"); root.appendChild(srcElement); srcElement.appendChild(doc.createTextNode(QString(task.src))); QString dest = QString(task.dest); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) dest.replace(list.value(1), list.value(0)); } file.close(); } QDomElement destElement = doc.createElement("dest"); root.appendChild(destElement); destElement.appendChild(doc.createTextNode(dest)); QDomElement srcUserElement = doc.createElement("src_user"); root.appendChild(srcUserElement); srcUserElement.appendChild(doc.createTextNode(QString(task.src_user))); QDomElement srcPasswdElement = doc.createElement("src_passwd"); root.appendChild(srcPasswdElement); srcPasswdElement.appendChild(doc.createTextNode(QString(task.src_pwd))); QDomElement dstUserElement = doc.createElement("dst_user"); root.appendChild(dstUserElement); dstUserElement.appendChild(doc.createTextNode(QString(task.dst_user))); QDomElement dstPasswdElement = doc.createElement("dst_passwd"); root.appendChild(dstPasswdElement); dstPasswdElement.appendChild(doc.createTextNode(QString(task.dst_pwd))); QDomElement execatElement = doc.createElement("execat"); root.appendChild(execatElement); execatElement.appendChild(doc.createTextNode(QString(task.execat))); QDomElement renameElement = doc.createElement("rename"); root.appendChild(renameElement); renameElement.appendChild(doc.createTextNode(QString(task.rename))); QString elementName, elementValue; if(m_pReq->parameter("cmd").contains("Downloads_Schedule_")) { elementName = "lang"; elementValue = QString(task.option.lang); } else if(m_pReq->parameter("cmd").contains("Local_Backup_")) { elementName = "inc"; elementValue = QString(task.option.inc); } QDomElement incElement = doc.createElement(elementName); root.appendChild(incElement); incElement.appendChild(doc.createTextNode(elementValue)); FreeTask(&task); m_var = doc.toString(); } void RenderResponseAppMngm::generateLocalBackupRenew() { renewOrAdd(false); if(m_pReq->parameter("cmd") == QString("Downloads_Schedule_Renew")) m_var = "<script>location.href='/web/download_mgr/downloads_setting.html?id=8401878'</script>"; else if(m_pReq->parameter("cmd") == QString("Local_Backup_Renew")) m_var = "<script>location.href='/web/backup_mgr/localbackup_setting.html?id=8401878'</script>"; } void RenderResponseAppMngm::generateLocalBackupDel() { QDomDocument doc; RESULT_STATUS result = DeleteTaskXml(m_pReq->parameter("f_idx").toLocal8Bit().data()); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement idxElement = doc.createElement("idx"); root.appendChild(idxElement); idxElement.appendChild(doc.createTextNode(m_pReq->parameter("f_idx"))); QDomElement fnameElement = doc.createElement("fname"); root.appendChild(fnameElement); fnameElement.appendChild(doc.createTextNode(m_pReq->parameter("f_idx") + ".xml")); QDomElement resultElement = doc.createElement("result"); root.appendChild(resultElement); resultElement.appendChild(doc.createTextNode("0")); m_var = doc.toString(); } void RenderResponseAppMngm::generateLocalBackupTest() { QDomDocument doc; DOWNLOAD_TEST_RESULT testResult; QString user = m_pReq->parameter("f_user"); QString pwd = m_pReq->parameter("f_pwd"); if(user == "*****") { user.clear(); pwd.clear(); } /* Null user is anonymount. */ QString src = QUrl::fromPercentEncoding(m_pReq->parameter("f_src").toLocal8Bit()); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) src.replace(list.value(0), list.value(1)); } file.close(); } QByteArray src_b = src.toUtf8(); QByteArray lang = m_pReq->parameter("f_lang").toLocal8Bit(); RESULT_STATUS resultSatus; if (m_pReq->parameter("cmd").contains("Localbackup_")) resultSatus = TestBackupTask(m_pReq->parameter("f_type").toInt(), user.isEmpty() ? NULL : user.toLocal8Bit().data(), pwd.isEmpty() ? NULL : pwd.toLocal8Bit().data(), src_b.data(), &testResult); else resultSatus = TestDownloadTask(m_pReq->parameter("f_type").toInt(), user.isEmpty() ? NULL : user.toLocal8Bit().data(), pwd.isEmpty() ? NULL : pwd.toLocal8Bit().data(), lang.data(), src_b.data(), &testResult); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement suserElement = doc.createElement("f_suser"); root.appendChild(suserElement); suserElement.appendChild(doc.createTextNode(user)); QDomElement spasswdElement = doc.createElement("f_spasswd"); root.appendChild(spasswdElement); spasswdElement.appendChild(doc.createTextNode(pwd)); if(!m_pReq->parameter("f_lang").isEmpty()) { QDomElement langElement = doc.createElement("f_lang"); root.appendChild(langElement); langElement.appendChild(doc.createTextNode(m_pReq->parameter("f_lang"))); } QDomElement srcElement = doc.createElement("src"); root.appendChild(srcElement); srcElement.appendChild(doc.createTextNode(m_pReq->parameter("f_src"))); int result = -1; int size = -1; if(testResult.result != -1) { result = testResult.result; size = testResult.size; } QDomElement resultElement = doc.createElement("result"); root.appendChild(resultElement); resultElement.appendChild(doc.createTextNode(QString::number(result))); QDomElement sizeElement = doc.createElement("size"); root.appendChild(sizeElement); sizeElement.appendChild(doc.createTextNode(QString::number(size))); m_var = doc.toString(); } void RenderResponseAppMngm::generateLocalBackupStart() { StartTask(m_pReq->parameter("f_idx").toLocal8Bit().data()); } void RenderResponseAppMngm::generateLocalBackupStop() { StopTask(m_pReq->parameter("f_idx").toLocal8Bit().data()); } void RenderResponseAppMngm::generateGetRsyncInfo() { QDomDocument doc; RSYNC_INFO rsyncInfo; memset(&rsyncInfo, 0, sizeof(RSYNC_INFO)); RESULT_STATUS status = GetRsyncInfo(&rsyncInfo); QDomElement root = doc.createElement("rsync_info"); doc.appendChild(root); if(status == RET_SUCCESS) { QDomElement serverEnableElement = doc.createElement("server_enable"); root.appendChild(serverEnableElement); serverEnableElement.appendChild(doc.createTextNode(QString::number(rsyncInfo.is_enable))); QDomElement serverPwElement = doc.createElement("server_pw"); root.appendChild(serverPwElement); serverPwElement.appendChild(doc.createTextNode(QString(rsyncInfo.pwd))); QDomElement localIpElement = doc.createElement("local_ip"); root.appendChild(localIpElement); localIpElement.appendChild(doc.createTextNode(QString(rsyncInfo.local_ip))); } else tDebug("RenderResponseAppMngm::generateGetRsyncInfo() status: %d", status); FreeRsyncInfo(&rsyncInfo); m_var = doc.toString(); } void RenderResponseAppMngm::generateSetRsyncServer() { if (m_pReq->parameter("f_onoff").toInt() == 1) { QFile::remove(RSYNC_SHARE_NODE); QStringList dirSystempt = getAPIFileOut(SYSTEM_PT_FILE, false, ""); QDir dir(dirSystempt.value(0) + "/.systemfile/foldermount"); dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot); QFileInfoList fileList = dir.entryInfoList(); Q_FOREACH(QFileInfo fileInfo, fileList) { QStringList fileOut = getAPIFileOut(fileInfo.absoluteFilePath(), false, ""); Q_FOREACH(QString oneLine, fileOut) { QStringList lineList = oneLine.split("path="); if (!lineList.isEmpty() && lineList.length() == 2) { QFile file(RSYNC_SHARE_NODE); if (file.open(QIODevice::Append)) { QTextStream out(&file); out << fileInfo.completeBaseName() << ":" << lineList.value(1) << "\n"; file.close(); } } } } } RESULT_STATUS status = SetRsyncInfo(m_pReq->parameter("f_onoff").toInt(), m_pReq->parameter("f_password").toLocal8Bit().data()); tDebug("RenderResponseAppMngm::generateSetRsyncServer() status: %d", status); m_var = "<script>location.href='/web/backup_mgr/remote_server.html'</script>"; } void RenderResponseAppMngm::generateGetBackupList() { QDomDocument doc; QString paraPage = m_pReq->parameter("page"); QString paraRp = m_pReq->parameter("rp"); REMOTE_LIST *taskList; int total = 0, pageCount = 0; memset(&taskList, 0, sizeof(REMOTE_LIST*)); GetRemoteListXmlValue(paraPage.toInt(), paraRp.toInt(), &total, &pageCount, &taskList); QString cellcontent3 = "<img border='0' src='/web/images/%1.png' width='27'" " height='17' onclick='onoff_job(\"%2\",%3)'>"; QString cellcontent4 = "<img border='0' src='/web/images/backup.png' width='16'" " height='16' onclick='backup_now(\"%1\")'>"; QDomElement root = doc.createElement("rows"); doc.appendChild(root); for (int i = 0; i < pageCount; i++) { QDomElement rowElement = doc.createElement("row"); root.appendChild(rowElement); QDomElement cellElement1 = doc.createElement("cell"); rowElement.appendChild(cellElement1); QString task_name = QString(taskList->task_name); cellElement1.appendChild(doc.createTextNode(task_name)); QDomElement cellElement2 = doc.createElement("cell"); rowElement.appendChild(cellElement2); cellElement2.appendChild(doc.createTextNode(QString(taskList->schedule_mode))); QDomElement cellElement3 = doc.createElement("cell"); rowElement.appendChild(cellElement3); cellElement3.appendChild(doc.createTextNode(QString(taskList->state))); /* what value is taskList->enable? */ QDomElement cellElement4 = doc.createElement("cell"); rowElement.appendChild(cellElement4); QString enable = QString(taskList->enable); cellElement4.appendChild(doc.createCDATASection(cellcontent3.arg((enable == "0")?"start":"stop", task_name, enable))); QDomElement cellElement5 = doc.createElement("cell"); rowElement.appendChild(cellElement5); cellElement5.appendChild(doc.createCDATASection(cellcontent4.arg(task_name))); QDomElement cellElement6 = doc.createElement("cell"); rowElement.appendChild(cellElement6); cellElement6.appendChild(doc.createTextNode("-")); rowElement.setAttribute("id", QString::number(i)); FreeRemoteList(&taskList[i]); } QDomElement pageElement = doc.createElement("page"); root.appendChild(pageElement); pageElement.appendChild(doc.createTextNode(paraPage)); QDomElement totalElement = doc.createElement("total"); root.appendChild(totalElement); totalElement.appendChild(doc.createTextNode(QString::number(total))); m_var = doc.toString(); } void RenderResponseAppMngm::generateGetAllTaskName() { QDomDocument doc; char **nameList; int taskNum = GetAllRemoteTaskName(&nameList); QDomElement root = doc.createElement("info"); doc.appendChild(root); for (int i = 0; i < taskNum; i++) { QDomElement taskElement = doc.createElement("task"); root.appendChild(taskElement); QDomElement nameElement = doc.createElement("name"); taskElement.appendChild(nameElement); nameElement.appendChild(doc.createTextNode(QString(nameList[i]))); } FreeRemoteTaskName(taskNum, &nameList); m_var = doc.toString(); } /* s_type= 1 | 2 (int) * // 1=nas to nas backup, 2=nas to linux backup */ void RenderResponseAppMngm::generateServerTest() { QDomDocument doc; QString paraIp = m_pReq->parameter("ip"); QString paraType = m_pReq->parameter("s_type"); QString paraDirection = m_pReq->parameter("direction"); QString paraTask = m_pReq->parameter("task"); QString paraKeepExistFile = m_pReq->parameter("keep_exist_file"); QString paraLocalPath = QUrl::fromPercentEncoding(m_pReq->parameter("local_path").toLocal8Bit()); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) paraLocalPath.replace(list.value(0), list.value(1)); } file.close(); } QString paraIncremental = m_pReq->parameter("incremental"); QString paraEncryption = m_pReq->parameter("encryption"); QString paraRsyncUser = m_pReq->parameter("rsync_user"); QString paraRsyncPw = m_pReq->parameter("rsync_pw"); QString paraSshUser = m_pReq->parameter("ssh_user"); QString paraSshPw = m_pReq->parameter("ssh_pw"); QString paraIncNum = m_pReq->parameter("inc_num"); REMOTE_TEST_RESULT result; memset(&result, 0, sizeof(REMOTE_TEST_RESULT)); TestRemoteBackupTask(paraIp.toLocal8Bit().data(), paraType.toInt(), paraDirection.toInt(), paraTask.toLocal8Bit().data(), paraLocalPath.toLocal8Bit().data(), paraEncryption.toInt(), paraKeepExistFile.toInt(), paraRsyncUser.toLocal8Bit().data(), paraRsyncPw.toLocal8Bit().data(), paraSshUser.toLocal8Bit().data(), paraSshPw.toLocal8Bit().data(), &result); QDomElement root = doc.createElement("test_info"); doc.appendChild(root); QDomElement sshTestStatusElement = doc.createElement("ssh_test_status"); root.appendChild(sshTestStatusElement); sshTestStatusElement.appendChild(doc.createTextNode(QString::number(result.ssh_test_result))); QDomElement rsyncTestStatusElement = doc.createElement("rsync_test_status"); root.appendChild(rsyncTestStatusElement); rsyncTestStatusElement.appendChild(doc.createTextNode(QString::number(result.rsync_test_result))); if(result.rsync_test_result == 101 ) { if(paraType == "1") { /* todo: need API */ QDomElement remoteHdA2FreeSizeElement = doc.createElement("remote_hd_a2_free_size"); root.appendChild(remoteHdA2FreeSizeElement); remoteHdA2FreeSizeElement.appendChild(doc.createTextNode("2.7T")); } int count = 0; char **node = NULL; GetRemoteRsyncSharePath(paraIp.toLocal8Bit().data(), &count, &node); QStringList remoteNodes; for (int i = 0; i < count; i++) remoteNodes << node[i]; FreeRemoteTaskName(count, &node); if(paraType == "2") { for(QString e : remoteNodes) { QDomElement shareNodeElement = doc.createElement("share_node"); root.appendChild(shareNodeElement); QDomElement nameElement = doc.createElement("name"); shareNodeElement.appendChild(nameElement); nameElement.appendChild(doc.createTextNode(e)); } } char **name = NULL, **path = NULL; int volCount = 0; GetRsyncSharePath(&volCount, &name, &path); QMap<QString, QString> shareNodeMap; for(int i=0; i< volCount; i++) { shareNodeMap.insert(QString(name[i]), QString(path[i])); } FreeRsyncSharePath(volCount, &name, &path); char *size = NULL; GetLocalDeviceSizeString(shareNodeMap.value("Volume_1").toLocal8Bit().data(), NULL, &size); QDomElement localDirectoryUsedSizeElement = doc.createElement("local_directory_used_size"); root.appendChild(localDirectoryUsedSizeElement); localDirectoryUsedSizeElement.appendChild(doc.createTextNode(QString(size))); if(size) free(size); if(paraType == "1") { for(QString e : shareNodeMap.keys()) { QDomElement shareNodeElement = doc.createElement("share_node"); root.appendChild(shareNodeElement); QDomElement nameElement = doc.createElement("name"); shareNodeElement.appendChild(nameElement); nameElement.appendChild(doc.createTextNode(e)); QDomElement pathElement = doc.createElement("path"); shareNodeElement.appendChild(pathElement); pathElement.appendChild(doc.createTextNode(shareNodeMap.value(e))); } } } m_var = doc.toString(); } void RenderResponseAppMngm::generateCheckRsyncRw() { QDomDocument doc; QByteArray paraIp = m_pReq->parameter("ip").toLocal8Bit(); QString paraType = m_pReq->parameter("s_type"); QString paraDirection = m_pReq->parameter("direction"); QByteArray paraTask = m_pReq->parameter("task").toLocal8Bit(); QString paraKeepExistFile = m_pReq->parameter("keep_exist_file"); QByteArray paraLocalPath = m_pReq->parameter("local_path").toLocal8Bit(); QByteArray paraIncremental = m_pReq->parameter("incremental").toLocal8Bit(); QString paraEncryption = m_pReq->parameter("encryption"); QByteArray paraRsyncUser = m_pReq->parameter("rsync_user").toLocal8Bit(); QByteArray paraRsyncPw = m_pReq->parameter("rsync_pw").toLocal8Bit(); QByteArray paraSshUser = m_pReq->parameter("ssh_user").toLocal8Bit(); QByteArray paraSshPw = m_pReq->parameter("ssh_pw").toLocal8Bit(); QByteArray paraIncNum = m_pReq->parameter("inc_num").toLocal8Bit(); QByteArray paraRemotePath = m_pReq->parameter("remote_path").toLocal8Bit(); int rsyncRet = TestRsyncConnect(paraIp.data(), paraType.toInt(), paraDirection.toInt(), paraTask.data(), paraLocalPath.data(), paraEncryption.toInt(), paraKeepExistFile.toInt(), paraRsyncUser.data(), paraRsyncPw.data(), paraSshUser.data(), paraSshPw.data()); QDomElement root = doc.createElement("rsync_info"); doc.appendChild(root); QDomElement rsyncRetElement = doc.createElement("rsync_ret"); root.appendChild(rsyncRetElement); rsyncRetElement.appendChild(doc.createTextNode(QString::number(rsyncRet))); m_var = doc.toString(); } void RenderResponseAppMngm::generateSetSchedule() { REMOTE_BACKUP_INFO r_info; memset(&r_info, 0, sizeof(REMOTE_BACKUP_INFO)); QByteArray task_name = QUrl::fromPercentEncoding(m_pReq->parameter("task").toLocal8Bit()).toUtf8(); r_info.task_name = task_name.data(); r_info.is_enable = 1; r_info.state = 1; r_info.server_type = m_pReq->parameter("s_type").toInt(); r_info.backup_type = m_pReq->parameter("direction").toInt(); r_info.schedule_mode = m_pReq->parameter("schedule_type").toInt(); r_info.is_use_ssh = m_pReq->parameter("ssh_user").isEmpty() ? 0 : 1; r_info.is_keep_exist_file = m_pReq->parameter("keep_exist_file").toInt(); r_info.is_inc_enable = m_pReq->parameter("incremental").toInt(); r_info.inc_number = m_pReq->parameter("inc_num").toInt(); QByteArray rsync_user = QUrl::fromPercentEncoding(m_pReq->parameter("rsync_user").toLocal8Bit()).toUtf8(); r_info.rsync_user = rsync_user.data(); QByteArray rsync_pwd = QUrl::fromPercentEncoding(m_pReq->parameter("rsync_pw").toLocal8Bit()).toUtf8(); r_info.rsync_pwd = rsync_pwd.data(); QByteArray ssh_user = QUrl::fromPercentEncoding(m_pReq->parameter("ssh_user").toLocal8Bit()).toUtf8(); r_info.ssh_user = ssh_user.data(); QByteArray ssh_pwd = QUrl::fromPercentEncoding(m_pReq->parameter("ssh_pw").toLocal8Bit()).toUtf8(); r_info.ssh_pwd = ssh_pwd.data(); QByteArray remote_ip = QUrl::fromPercentEncoding(m_pReq->parameter("ip").toLocal8Bit()).toUtf8(); r_info.remote_ip = remote_ip.data(); QByteArray remote_path = QUrl::fromPercentEncoding(m_pReq->parameter("remote_path").toLocal8Bit()).toUtf8(); r_info.remote_path = remote_path.data(); QString localPath = QUrl::fromPercentEncoding(m_pReq->parameter("local_path").toLocal8Bit()); QFile file(SHARE_INFO_FILE); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); while (!in.atEnd()) { QStringList list = in.readLine().split(":"); if (!list.isEmpty() && list.length() == 2) localPath.replace(list.value(0), list.value(1)); } file.close(); } QByteArray local_path = QUrl::fromPercentEncoding(localPath.toLocal8Bit()).toUtf8(); r_info.local_path = local_path.data(); //QDateTime execat = QDateTime::fromString(QString(taskList[i].execat), "yyyyMMddhhmm"); // crond_type= 1 | 2 | 3 (int) //1->Monthly, 2-> Weekly 3-> daily // recur_type= 0~4(int) //0=none, 1=day, 2=week, 3=month if schedule_mode=3 // recur_date= 0~6 | 1~31 (int) //recur_type=2 -> 0~6=Sun, Mon, Tue, Wed, Thu, Fri, Sat . recur_type=3 -> 1~31 QByteArray execat; if (m_pReq->parameter("schedule_type") == "1") { r_info.recur_type = 0; r_info.recur_date = 0; execat = QString("").toUtf8(); r_info.execat = execat.data(); if (m_pReq->parameter("backup_now") == "1") { QDateTime curDatetime = QDateTime::currentDateTime(); curDatetime.time().addSecs(60 - curDatetime.time().second()); } } else if (m_pReq->parameter("schedule_type") == "2") { r_info.recur_type = 0; r_info.recur_date = 0; QDateTime curDatetime = QDateTime::currentDateTime(); curDatetime.date().setDate(curDatetime.date().year(), m_pReq->parameter("month").toInt(), m_pReq->parameter("day").toInt()); curDatetime.time().setHMS(m_pReq->parameter("hour").toInt(), m_pReq->parameter("minute").toInt(), 0); execat = curDatetime.toString("yyyyMMddhhmm").toUtf8(); r_info.execat = execat.data(); } else { if(m_pReq->parameter("crond_type") == "1") { r_info.recur_type = 3; r_info.recur_date = m_pReq->parameter("day").toInt(); } else if(m_pReq->parameter("crond_type") == "2") { r_info.recur_type = 2; r_info.recur_date = m_pReq->parameter("weekly").toInt(); } else { r_info.recur_type = 1; r_info.recur_date = m_pReq->parameter("day").toInt(); } execat = QString("%1%2").arg(m_pReq->parameter("hour")).arg(m_pReq->parameter("minute")).toUtf8(); r_info.execat = execat.data(); } SaveRemoteXml(r_info, (m_pReq->parameter("type") == "1")?1:0); m_var = "N/A"; } void RenderResponseAppMngm::generateGetModifyInfo() { QDomDocument doc; REMOTE_BACKUP_INFO r_info_ret; memset(&r_info_ret, 0, sizeof(REMOTE_BACKUP_INFO)); GetRemoteTaskXmlValue(m_pReq->parameter("name").toLocal8Bit().data(), TAG_R_ALL, &r_info_ret); QDomElement root = doc.createElement("info"); doc.appendChild(root); QDomElement jobNameElement = doc.createElement("job_name"); root.appendChild(jobNameElement); jobNameElement.appendChild(doc.createTextNode(m_pReq->parameter("name"))); QDomElement serverTypeElement = doc.createElement("server_type"); root.appendChild(serverTypeElement); serverTypeElement.appendChild(doc.createTextNode(QString::number(r_info_ret.server_type))); QDomElement backupTypeElement = doc.createElement("backup_type"); root.appendChild(backupTypeElement); backupTypeElement.appendChild(doc.createTextNode(QString::number(r_info_ret.backup_type))); QDomElement scheduleModeElement = doc.createElement("schedule_mode"); root.appendChild(scheduleModeElement); scheduleModeElement.appendChild(doc.createTextNode(QString::number(r_info_ret.schedule_mode))); QDomElement useSshElement = doc.createElement("use_ssh"); root.appendChild(useSshElement); useSshElement.appendChild(doc.createTextNode(QString::number(r_info_ret.is_use_ssh))); QDomElement keepExistFileElement = doc.createElement("keep_exist_file"); root.appendChild(keepExistFileElement); keepExistFileElement.appendChild(doc.createTextNode(QString::number(r_info_ret.is_keep_exist_file))); QDomElement incBackupElement = doc.createElement("inc_backup"); root.appendChild(incBackupElement); incBackupElement.appendChild(doc.createTextNode(QString::number(r_info_ret.is_inc_enable))); QDomElement incNumberElement = doc.createElement("inc_number"); root.appendChild(incNumberElement); incNumberElement.appendChild(doc.createTextNode(QString::number(r_info_ret.inc_number))); QDomElement scheduleElement = doc.createElement("schedule"); root.appendChild(scheduleElement); scheduleElement.appendChild(doc.createTextNode("")); QDomElement remoteIpElement = doc.createElement("remote_ip"); root.appendChild(remoteIpElement); remoteIpElement.appendChild(doc.createTextNode(QString(r_info_ret.remote_ip))); QDomElement localPathElement = doc.createElement("local_path"); root.appendChild(localPathElement); localPathElement.appendChild(doc.createTextNode(QString(r_info_ret.local_path))); QDomElement rsyncUserElement = doc.createElement("rsync_user"); root.appendChild(rsyncUserElement); rsyncUserElement.appendChild(doc.createTextNode(QString(r_info_ret.rsync_user))); QDomElement rsyncPwElement = doc.createElement("rsync_pw"); root.appendChild(rsyncPwElement); rsyncPwElement.appendChild(doc.createTextNode(QString(r_info_ret.rsync_pwd))); QDomElement sshUserElement = doc.createElement("ssh_user"); root.appendChild(sshUserElement); sshUserElement.appendChild(doc.createTextNode(QString(r_info_ret.ssh_user))); QDomElement sshPwElement = doc.createElement("ssh_pw"); root.appendChild(sshPwElement); sshPwElement.appendChild(doc.createTextNode(QString(r_info_ret.ssh_pwd))); QDomElement remotePathElement = doc.createElement("remote_path"); root.appendChild(remotePathElement); remotePathElement.appendChild(doc.createTextNode(QString(r_info_ret.remote_path))); FreeRemoteTask(&r_info_ret); m_var = doc.toString(); } void RenderResponseAppMngm::generateDelSchedule() { DeleteRemoteTaskXml(m_pReq->parameter("name").toLocal8Bit().data()); m_var = "N/A"; } void RenderResponseAppMngm::generateEnableDisableSchedule() { StartStopRemoteTask(m_pReq->parameter("name").toLocal8Bit().data(), m_pReq->parameter("enable").toLocal8Bit().data()); m_var = "N/A"; } void RenderResponseAppMngm::generateBackupNow() { QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_START_REMOTE_BACKUP + " " + m_pReq->parameter("name")); m_var = "N/A"; } void RenderResponseAppMngm::generateMtpInfoGet() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_get_mtp_info", true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QStringList configTagNames(QStringList() << "backup_date" << "state" << "dest_dir" << "mtp_status"); if( configTagNames.size() == apiOut.size() ) { for(int i=0; i < configTagNames.size(); i++) { QDomElement configContentElement = doc.createElement(configTagNames.value(i)); root.appendChild(configContentElement); configContentElement.appendChild(doc.createTextNode(apiOut.value(i))); } } else { //assert(0); tError("RenderResponseSysStatus::generateMtpInfoGet(): " "configTagNames size is not equal to apiOut size."); } m_var = doc.toString(); } void RenderResponseAppMngm::generateUsbBackupInfoGet() { QDomDocument doc; QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_get_usb_backup_info", true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.isEmpty() ? "0" : "1")); QStringList configTagNames(QStringList() << "front_usb" << "state" << "direction" << "source_dir" << "dest_dir" << "type" << "backup_status"); if(!apiOut.isEmpty()) { if( configTagNames.size() == apiOut.size() ) { for(int i=0; i < configTagNames.size(); i++) { QDomElement configContentElement = doc.createElement(configTagNames.value(i)); root.appendChild(configContentElement); configContentElement.appendChild(doc.createTextNode(apiOut.value(i))); } } else { //assert(0); tError("RenderResponseSysStatus::generateUsbBackupInfoGet(): " "configTagNames size is not equal to apiOut size."); } } m_var = doc.toString(); } void RenderResponseAppMngm::generateMtpInfoSet() { QDomDocument doc; QString paraEnable = m_pReq->parameter("f_enable"); QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_set_mtp_backups_cfg " + allParametersToString(), true, ";"); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(paraEnable)); /* todo: Volume_1 is /mnt/HD/HD_a2 ?? */ // QString dest = "/mnt/HD/HD_a2"; // if(paraDestDir == "Volume_2") // dest = "/mnt/HD/HD_b2"; QDomElement destElement = doc.createElement("dest"); root.appendChild(destElement); destElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateUsbBackupInfoSet() { QDomDocument doc; // QString paraEnable = m_pReq->parameter("f_enable"); // QString paraDirection = m_pReq->parameter("f_direction"); // QString paraSourceDir = m_pReq->parameter("f_source_dir"); // QString paraDestDir = m_pReq->parameter("f_dest_dir"); // QString paraType = m_pReq->parameter("f_type"); QStringList apiOut = getAPIStdOut(API_PATH + SCRIPT_MANAGER_API + " service_set_usb_backup_cfg " + allParametersToString(), true); QDomElement root = doc.createElement("config"); doc.appendChild(root); QDomElement resElement = doc.createElement("res"); root.appendChild(resElement); resElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); } void RenderResponseAppMngm::generateGetUsbMappingInfo() { QDomDocument doc; QStringList apiOut = getAPIFileOut(USB_SHARE_INFO_FILE, true); QDomElement root = doc.createElement("mapping_info"); doc.appendChild(root); QDomElement itemElement = doc.createElement("item"); root.appendChild(itemElement); QDomElement dataElement = doc.createElement("data"); itemElement.appendChild(dataElement); dataElement.appendChild(doc.createTextNode(apiOut.value(0))); m_var = doc.toString(); }
1d023058a247ca51e1510c78c1f7b6dce0553b97
0d653408de7c08f1bef4dfba5c43431897097a4a
/cmajor/sngxml/serialization/XmlSerializationContext.hpp
14d610724cf86d72969fc4da7d34d67db2c66243
[]
no_license
slaakko/cmajorm
948268634b8dd3e00f86a5b5415bee894867b17c
1f123fc367d14d3ef793eefab56ad98849ee0f25
refs/heads/master
2023-08-31T14:05:46.897333
2023-08-11T11:40:44
2023-08-11T11:40:44
166,633,055
7
2
null
null
null
null
UTF-8
C++
false
false
1,416
hpp
XmlSerializationContext.hpp
// ================================= // Copyright (c) 2022 Seppo Laakko // Distributed under the MIT license // ================================= #ifndef SNGXML_XML_XML_SERIALIZATION_CONTEXT_INCLUDED #define SNGXML_XML_XML_SERIALIZATION_CONTEXT_INCLUDED #include <sngxml/serialization/XmlSerApi.hpp> namespace sngxml { namespace xmlser { enum class XmlSerializationFlags : int { none = 0, suppressMetadata = 1 << 0 }; SNGXML_SERIALIZATION_API inline XmlSerializationFlags operator|(XmlSerializationFlags left, XmlSerializationFlags right) { return XmlSerializationFlags(int(left) | int(right)); } SNGXML_SERIALIZATION_API inline XmlSerializationFlags operator&(XmlSerializationFlags left, XmlSerializationFlags right) { return XmlSerializationFlags(int(left) & int(right)); } SNGXML_SERIALIZATION_API inline XmlSerializationFlags operator~(XmlSerializationFlags flag) { return XmlSerializationFlags(~int(flag)); } class SNGXML_SERIALIZATION_API XmlSerializationContext { public: XmlSerializationContext(); bool GetFlag(XmlSerializationFlags flag) { return (flags & flag) != XmlSerializationFlags::none; } void SetFlag(XmlSerializationFlags flag) { flags = flags | flag; } void ResetFlag(XmlSerializationFlags flag) { flags = flags & ~flag; } private: XmlSerializationFlags flags; }; } } // namespace sngxml::xmlser #endif // SNGXML_XML_XML_SERIALIZATION_CONTEXT_INCLUDED
5e939a3cb4d638f35cc877e2c7362fe3b39af203
227098e691187ca1cd1a1a5bfeed5ab89d0f485d
/teams.cpp
1f3cb0b630c66c429446adf088ca98b65ab812e0
[]
no_license
lucassf/Garde
e5b6caf4c1f1b636b61a5a171b529fa40a147bf2
a01703960e6a8ceb66be2046eba38e7bca4bde39
refs/heads/master
2021-07-17T10:36:06.910732
2017-10-24T15:27:32
2017-10-24T15:27:32
108,146,645
0
0
null
null
null
null
UTF-8
C++
false
false
3,599
cpp
teams.cpp
#include <bits/stdc++.h> using namespace std; typedef pair<double,double> dd; struct team{ int points, goal_balance, pro_goals; int id; string name; team(){} team(string _name,int _points,int _goal_balance,int _pro_goals, int _id){ name = _name; points = _points, goal_balance = _goal_balance, pro_goals = _pro_goals; id = _id; } team win(){ return team(name,points+3,goal_balance+1,pro_goals+1,id); } team draw(){ return team(name,points+1,goal_balance,pro_goals+1,id); } team lose(){ return team(name,points,goal_balance-1,pro_goals,id); } bool operator<(team other)const{ if (points!=other.points) return points>other.points; if (goal_balance!=other.goal_balance) return goal_balance>other.goal_balance; return pro_goals>other.pro_goals; } }; struct game{ int team1_id,team2_id; double pwin, pdraw, plose; game(){} game(int t1,int t2,double pw,double pd,double pl){ team1_id = t1, team2_id = t2, pwin = pw, pdraw = pd, plose = pl; } }; void recursion(int index,vector<team> &teams,vector<game> &games,vector<dd> &probs,double prob){ if (index == games.size()){ vector<team> aux_teams = teams; sort(aux_teams.begin(),aux_teams.end()); for (int i=0;i<4;i++) probs[aux_teams[i].id].first += prob; probs[aux_teams[4].id].second += prob; return; } int team1_id = games[index].team1_id; int team2_id = games[index].team2_id; team team1,team2; team1 = teams[team1_id]; team2 = teams[team2_id]; teams[team1_id] = team1.win(); teams[team2_id] = team2.lose(); recursion(index+1,teams,games,probs,prob*games[index].pwin); teams[team1_id] = team1.draw(); teams[team2_id] = team2.draw(); recursion(index+1,teams,games,probs,prob*games[index].pdraw); teams[team1_id] = team1.lose(); teams[team2_id] = team2.win(); recursion(index+1,teams,games,probs,prob*games[index].plose); teams[team1_id] = team1; teams[team2_id] = team2; } vector<dd> getClassProb(vector<team> &teams,vector<game> &games){ vector<dd> probs; probs.assign(teams.size(),dd(0,0)); recursion(0,teams,games,probs,1); return probs; } int main(){ vector<team> teams; vector<game> games; teams.push_back(team("Brasil",38,27,38,0)); teams.push_back(team("Uruguai",28,10,28,1)); teams.push_back(team("Argentina",25,1,16,2)); teams.push_back(team("Colombia",26,2,20,3)); teams.push_back(team("Peru",25,1,26,4)); teams.push_back(team("Chile",26,2,26,5)); teams.push_back(team("Paraguai",24,-5,19,6)); teams.push_back(team("Equador",20,-1,25,7)); teams.push_back(team("Bolivia",14,-20,14,8)); teams.push_back(team("Venezuela",9,-17,18,9)); games.push_back(game(0, 5, 0.7, 0.2, 0.1)); games.push_back(game(7, 2, 0.3, 0.2, 0.5)); games.push_back(game(4, 3, 0.3, 0.4, 0.3)); games.push_back(game(1, 8, 0.65, 0.15, 0.2)); games.push_back(game(6, 9, 0.5, 0.25, 0.25)); vector<dd> probs = getClassProb(teams,games); printf("%15s|%20s|%20s\n\n","Selecao","Prob. Classificar","Prob. Repescagem"); for (int i=0;i<probs.size();i++){ printf("%15s|%20.2lf|%20.2lf\n",teams[i].name.c_str(),probs[i].first*100,probs[i].second*100); } char ok; printf("\nPressiona enter para sair...\n"); scanf("%c",&ok); }
8b057955fb5238fece6a13b2f0e21efedeea7afb
5c40da8a9b686b75276324395ca910dc0addc6ff
/dm9375/BigInteger.cpp
530935d57f514cf65338342735713580137b7dde
[]
no_license
S1ckick/dm9375
e6d1fe5fbc7aa848dc84f42929b0ad86a96229ab
ae8092e650398123ad62ea0f2447d31ca4db50bb
refs/heads/master
2022-07-09T16:25:40.164960
2020-05-13T07:48:50
2020-05-13T07:48:50
257,342,019
0
0
null
2020-05-13T06:05:21
2020-04-20T16:34:21
C++
UTF-8
C++
false
false
9,158
cpp
BigInteger.cpp
#include "header.h" BigInteger::BigInteger() { sign = plus_sign; number = BigNatural(); } BigInteger::~BigInteger() { } BigInteger &BigInteger::operator=(BigInteger const &BigInt) { sign = BigInt.sign; number = BigNatural(BigInt.number); return *this; } BigInteger::BigInteger(int number) { if (number < 0) { number = -number; sign = minus_sign; } else sign = plus_sign; this->number = BigNatural(number); } BigInteger::BigInteger(const BigInteger &BigInt) { sign = BigInt.sign; number = BigNatural(BigInt.number); } BigInteger::BigInteger(std::string string) { if (string[0] == '-') { sign = minus_sign; number = BigNatural(string.erase(0, 1)); } else { sign = plus_sign; number = BigNatural(string); } } std::string BigInteger::ToString() { if (sign == minus_sign) { std::string strBigN; strBigN += '-'; strBigN += number.ToString(); return strBigN; } else return number.ToString(); } /*********************************************************/ /*MODULES*/ //Барашкин Дмитрий 9375 BigNatural ABS_Z_N(BigInteger biIn) { BigInteger res = BigInteger(biIn); return res.number; } //Барашкин Дмитрий 9375 int POZ_Z_D(BigInteger biIn) { if (biIn.number.coef[0] == 0 && biIn.number.size == 1) { return 0; } else if (biIn.sign == minus_sign) { return 1; } else { return 2; } } //Барашкин Дмитрий 9375 /* MUL_ZM_Z получает на вход целое число и меняет его знак Параметры: 1)BigInteger biIn-исходное число Функция возвращает целое число с противоположным знаком-BigInteger */ BigInteger MUL_ZM_Z(BigInteger biIn) { BigInteger res = BigInteger(biIn); if (res.number.coef[0] == 0 && res.number.size == 1) { return res; } else if (res.sign == plus_sign) { res.sign = minus_sign; return res; } else if (res.sign == minus_sign) { res.sign = plus_sign; return res; } return res; } //Шарифуллин Руслан 9375 //На вход функция получает натуральное число и на выходе выдаёт целое. BigInteger TRANS_N_Z(BigNatural b) { BigInteger bigInt; bigInt.number = b; bigInt.sign = plus_sign; return bigInt; } //Шарифуллин Руслан 9375 //На вход функция получает целое число и на выходе выдаёт натуральное. BigNatural TRANS_Z_N(BigInteger b) { BigNatural bigNat; bigNat = b.number; return bigNat; } //Гладилин Сергей 9375 /*ADD_ZZ_Z Возвращает результат сложения двух целых чисел Параметры: 1) BigInteger first - первое целое число 2) BigInteger second - второе целое число Функция возвращает резульат сложения двух целых чисел BigInteger */ BigInteger ADD_ZZ_Z(BigInteger first, BigInteger second) { BigInteger result; result.sign = first.sign; if (first.sign == second.sign) { result.number = ADD_NN_N(ABS_Z_N(first), ABS_Z_N(second)); return result; } if (first.sign == minus_sign) { BigInteger tmp(second); second = first; first = tmp; result.sign = plus_sign; } if (COM_NN_D(ABS_Z_N(first), ABS_Z_N(second)) == 2) { result.number = SUB_NN_N(ABS_Z_N(first), ABS_Z_N(second)); return result; } else { result.number = SUB_NN_N(ABS_Z_N(second), ABS_Z_N(first)); if (!NZER_N_B(result.number)) { result.sign = plus_sign; return result; } else { result.sign = minus_sign; return result; } } } //Гладилин Сергей 9375 /*SUB_ZZ_Z Возвращает резульат вычитания двух целых чисел Параметры: 1) BigInteger first - первое целое число 2) BigInteger second - второе целое число Функция возвращает резульата вычитания двух целых чисел BigInteger */ BigInteger SUB_ZZ_Z(BigInteger first, BigInteger second) { BigInteger result; result.sign = first.sign; if (first.sign == second.sign) { if (COM_NN_D(ABS_Z_N(first), ABS_Z_N(second)) == 2) result.number = SUB_NN_N(ABS_Z_N(first), ABS_Z_N(second)); else { result.number = SUB_NN_N(ABS_Z_N(second), ABS_Z_N(first)); if (COM_NN_D(ABS_Z_N(first), ABS_Z_N(second)) == 0) result.sign = plus_sign; else result = MUL_ZM_Z(result); } } else result.number = ADD_NN_N(ABS_Z_N(first), ABS_Z_N(second)); return result; } //Покровская Елизавета 9375 /* Умножение целых чисел firstInt-первое целое число secondInt-второе целое число функция возвращает целое цисло BigInteger */ BigInteger MUL_ZZ_Z(BigInteger firstInt, BigInteger secondInt) { BigInteger answer; BigNatural absFirstInt; BigNatural absSecondInt; absFirstInt = ABS_Z_N(firstInt); // находим модули чисел, то есть делаем целые числа натуральными absSecondInt = ABS_Z_N(secondInt); answer.number = MUL_NN_N(absFirstInt, absSecondInt); // перемножаем натуральные числа if (POZ_Z_D(firstInt) == POZ_Z_D(secondInt)) return answer; // если оба числа положительные или отрицательные, то находим ответ else return MUL_ZM_Z(answer); // если нет, то умножаем на (-1) } //Шагиев Даниил 9375 BigInteger DIV_ZZ_Z(BigInteger first, BigInteger second) { //если первое число не нуль if ((first.number.coef[0] != 0) || (first.number.size != 1)) { BigInteger res; //если второе число не нуль if ((second.number.coef[0] != 0 || second.number.size != 1)) { res.number = DIV_NN_N(ABS_Z_N(first), ABS_Z_N(second)); res.sign = first.sign == second.sign ? plus_sign : minus_sign; if (first.sign==minus_sign && POZ_Z_D(MOD_ZZ_Z(first,second))!=0)//если первое число имеет знак минус и остаток не ноль, то отнимем единицу. { BigInteger one(1); res=SUB_ZZ_Z(res,one); } } else//если второе число нуль res.number.size = 0; return res; } else//если нуль { BigInteger res; return res; } } //Шагиев Даниил 9375 BigInteger MOD_ZZ_Z(BigInteger first, BigInteger second) { if (((first.number.coef[0] == 0) && (first.number.size == 1)) || ((second.number.coef[0] == 0) && (second.number.size == 1))) { BigInteger res; return res; } else { // first is positive if (((POZ_Z_D(first) == 2) && (POZ_Z_D(second) == 1)) || ((POZ_Z_D(first) == 2) && (POZ_Z_D(second) == 2))) { first.sign = plus_sign; second.sign = plus_sign; return SUB_ZZ_Z(first, MUL_ZZ_Z(second, DIV_ZZ_Z(first, second))); } else if ((POZ_Z_D(first) == 1) && (POZ_Z_D(second) == 2)) { // first is negative and second is positive first.sign = plus_sign; BigInteger res = DIV_ZZ_Z(first, second); res.sign = minus_sign; first.sign = minus_sign; BigInteger check = MUL_ZZ_Z(second, res); if (COM_NN_D(check.number, first.number) == 0 && check.sign == first.sign) { BigInteger res; return res; } res = SUB_ZZ_Z(res, BigInteger(1)); res = SUB_ZZ_Z(first, MUL_ZZ_Z(second, res)); return res; } else { // first and second are negative first.sign = plus_sign; second.sign = plus_sign; BigInteger res = DIV_ZZ_Z(first, second); first.sign = minus_sign; second.sign = minus_sign; BigInteger check = MUL_ZZ_Z(second, res); if (COM_NN_D(check.number, first.number) == 0 && check.sign == first.sign) { BigInteger res; return res; } res = ADD_ZZ_Z(res, BigInteger(1)); res = SUB_ZZ_Z(first, MUL_ZZ_Z(second, res)); return res; } } }
492ec9fd84a0df8ff21498fbed17d9d8175c2e3e
a82dfb61b17fa66b9c75fe871401cff77aa77f56
/utils/data_model_to_pymcell/generator_utils.cpp
fd3d7120177c8bc9ff13b3c05bc80a5292167612
[ "MIT" ]
permissive
mcellteam/mcell
49ca84048a091de8933adccc083d31b7bcb1529e
3920aec22c55013b78f7d6483b81f70a0d564d22
refs/heads/master
2022-12-23T15:01:51.931150
2021-09-29T16:49:14
2021-09-29T16:49:14
10,253,341
29
12
NOASSERTION
2021-07-08T01:56:40
2013-05-23T20:59:54
C++
UTF-8
C++
false
false
18,740
cpp
generator_utils.cpp
/****************************************************************************** * * Copyright (C) 2020 by * The Salk Institute for Biological Studies * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ******************************************************************************/ #include <fstream> #include <algorithm> #include <ctype.h> #include "generator_utils.h" #include "api/python_export_constants.h" #include "api/compartment_utils.h" #include "generator_structs.h" using namespace MCell::API; namespace MCell { void check_not_empty(const Value& parent, const char* key, const std::string& msg_location) { string s = parent[key].asString(); bool white_space = std::all_of(s.begin(), s.end(), ::isspace); if (s == "" || white_space) { ERROR("Unexpected empty string as value of " + msg_location + " - " + key + "."); } } static std::string replace_id_with_function(const std::string& id, const bool use_python_functions) { const auto& func_it = mdl_functions_to_py_bngl_map.find(id); if (func_it != mdl_functions_to_py_bngl_map.end()) { // replace if (use_python_functions) { return func_it->second.first; } else { // BNGL variant return func_it->second.second; } } else { // other id, keep it as it is return id; } } // when use_python_functions is true, function calls are replaced with Python function names // when false, they are replaced with BNGL function names std::string replace_function_calls_in_expr(const std::string& data_model_expr, const bool use_python_functions) { std::string res; // all function names are represented as ids, i.e. [a-zA-Z_][a-zA-Z0-9_]* // practically the same automaton as in get_used_ids enum state_t { START, IN_ID, IN_NUM }; state_t state = START; string curr_id; for (size_t i = 0; i < data_model_expr.size(); i++) { char c = data_model_expr[i]; switch (state) { case START: if (isalpha(c) || c == '_') { state = IN_ID; curr_id += c; } else if (isdigit(c)) { state = IN_NUM; res += c; } else { res += c; } break; case IN_ID: if (isalnum(c) || c == '_') { curr_id += c; } else { res += replace_id_with_function(curr_id, use_python_functions); res += c; curr_id = ""; state = START; } break; case IN_NUM: if (isdigit(c) || c == '.' || c == 'e' || c == '+' || c == '-') { // ok - but must not be exp res += c; } else { if (isalpha(c) || c == '_') { state = IN_ID; curr_id += c; } else { state = START; res += c; } } break; } } if (state == IN_ID) { res += replace_id_with_function(curr_id, use_python_functions); } return res; } std::string get_module_name_w_prefix(const std::string& output_files_prefix, const std::string file_suffix) { if (output_files_prefix == "" || output_files_prefix.back() == '/' || output_files_prefix.back() == '\\') { return file_suffix; } else { size_t pos = output_files_prefix.find_last_of("/\\"); if (pos == string::npos) { return output_files_prefix + "_" + file_suffix; } else { return output_files_prefix.substr(pos) + "_" + file_suffix; } } } void parse_rxn_rule_side( Json::Value& substances_node, std::vector<std::string>& substances, std::vector<std::string>& orientations) { // cannot use BNGL parser directly because reactions may contain orientations substances.clear(); orientations.clear(); string str = substances_node.asString(); // finite automata to parse the reaction side string, e.g. "a + b" enum state_t { START, CPLX, IN_PAREN, AFTER_MOL, AFTER_ORIENT, AFTER_PLUS }; state_t state = START; string current_id; for (size_t i = 0; i < str.size(); i++) { char c = str[i]; switch (state) { case START: if (isalnum(c) || c == '_' || c == '.' || c == '@') { state = CPLX; current_id = c; } else if (isblank(c)) { // ok } else { ERROR("Could not parse reaction side " + str + " (START)."); } break; case CPLX: if (isalnum(c) || c == '_' || c == '.' || c == '@' || c == ':') { current_id += c; } else if (c == '(') { state = IN_PAREN; current_id += '('; } else if (isblank(c) || c == '+' || c == '\'' || c == ',' || c == ';') { substances.push_back(current_id); orientations.push_back(""); if (c == '\'' || c == ',' || c == ';') { orientations.back() = c; } current_id = ""; if (c == '+') { state = AFTER_PLUS; } else { state = AFTER_MOL; } } else { ERROR("Could not parse reaction side " + str + " (MOL_ID)."); } break; case IN_PAREN: if (isalnum(c) || c == '_' || c == ',' || c == '~' || c == '!' || c == '+' || c == '?') { current_id += c; } else if (c == ')') { state = CPLX; current_id += ')'; } else { ERROR("Could not parse reaction side " + str + " (IN_PAREN)."); } break; case AFTER_MOL: if (c == '+') { state = AFTER_PLUS; } else if (c == '\'') { state = AFTER_ORIENT; orientations.back() = c; } else if (c == ',') { state = AFTER_ORIENT; orientations.back() = c; } else if (c == ';') { state = AFTER_ORIENT; orientations.back() = c; } else if (isblank(c)) { // ok } else { ERROR("Could not parse reaction side " + str + " (AFTER_MOL)."); } break; case AFTER_ORIENT: if (c == '+') { state = AFTER_PLUS; } else if (isblank(c)) { // ok } else { ERROR("Could not parse reaction side " + str + " (AFTER_ORIENT)."); } break; case AFTER_PLUS: if (isalnum(c) || c == '_' || c == '@') { state = CPLX; current_id = c; } else if (isblank(c)) { // ok } else { ERROR("Could not parse reaction side " + str + " (AFTER_PLUS)."); } break; default: assert(false); } } if (current_id != "") { substances.push_back(current_id); orientations.push_back(""); } } string remove_compartments(const std::string& species_name) { size_t i = 0; string res; bool in_compartment = false; while (i < species_name.size()) { char c = species_name[i]; if (c == '@') { assert(!in_compartment); in_compartment = true; } else if (in_compartment && (!isalnum(c) && c != '_')) { in_compartment = false; if (c != ':') { res += c; } } else if (!in_compartment) { res += c; } i++; } return res; } // returns "" if there are multiple compartments and sets *has_multiple_compartments to // true if it is not nullptr string get_single_compartment(const std::string& name, bool* has_multiple_compartments) { std::vector<std::string> compartments; API::get_compartment_names(name, compartments); if (has_multiple_compartments != nullptr) { *has_multiple_compartments = false; } if (compartments.empty()) { return ""; } else { string res = compartments[0]; for (size_t i = 1; i < compartments.size(); i++) { if (res != compartments[i]) { // multiple compartments if (has_multiple_compartments != nullptr) { *has_multiple_compartments = true; } return ""; } } return res; } } static string make_cplx(const string bngl_str, const string orient = "", const string compartment = "") { string res = S(MDOT) + API::NAME_CLASS_COMPLEX + "('" + fix_dots_in_simple_species(bngl_str) + "'"; if (orient != "") { res += S(", ") + API::NAME_ORIENTATION + " = " + MDOT + API::NAME_ENUM_ORIENTATION + "." + orient; } if (compartment != "") { res += S(", ") + API::NAME_COMPARTMENT_NAME + " = '" + compartment + "'"; } res += ")"; return res; } bool static is_mdot_superclass(const std::string& name) { return name == S(MDOT) + API::NAME_CV_AllMolecules || name == S(MDOT) + API::NAME_CV_AllVolumeMolecules || name == S(MDOT) + API::NAME_CV_AllSurfaceMolecules; } string make_species_or_cplx( const SharedGenData& data, const std::string& name, const std::string& orient, const std::string& compartment) { bool is_superclass = is_mdot_superclass(name); if (is_superclass && orient == "" && compartment == "") { return name; } if (is_superclass || !data.bng_mode) { stringstream ss; const SpeciesOrMolType* species_info = data.find_species_or_mol_type_info(name); if (is_superclass || (species_info != nullptr && species_info->is_species)) { // substance was declared as species, we can use its id directly ss << make_id(name) << "." << API::NAME_INST << "("; if (orient != "") { assert(compartment == ""); ss << API::NAME_ORIENTATION << " = " << MDOT << API::NAME_ENUM_ORIENTATION << "." << orient; } if (compartment != "") { assert(orient == ""); ss << API::NAME_COMPARTMENT_NAME << " = '" << compartment << "'"; } ss << ")"; return ss.str(); } } // otherwise we will generate a BNGL string return make_cplx(name, orient, compartment); } string reaction_name_to_id(const string& json_name) { string res_name = json_name; replace(res_name.begin(), res_name.end(), ' ', '_'); replace(res_name.begin(), res_name.end(), '.', '_'); replace(res_name.begin(), res_name.end(), ')', '_'); replace(res_name.begin(), res_name.end(), '(', '_'); replace(res_name.begin(), res_name.end(), '!', '_'); replace(res_name.begin(), res_name.end(), '~', '_'); replace(res_name.begin(), res_name.end(), ':', '_'); res_name = regex_replace(res_name, regex("<->"), "revto"); res_name = regex_replace(res_name, regex("->"), "to"); res_name = regex_replace(res_name, regex("\\+"), "plus"); res_name = regex_replace(res_name, regex("\\?"), "any_bond"); res_name = regex_replace(res_name, regex("'"), "_up"); res_name = regex_replace(res_name, regex(","), "_down"); res_name = regex_replace(res_name, regex(";"), "_any"); res_name = regex_replace(res_name, regex("@"), "_at_"); return res_name; } string get_rxn_id(Json::Value& reaction_list_item, uint& unnamed_rxn_counter) { string name = reaction_list_item[KEY_RXN_NAME].asString(); if (name == "") { name = UNNAMED_REACTION_RULE_PREFIX + to_string(unnamed_rxn_counter); unnamed_rxn_counter++; } else { name = reaction_name_to_id(name); } return name; } string create_count_name( const string& what_to_count, const string& where_to_count, const bool molecules_not_species) { // first remove all cterm_refixes regex pattern_cterm(COUNT_TERM_PREFIX); string what_to_count_no_cterm = regex_replace(what_to_count, pattern_cterm, ""); string res = COUNT_PREFIX + fix_id(what_to_count_no_cterm); if (!molecules_not_species) { res += "_species"; } if (where_to_count != WORLD && where_to_count != "") { res += "_" + where_to_count; } return res; } uint get_num_counts_in_mdl_string(const string& mdl_string) { uint res = 0; size_t pos = 0; while ((pos = mdl_string.find(COUNT, pos)) != string::npos) { res++; pos += strlen(COUNT); } return res; } string remove_c_comment(const string& str) { std::regex e ("/\\*.*\\*/"); return std::regex_replace(str, e, ""); } string remove_whitespace(const string& str) { std::regex e ("[ \t]"); return std::regex_replace(str, e, ""); } size_t find_end_brace_pos(const string& str, const size_t start) { int braces_count = 1; assert(str[start] == '['); size_t i = start + 1; while (braces_count > 0 && i < str.size()) { if (str[i] == '[') { braces_count++; } else if (str[i] == ']') { braces_count--; } i++; } return i - 1; } void process_single_count_term( const SharedGenData& data, const string& mdl_string, bool& rxn_not_mol, bool& molecules_not_species, string& what_to_count, string& where_to_count, string& orientation) { // mdl_string is always in the form COUNT[what,where] size_t start_brace = mdl_string.find('['); size_t comma = mdl_string.rfind(','); size_t end_brace = find_end_brace_pos(mdl_string, start_brace); if (mdl_string.find(COUNT) == string::npos) { ERROR("String 'COUNT' was not found in mdl_string '" + mdl_string + "'."); } if (start_brace == string::npos || comma == string::npos || end_brace == string::npos || start_brace > comma || start_brace > end_brace || comma > end_brace ) { ERROR("Malformed mdl_string '" + mdl_string + "'."); } what_to_count = mdl_string.substr(start_brace + 1, comma - start_brace - 1); what_to_count = trim(what_to_count); // default is 'molecules_pattern', for now we are storing the // as a comment because the counting type belongs to the count term, // not to the whole 'reaction_output_list' // TODO: this should resolved in a better way molecules_not_species = true; if (what_to_count.find(MARKER_SPECIES_COMMENT) != string::npos) { molecules_not_species = false; } what_to_count = remove_c_comment(what_to_count); // process orientation orientation = ""; assert(what_to_count != ""); char last_c = what_to_count.back(); if (last_c == '\'' || last_c == ',' || last_c == ';') { string s; s = last_c; orientation = convert_orientation(s); what_to_count = what_to_count.substr(0, what_to_count.size() - 1); } if (data.find_reaction_rule_info(what_to_count) != nullptr) { rxn_not_mol = true; } else { // if we did not find the name to be a reaction, we assume it is a BNGL pattern rxn_not_mol = false; } string where_tmp = mdl_string.substr(comma + 1, end_brace - comma - 1); size_t dot_pos = where_tmp.find('.'); if (dot_pos != string::npos) { // no completely sure when a '.' can appear where_tmp = where_tmp.substr(dot_pos + 1); } where_tmp = trim(where_tmp); if (where_tmp == WORLD) { where_tmp = ""; } // remove all [ALL] and replace box1[box1_sr1] -> box1_box1_sr1 where_to_count = ""; size_t i = 0; while (i < where_tmp.size()) { char c = where_tmp[i]; if (c == '[') { // followed by ALL]? if (i + 4 < where_tmp.size() && where_tmp.substr(i + 1, 4) == "ALL]") { // skip i += 5; } else { // replace where_to_count += '_'; i++; } } else if (c == ']') { // ignore i++; } else { // keep character where_to_count += c; i++; } } } // sets val if the name_or_value is a floating point value, // if not, tries to find the parameter and reads its value // returns true on success // parameters are not evaluated and only one level is tried, // returns false if value was not obtained bool get_parameter_value(Json::Value& mcell, const string& name_or_value, double& val) { try { val = stod(name_or_value); return true; } catch (const std::invalid_argument&) { // not a float, try to get parameter value if (mcell.isMember(KEY_PARAMETER_SYSTEM) && mcell.isMember(KEY_MODEL_PARAMETERS)) { Json::Value& params = mcell[KEY_PARAMETER_SYSTEM][KEY_MODEL_PARAMETERS]; for (Value::ArrayIndex i = 0; i < params.size(); i++) { if (params[i][KEY_NAME].asString() == name_or_value) { try { if (params[i].isMember(KEY__EXTRAS)) { val = stod(params[i][KEY__EXTRAS][KEY_PAR_VALUE].asString()); } else { val = stod(params[i][KEY_PAR_EXPRESSION].asString()); } return true; } catch (const std::invalid_argument&) { return false; } } } } } return false; } bool is_volume_mol_type(Json::Value& mcell, const std::string& mol_type_name) { string mol_type_name_no_comp = remove_compartments(mol_type_name); Value& define_molecules = get_node(mcell, KEY_DEFINE_MOLECULES); check_version(KEY_DEFINE_MOLECULES, define_molecules, VER_DM_2014_10_24_1638); Value& molecule_list = get_node(define_molecules, KEY_MOLECULE_LIST); for (Value::ArrayIndex i = 0; i < molecule_list.size(); i++) { Value& molecule_list_item = molecule_list[i]; check_version(KEY_MOLECULE_LIST, molecule_list_item, VER_DM_2018_10_16_1632); string name = molecule_list_item[KEY_MOL_NAME].asString(); if (name != mol_type_name_no_comp) { continue; } string mol_type = molecule_list_item[KEY_MOL_TYPE].asString(); CHECK_PROPERTY(mol_type == VALUE_MOL_TYPE_2D || mol_type == VALUE_MOL_TYPE_3D); return mol_type == VALUE_MOL_TYPE_3D; } ERROR("Could not find species or molecule type '" + mol_type_name_no_comp + "'."); } static void get_mol_types_in_species(const std::string& species_name, vector<string>& mol_types) { mol_types.clear(); size_t i = 0; string current_name; bool in_name = true; while (i < species_name.size()) { char c = species_name[i]; if (c == '(') { in_name = false; assert(current_name != ""); mol_types.push_back(current_name); current_name = ""; } else if (c == '.') { in_name = true; } else if (in_name && !isspace(c)) { current_name += c; } i++; } if (current_name != "") { mol_types.push_back(current_name); } } bool is_volume_species(Json::Value& mcell, const std::string& species_name) { if (is_simple_species(species_name)) { return is_volume_mol_type(mcell, species_name); } else { vector<string> mol_types; get_mol_types_in_species( species_name, mol_types); for (string& mt: mol_types) { if (!is_volume_mol_type(mcell, mt)) { // surface return false; } } return true; } } } // namespace MCell
1ae3757a05e884a7847b44fcab88556139e318fb
e117951c2aaf2703f213317e2760c6684222872d
/Assignments/Text-Protocol/src/Message.h
c5bbbe8be723c963bd60737fdfa296676fa5d979
[ "MIT" ]
permissive
prince-chrismc/Data-Communication
f3fe052b1864a24bd450d5a1e50288b81758adb1
04df3591ac726c1f330788b6b24cdb15309b5461
refs/heads/master
2021-07-11T22:10:42.921347
2019-02-11T04:10:39
2019-02-11T04:10:39
147,980,393
0
0
MIT
2018-11-16T15:34:14
2018-09-09T00:32:11
C++
UTF-8
C++
false
false
3,316
h
Message.h
/* MIT License Copyright (c) 2018 Chris McArthur, prince.chrismc(at)gmail(dot)com 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. */ #pragma once #include <string> // In little endian, a 32bit integer value of 1 is represented in hex as `0x01 0x00 0x00 0x00` constexpr auto TEST_BYTE = 1; constexpr bool IS_LITTLE_ENDIAN = ( TEST_BYTE == 0x10000000 ); constexpr bool IS_BIG_ENDIAN = ( TEST_BYTE == 0x00000001 ); namespace TextProtocol { template <typename Enum> auto operator++( Enum& e, int ) noexcept { static_assert( std::is_enum<Enum>::value, "type must be an enum" ); Enum temp = e; auto newValue = static_cast<std::underlying_type_t<Enum>>( e ); ++newValue; e = Enum{ newValue }; return temp; } template <typename Enum> Enum& operator++( Enum& e ) noexcept { static_assert( std::is_enum<Enum>::value, "type must be an enum" ); auto newValue = static_cast<std::underlying_type_t<Enum>>( e ); ++newValue; e = Enum{ newValue }; return e; } template <typename Enum> bool operator>( const Enum& lhs, const std::underlying_type_t<Enum>& rhs ) { return static_cast<std::underlying_type_t<Enum>>( lhs ) > rhs; } enum class PacketType : unsigned char { ACK = 0x06, NACK = 0x15, SYN = 0x16, SYN_ACK = SYN + ACK }; enum class SequenceNumber : unsigned long { MAX = 0xffffffffUL }; enum class IpV4Address : unsigned long { }; enum class PortNumber : unsigned short { }; class Message { public: Message( PacketType type, SequenceNumber id, IpV4Address dstIp, PortNumber port ); size_t Size() const; std::string ToByteStream() const; friend std::ostream& operator<<(std::ostream& os, const Message& message ); static Message Parse( const std::string& rawBytes ); static constexpr auto BASE_PACKET_SIZE = sizeof( PacketType ) + sizeof( SequenceNumber ) + sizeof( IpV4Address ) + sizeof( PortNumber ); static constexpr auto MAX_PAYLOAD_LENGTH = 1013; static constexpr auto MAX_MESSAGE_SIZE = BASE_PACKET_SIZE + MAX_PAYLOAD_LENGTH; PacketType m_PacketType; SequenceNumber m_SeqNum; IpV4Address m_DstIp; PortNumber m_DstPort; std::string m_Payload = "Hello World!"; // max 1014 bytes }; }
9e3c60d06b71711ed182e9c1e0b5903cc8ea63b0
90d39aa2f36783b89a17e0687980b1139b6c71ce
/Codechef/aug12long/BLOCKING.cpp
f750c4d59c5548f87c13667729d7ab4f2b88ba70
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,486
cpp
BLOCKING.cpp
/* Nimesh Ghelani (nims11) */ #include<iostream> #include<cstdio> #include<algorithm> #include<map> #include<string> #include<vector> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",&a) #define newline printf("\n") #define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b #define SWAP(a,b) {int tmp=a;a=b;b=tmp;} #define P_I(a) printf("%d",a) using namespace std; struct foo { int T,H; friend bool operator<(const foo &a,const foo &b) { return a.T<b.T; } }bar[100][100]; int n; int visited[101]; bool getans(int N) { if(N==-1)return true; int i=0; while(i<n && (visited[bar[N][i].H]>bar[N][i].T || visited[bar[N][i].H]==-1)) { i++; } P_I(i);newline; for(i=i-1;i>=0;i--) { if(visited[bar[N][i].H]==-1) { visited[bar[N][i].H]=bar[N][i].T; if(getans(N-1)){printf("%d ",bar[N][i].H+1);return true;} visited[bar[N][i].H]=-1; } } return false; } int main() { in_I(n); for(int i=0;i<n;i++)visited[i]=-1; for(int i=0;i<n;i++) for(int j=0;j<n;j++) { in_I(bar[i][j].T); bar[i][j].H=j; } for(int i=0;i<n;i++) sort(bar[i],bar[i]+n); // for(int i=0;i<n;i++) // {for(int j=0;j<n;j++) // cout<<bar[i][j].T<<","<<bar[i][j].H<<" "; // cout<<endl;} if(!getans(n-1)) printf("-1\n"); }
c999d75b05fb2c3319ee53b2ff2b9b0b246daa7c
3278711458bdc044d263b7c58655a8e4164a9e48
/vault13/volume/src/volume.h
54e59876247f9022fbb2b6b165157705f2c4bcce
[]
no_license
z80/prototyping
964b96e32623336d20c3b87e34f38e0f32956dd9
b95a6b4a1350b527886180fd854310eed395fca2
refs/heads/master
2020-04-07T03:26:58.947548
2019-07-02T15:23:37
2019-07-02T15:23:37
158,016,718
2
0
null
null
null
null
UTF-8
C++
false
false
506
h
volume.h
#ifndef __VOLUME_H_ #define __VOLUME_H_ #include "Ogre.h" #include "OgreApplicationContext.h" #include "OgreVolumeChunk.h" #include "OgreVolumeCSGSource.h" #include "OgreVolumeCacheSource.h" #include "OgreVolumeTextureSource.h" using namespace Ogre; using namespace Volume; class Volume2 { public: Volume2( SceneManager * smgr ); ~Volume2(); void create(); void destroy(); private: SceneManager * smgr; Chunk * volume; SceneNode * volumeNode; }; #endif
f441356770ef0ffab2390313171b4371f4eebbd6
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/Assembly-CSharp/PhysicsEffects.h
31db279bdae37622d712ef31b19201ca7c2e33e0
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
801
h
PhysicsEffects.h
#pragma once #include "BaseEntity.h" #include "SoundDefinition.h" namespace rust { class PhysicsEffects : public MonoBehaviour // 0x18 { public: BaseEntity* entity; // 0x18 (size: 0x8, flags: 0x6, type: 0x12) SoundDefinition* physImpactSoundDef; // 0x20 (size: 0x8, flags: 0x6, type: 0x12) float minTimeBetweenEffects; // 0x28 (size: 0x4, flags: 0x6, type: 0xc) float lastEffectPlayed; // 0x2c (size: 0x4, flags: 0x1, type: 0xc) float lowMedThreshold; // 0x30 (size: 0x4, flags: 0x6, type: 0xc) float medHardThreshold; // 0x34 (size: 0x4, flags: 0x6, type: 0xc) float enableDelay; // 0x38 (size: 0x4, flags: 0x6, type: 0xc) float enabledAt; // 0x3c (size: 0x4, flags: 0x1, type: 0xc) float ignoreImpactThreshold; // 0x40 (size: 0x4, flags: 0x1, type: 0xc) }; // size = 0x48 }
1d821fefaeb02ad11a89937fa1026b821b022b5c
a29da28e699887f1d7fc3d61e75982aee71e1c93
/process_generator.cc
5692d34e5bbb6cca3bbf9168bdba965be982c996
[]
no_license
guybrush2105/schedulersimulator
74e081115079f1fb3de3e6fb91f27c2e7c062398
3be1de3aa3a52f48b4ed18fcc2cdd3a59b394576
refs/heads/master
2022-03-22T10:05:56.911500
2019-11-21T17:14:55
2019-11-21T17:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
cc
process_generator.cc
#include <sys/msg.h> #include <unistd.h> #include "task_struct.hh" #include "queue.hh" #include "mem.hh" /*! * \file process_generator.cc */ //! Funzione definita in sem.cc void down(int sem_id, int n_sem = 0); //! Funzione definita in sem.cc void up(int sem_id, int n_sem = 0); //! Funzione definita in execute.cc void execute(task_struct, mem*); /*! \brief Generatore di processi \param cpu_queue Puntatore all'area di memoria condivisa contenente la struttura dati per la coda di ready \param shmem Puntatore alla zona condivisa contenente la struttura dati mem \param cpu_queue_sem_id Identificatore del semaforo per la mutua esclusione sulla coda di cpu \param io_queue_sem_id Identificatore del semaforo per la mutua esclusione sulla coda di io A comando dell'utente genera un processo attraverso la funzione fork(). Il processo cosi' generato, chiama la funzione execute() che simula la sua esecuzione */ void process_generator(queue *cpu_queue, mem *shmem, int cpu_queue_sem_id, int io_queue_sem_id) { char c = '1'; while(c != '0') { std::cout << "MENU" << '\n'; std::cout << " Premi 1: Genera un processo" << '\n'; std::cout << " Premi 2: Genera un processo con statistiche a scelta" << '\n'; std::cout << " Premi 0: Esci" << std::endl; std::cout << "Scelta: "; std::cin >> c; if(c == '1' || c == '2') { task_struct process; if(c == '2') { int io_use; int cpu_burst; std::cout << "Numero di accessi al dispositivo di i/o: " << std::endl; std::cin >> io_use; std::cout << "Burst iniziale di cpu: " << std::endl; std::cin >> cpu_burst; process.stats.io_use = io_use; process.stats.cpu_burst = cpu_burst; }; process.msg_id = msgget(IPC_PRIVATE, IPC_CREAT | 0666 ); process.pid = fork(); if(process.pid == 0) //mando in esecuzione il figlio execute(process, shmem); std::cout << "Creato processo " << process.pid << std::endl; //Il generatore mette in coda di cpu il processo creato down(cpu_queue_sem_id); cpu_queue -> push_back(process); up(cpu_queue_sem_id); } else if(c == '0') std::cout << "Uscita ..." << std::endl; else std::cout << "Errore!" << std::endl; }; shmem -> exit = 0; exit(0); };
0389ace93a51b3ee9cfbde1bb48c18236d3d4024
e1da11e5a4f12c98e92b4c87fcb0c65dcf8942d9
/KinectOpenCV/Mesh.h
73f9d012e8a4ee862490447b772984d8ad24edd4
[]
no_license
WPI-ARC/cloth_tracking
70e8b5b420d68361023a56f43b1bd7ba57f6f579
973fcbc4a12a40dbb364ea8adbfc5fcd150bfeda
refs/heads/master
2016-08-12T09:54:54.054235
2016-02-11T00:39:41
2016-02-11T00:39:41
49,797,236
0
1
null
null
null
null
UTF-8
C++
false
false
2,945
h
Mesh.h
/** * Author Michael McConnell * Date: 10/9/2015 * SDK's: OpenCV 3.0 * * This class represents a surface interpolation. The points are ordered from top left to bottom right row wise. */ #pragma once #ifndef MESH_H #define MESH_H #include "stdafx.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> #include "opencv2/video/tracking.hpp" #include "opencv2\shape\shape_transformer.hpp" #include <iostream> using namespace std; /** * \brief The Mesh class reprents a multi point interpolation. The points are ordered from top left to bottom right row wise. */ class Mesh { public: /** \brief The default constructor*/ Mesh(); /** \overload \brief Constructor: Builds rectangular mesh from retangluar bounds with the given number of segments on each side.*/ Mesh(cv::Rect bounds, int segments); /** \overload \brief Constructor: Builds mesh from vector of 2d points with the provided number of rows and cols. This is not interpolated.*/ Mesh(const vector<cv::Point2f>& vec, int rows, int cols); /** \overload \brief Copy Contructor: Builds new mesh from provided mesh.*/ Mesh(const Mesh& m); /** \brief Builds rectangular mesh from retangluar bounds with the given number of segments on each side.*/ void makeInterpolatedMesh(const cv::Rect& bounds, int segments); /** \brief Draws the mesh onto the provided image Mat*/ void drawMesh(cv::Mat& img); /** \brief Generates a vector of 2d points from the mesh. Vector has length rows * cols.*/ vector<cv::Point2f> getVectorFromMesh(); /** \brief Builds mesh from vector of 2d points with the provided number of rows and cols. This is not interpolated.*/ void makeMeshFromVector(const vector<cv::Point2f>& vec, int cols, int rows); /** \brief Returns the 3d Point Vector at the provided Mesh coordinates.*/ cv::Vec3f& at(int r, int c); /** \brief Returns the number of Rows in the Mesh*/ int getRows(); /** \brief Returns the number of Cols in the Mesh*/ int getCols(); /** \brief Finds the nearest Mesh index with 2d coordinates closet to the provided point.*/ static cv::Vec2i getNearestPointCoordinates(cv::Point p, cv::Mat& mesh); /** \brief Returns THe distance between two 2d points*/ static float distanceToPoint(cv::Point p1, cv::Point p2); /** \brief Returns the rectangular bounds of a vector of 2d points.*/ static cv::Rect getVectorBounds(vector<cv::Point>& data); /** The Data Mat for the Mesh Object. Each index holds a 3d Point Vector representing that points 3d locations.*/ cv::Mat meshPoints; /** A vector which holds the control (measured) points of the mesh. The value stored in each index coresponds to that points index in meshPoints. */ vector<cv::Vec2i> controlIndex; //Each point Vec2i in this vector stores the row and col of a control point in the mesh. private: }; #endif
da17a73bdf755db7c2e99f97c71d4ed85211eddf
038e3bed7eef1fae2d4d19b25f9f378b4fc091ed
/lab14_1.cpp
8c4317fe0733996081fce724b4f1855c3badabe1
[]
no_license
ChayanonPitak/lab14
08c6324d9b572bc1369419c4bc907912b03c4a25
8f77bed4066d0f07440886c20e1c540e4d4f8f28
refs/heads/master
2023-02-25T23:12:33.182652
2021-02-02T09:07:30
2021-02-02T09:07:30
335,208,531
0
0
null
null
null
null
UTF-8
C++
false
false
597
cpp
lab14_1.cpp
#include <iostream> using namespace std; int a = 5; char b = 'A'; char &c = b; int *x = &a; char *y = &b; int **z = &x; void ShowVar() { cout << a << " "; cout << b << " "; cout << c << " "; cout << x << " "; cout << (void *) y << " "; cout << z << endl; return; } void ShowAddress() { cout << &a << " "; cout << (void *) &b << " "; cout << (void *) &c << " "; cout << &x << " "; cout << (void *) &y << " "; cout << &z << endl; return; } int main(){ ShowVar(); ShowAddress(); c = 'F'; ShowVar(); *y = 'W'; ShowVar(); *x = 6; ShowVar(); **z = 7; ShowVar(); return 0; }
3e6ae75d047780778ee1dff6e0840a14737a7476
c675d42a6261ecfc09198c20a9a2e60d90e19f47
/Arduino Basics and Kinematics/Reference/Robot Documentation/BOE Bot/Shield-Bot-Code-2013-12-01/RoboticsBOEShield_Ch4_20120310/ControlWithCharacters/ControlWithCharacters.ino
4620716752590b74453e08b60a399c9dabb83a37
[]
no_license
ryanhjohnston1204/Arduino-SLAM
0e13a7c2512a8a1f7bf1f7b29bcce1f2a5f9f138
77065e75473583ccb0ee43977980592001f52a08
refs/heads/master
2022-12-01T13:18:42.592943
2020-08-16T03:44:04
2020-08-16T03:44:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,185
ino
ControlWithCharacters.ino
// Robotics with the BOE Shield – ControlWithCharacters // Move forward, left, right, then backward for testing and tuning. #include <Servo.h> // Include servo library char maneuvers[] = "fffffffffflllrrrbbbbbbbbbbs"; Servo servoLeft; // Declare left and right servos Servo servoRight; void setup() // Built-in initialization block { tone(4, 3000, 1000); // Play tone for 1 second delay(1000); // Delay to finish tone servoLeft.attach(13); // Attach left signal to P13 servoRight.attach(12); // Attach right signal to P12 // Parse maneuvers and feed each successive character to the go function. int index = 0; do { go(maneuvers[index]); } while(maneuvers[index++] != 's');} void loop() // Main loop auto-repeats { // Empty, nothing needs repeating } void go(char c) // go function { switch(c) // Switch to code based on c { case 'f': // c contains 'f' servoLeft.writeMicroseconds(1700); // Full speed forward servoRight.writeMicroseconds(1300); break; case 'b': // c contains 'b' servoLeft.writeMicroseconds(1300); // Full speed backward servoRight.writeMicroseconds(1700); break; case 'l': // c contains 'l' servoLeft.writeMicroseconds(1300); // Rotate left in place servoRight.writeMicroseconds(1300); break; case 'r': // c contains 'r' servoLeft.writeMicroseconds(1700); // Rotate right in place servoRight.writeMicroseconds(1700); break; case 's': // c contains 's' servoLeft.writeMicroseconds(1500); // Stop servoRight.writeMicroseconds(1500); break; } delay(200); // Execute for 0.2 seconds }
b1d28afb48dd1154a6da78e9832fcc5f0da2d8ec
fd862ecd66cc69f9d6e115130cbb29b6a7c1269e
/ztechallenge2020/utilities.cpp
95894c6dd9836503ea6bde1ca0fffb85216b5c99
[]
no_license
lyandut/ztechallenge2020
cfd0062f5a3d59ad5f1999a547fe0a5edd5b3ac3
59bac826c4160b1a9b466190b18a8a28daf411b2
refs/heads/master
2022-07-05T15:17:59.381420
2020-05-10T19:57:01
2020-05-10T19:57:01
262,865,193
0
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
utilities.cpp
#include "utilities.h" void split(const string& s, vector<string>& tokens, const string& delimiters) { tokens.clear(); string::size_type lastPos = s.find_first_not_of(delimiters, 0); string::size_type pos = s.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { tokens.push_back(s.substr(lastPos, pos - lastPos)); lastPos = s.find_first_not_of(delimiters, pos); pos = s.find_first_of(delimiters, lastPos); } }
60926ab69f24be22c2e93831a59d96d7c664b99b
b751d78debdc9ad12b880b15fa5db2834c68dd7f
/source/screens/Screen_TimerRecharge.h
beb6e4c89f35664dd3caf98f6fa4dec9a5079860
[ "MIT" ]
permissive
rbultman/tv-timer
a341e81a2c6f6fe83a0eee4b0923a297945a3294
29b0fc9f9d96fc8b1c294d21a51505a1fd2ed9ff
refs/heads/main
2023-03-11T19:28:43.920502
2021-03-01T11:06:47
2021-03-01T11:06:47
323,670,046
0
0
null
null
null
null
UTF-8
C++
false
false
768
h
Screen_TimerRecharge.h
/* Screen_TimerRecharge.h A screen that shows the time, date, and a recharge counter. Author: Rob Bultman License: MIT */ #ifndef SCREEN_TIMER_RECHARGE_H #define SCREEN_TIMER_RECHARGE_H #include "lvgl.h" #include "screen_class.h" #include "ds3231.h" class Screen_TimerRecharge : public ScreenClass { public: Screen_TimerRecharge() : timeLabel(NULL), dateLabel(NULL) {} lv_obj_t *CreateScreen(lv_indev_t *pInputDevice, bool hasNextButton = false, bool hasPreviousButton = false); void UpdateScreen(time_t currentEpoch, ds3231_alrm_t &alarmTime); private: static void EventHandler(lv_obj_t *obj, lv_event_t event); lv_obj_t *timeLabel; lv_obj_t *dateLabel; lv_obj_t *rechargeLabel; }; #endif // SCREEN_TIMER_RECHARGE_H
25021064fcafe0bfea361d6d306598fd36b8bce6
cfe790e3fdef80c64e208327929d923cf235a5f0
/LAB3.cpp
2810b0c84647a11c1056eb97cd96edd11be7814a
[]
no_license
IvanVlichko824/GameTheory
4d5976aed55f209c98068c3144d3f92daa5a9f57
eaf832e81ce376796c6a0ef65517b38d8d2d50e1
refs/heads/master
2023-05-07T00:08:41.034920
2021-05-23T13:39:46
2021-05-23T13:39:46
293,121,496
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
16,643
cpp
LAB3.cpp
#include <iostream> #include <ctime> #include <cmath> #include <vector> #include <iomanip> using namespace std; //Функция транспонирования матрицы template <typename T> void TransponMtx(T** matr, T** tMatr, int n) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) tMatr[j][i] = matr[i][j]; } //Функция освобождения памяти template <typename T> void FreeMem(T** matr, int n) { for (int i = 0; i < n; i++) delete[] matr[i]; delete[] matr; } //Функция заполнения матрицы template <typename T> void SetMtx(T** matr, vector<vector<int>> M, int n) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { matr[i][j] = M[i][j]; } } //Функция печати матрицы template <typename T> void PrintMtx(T** matr, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << setw(20) << setprecision(4) << matr[i][j] << " "; cout << endl; } } //Функция вычеркивания строки и столбца void Get_matr(int** matr, int n, int** temp_matr, int indRow, int indCol) { int ki = 0; for (int i = 0; i < n; i++) { if (i != indRow) { for (int j = 0, kj = 0; j < n; j++) { if (j != indCol) { temp_matr[ki][kj] = matr[i][j]; kj++; } } ki++; } } } //Функция вычисления определителя матрицы int Det(int** matr, int n) { int temp = 0; //Временная переменная для хранения определителя int k = 1; //Степень if (n < 1) { cout << "Ошибка ввода: некорректный размер матрицы" << endl; return 0; } else if (n == 1) temp = matr[0][0]; else if (n == 2) temp = matr[0][0] * matr[1][1] - matr[1][0] * matr[0][1]; else { for (int i = 0; i < n; i++) { int m = n - 1; int** temp_matr = new int*[m]; for (int j = 0; j < m; j++) temp_matr[j] = new int[m]; Get_matr(matr, n, temp_matr, 0, i); temp = temp + k * matr[0][i] * Det(temp_matr, m); k = -k; FreeMem(temp_matr, m); } } return temp; } void matrFill(vector<vector<int>> &M, int n) { //Случайное заполнение матриц for (int i = 0; i < n; i++) { vector<int> temp; for (int j = 0; j < n; j++) { int znak = rand() % 2; if (znak == 0) temp.push_back(rand() % 50); if (znak == 1) temp.push_back((rand() % 50) * -1); } M.push_back(temp); } } void bimatrFill(vector<vector<int>> &TA, vector<vector<int>> &TB, int n) { for (int i = 0; i < 2; i++) { vector<int> temp; for (int j = 0; j < 2; j++) { temp.push_back(0); } TA.push_back(temp); TB.push_back(temp); } TA[0][0] = 5; TB[0][0] = 0; TA[0][1] = 8; TB[0][1] = 4; TA[1][0] = 7; TB[1][0] = 6; TA[1][1] = 6; TB[1][1] = 3; } void matrZeroFill(vector<vector<int>>& A, vector<vector<int>>& B, int n) { //Создание матриц для нахождения пересечения множеств for (int i = 0; i < n; i++) { vector<int> temp; for (int j = 0; j < n; j++) { temp.push_back(0); } A.push_back(temp); B.push_back(temp); } } void matrPrint(vector<vector<int>> A, vector<vector<int>> B, int n) { //Вывод матрицы стратегий двух игроков for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << "(" << setw(3) << A[i][j] << ", " << setw(3) << B[i][j] << ") "; } cout << endl; } } int checkMaxStr(vector<vector<int>> M, int n, int x) { //Поиск максимума по строке int max = -100; int m; int unique = 0; for (int j = 0; j < n; j++) { if (M[x][j] > max) { max = M[x][j]; m = j; } } for (int j = 0; j < n; j++) { if (M[x][j] == max) { //Проверка на уникальность максимума unique++; } } if (unique > 1) { //cout << "Для строки " << x + 1 << " уникальность максимума не достигнута (" << max << ")" << endl; return n; } return m; } int checkMaxStl(vector<vector<int>> M, int n, int x) { //Поиск максимума по столбцу int max = -100; int m; int unique = 0; for (int j = 0; j < n; j++) { if (M[j][x] > max) { max = M[j][x]; m = j; } } for (int j = 0; j < n; j++) { if (M[j][x] == max) { //Проверка на уникальность максимума unique++; } } if (unique > 1) { //cout << "Для столбца " << x + 1 << " уникальность максимума не достигнута (" << max << ")" << endl; return n; } return m; } void nashCheck(vector<vector<int>> A, vector<vector<int>> B, vector<vector<int>> &tN, int n) { vector<vector<int>> nash; for (int i = 0; i < n; i++) { vector<int> temp; for (int j = 0; j < n; j++) { temp.push_back(0); } nash.push_back(temp); } for (int i = 0; i < n; i++) { if (checkMaxStl(A, n, i) != n) { //cout << "Макс. в столбце " << i + 1 << " для игрока А: " << A[checkMaxStl(A, n, i)][i] << endl; nash[checkMaxStl(A, n, i)][i]++; } if (checkMaxStr(B, n, i) != n) { //cout << "Макс. в строке " << i + 1 << " для игрока В: " << B[i][checkMaxStr(B, n, i)] << endl; nash[i][checkMaxStr(B, n, i)]++; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (nash[i][j] == 2) cout << setw(1) << " + "; if (nash[i][j] == 1) cout << setw(1) << " = "; if (nash[i][j] == 0) cout << setw(1) << " - "; } cout << endl; } cout << "Равновесие Нэша: " << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (nash[i][j] == 2) cout << "(" << setw(3) << A[i][j] << ", " << setw(3) << B[i][j] << ") " << endl; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { tN[i][j] = nash[i][j]; } } } void matrExamples(vector<vector<int>> &Pa, vector<vector<int>> &Sa, vector<vector<int>> &Da, vector<vector<int>> &Pb, vector<vector<int>> &Sb, vector<vector<int>> &Db) { //Заполнение матриц-примеров for (int i = 0; i < 2; i++) { vector<int> temp; for (int j = 0; j < 2; j++) { temp.push_back(0); } Pa.push_back(temp); Pb.push_back(temp); Sa.push_back(temp); Sb.push_back(temp); Da.push_back(temp); Db.push_back(temp); } Pa[0][0] = -1; Pb[0][0] = -1; Pa[0][1] = -2; Pb[0][1] = 2; Pa[1][0] = 2; Pb[1][0] = -5; Pa[1][1] = -7; Pb[1][1] = -7; Sa[0][0] = 4; Sb[0][0] = 1; Sa[0][1] = 0; Sb[0][1] = 0; Sa[1][0] = 0; Sb[1][0] = 0; Sa[1][1] = 1; Sb[1][1] = 4; Da[0][0] = -5; Db[0][0] = -5; Da[0][1] = 0; Db[0][1] = -10; Da[1][0] = -10; Db[1][0] = 0; Da[1][1] = -1; Db[1][1] = -1; } void paretoCheck(vector<vector<int>> A, vector<vector<int>> B, vector<vector<int>> &tP, int n) { vector<vector<int>> pareto; for (int i = 0; i < n; i++) { vector<int> temp; for (int j = 0; j < n; j++) { temp.push_back(0); } pareto.push_back(temp); } //int c = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int i2 = 0; i2 < n; i2++) { for (int j2 = 0; j2 < n; j2++) { if (((A[i][j] <= A[i2][j2]) && (B[i][j] < B[i2][j2])) || ((A[i][j] < A[i2][j2]) && (B[i][j] <= B[i2][j2]))) { pareto[i][j]++; } } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (pareto[i][j] > 0) cout << setw(1) << " - "; if (pareto[i][j] == 0) cout << setw(1) << " + "; } cout << endl; } cout << "Оптимальные по Парето: " << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (pareto[i][j] == 0) cout << "(" << setw(3) << A[i][j] << ", " << setw(3) << B[i][j] << ") " << endl; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { tP[i][j] = pareto[i][j]; } } } void findCol(vector<vector<int>> A, vector<vector<int>> B, vector<vector<int>> tN, vector<vector<int>> tP, int n) { vector<vector<int>> col; int c = 0; for (int i = 0; i < n; i++) { vector<int> temp; for (int j = 0; j < n; j++) { temp.push_back(0); } col.push_back(temp); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((tN[i][j] == 2) && (tP[i][j] == 0)) { col[i][j]++; c++; } } } if (c == 0) { cout << "Нет пересечения множеств" << endl; } else { cout << "Пересечение:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (col[i][j] == 1) { cout << "(" << setw(3) << A[i][j] << ", " << setw(3) << B[i][j] << ") " << endl; } } } } } template <typename T> void FindMtx(T** tobr_matr, int n) { vector<float> res; for (int i = 0; i < n; i++) { res.push_back(0); } vector<float> u; for (int i = 0; i < n; i++) { u.push_back(1); } for (int i = 0; i < n; i++) { float temp = 0; for (int j = 0; j < n; j++) { temp += tobr_matr[i][j] * u[i]; } res[i] = temp; } cout << "uB^-1 = ("; for (int i = 0; i < n; i++) { cout << res[i]; if (i != n - 1) cout << ", "; } cout << ") " << endl; float temp = 0; for (int i = 0; i < n; i++) temp += res[i]; cout << "v1 = uB^-1u = " << 1 / temp << endl; cout << "x = ["; for (int i = 0; i < n; i++) { cout << res[i] / temp; if (i != n - 1) cout << ", "; } cout << "] " << endl; } template <typename T> void FindMty(T** tobr_matr, int n) { vector<float> res; for (int i = 0; i < n; i++) { res.push_back(0); } vector<float> u; for (int i = 0; i < n; i++) { u.push_back(1); } for (int i = 0; i < n; i++) { float temp = 0; for (int j = 0; j < n; j++) { temp += tobr_matr[j][i] * u[i]; } res[i] = temp; } cout << "A^-1u = ("; for (int i = 0; i < n; i++) { cout << res[i]; if (i != n - 1) cout << ", "; } cout << ") " << endl; float temp = 0; for (int i = 0; i < n; i++) temp += res[i]; cout << "v2 = uA^-1u = " << 1 / temp << endl; cout << "y = ["; for (int i = 0; i < n; i++) { cout << res[i] / temp; if (i != n - 1) cout << ", "; } cout << "] " << endl; } int main() { srand(unsigned(time(0))); setlocale(0, ""); cout << "================== Задание 1 ==================" << endl; int n = 10; vector<vector<int>> A; vector<vector<int>> B; //Матрицы стратегий игроков А и В vector<vector<int>> PA, PB, SA, SB, DA, DB, tA, tB, tNas, tPar; matrFill(A, n); matrFill(B, n); //Случайное заполнение матриц стратегий игроков А и В matrPrint(A, B, n); //Вывод матрицы стратегий игроков А и В matrZeroFill(tNas, tPar, n); //Создание матриц для нахождения пересечения множеств cout << endl << "----------- Поиск равновесия Нэша -----------" << endl; nashCheck(A, B, tNas, n); cout << endl << "---------- Оптимальность по Парето ----------" << endl; paretoCheck(A, B, tPar, n); cout << endl << "---------- Нахождение пересечений ----------" << endl; findCol(A, B, tNas, tPar, n); cout << endl << "====== Проверка алгоритмов на примерах ======" << endl; matrExamples(PA, SA, DA, PB, SB, DB); cout << endl << "==== Перекресток (с разными отклонениями) ====" << endl; matrPrint(PA, PB, 2); cout << endl << "----------- Поиск равновесия Нэша -----------" << endl; nashCheck(PA, PB, tNas, 2); cout << endl << "---------- Оптимальность по Парето ----------" << endl; paretoCheck(PA, PB, tPar, 2); cout << endl << "---------- Нахождение пересечений ----------" << endl; findCol(PA, PB, tNas, tPar, 2); cout << endl << "=============== Семейный спор ===============" << endl; matrPrint(SA, SB, 2); cout << endl << "----------- Поиск равновесия Нэша -----------" << endl; nashCheck(SA, SB, tNas, 2); cout << endl << "---------- Оптимальность по Парето ----------" << endl; paretoCheck(SA, SB, tPar, 2); cout << endl << "---------- Нахождение пересечений ----------" << endl; findCol(SA, SB, tNas, tPar, 2); cout << endl << "=========== Дилемма заключенного ===========" << endl; matrPrint(DA, DB, 2); cout << endl << "----------- Поиск равновесия Нэша -----------" << endl; nashCheck(DA, DB, tNas, 2); cout << endl << "---------- Оптимальность по Парето ----------" << endl; paretoCheck(DA, DB, tPar, 2); cout << endl << "---------- Нахождение пересечений ----------" << endl; findCol(DA, DB, tNas, tPar, 2); cout << endl << "=============== Задание 2 ==================" << endl; bimatrFill(tA, tB, 2); matrPrint(tA, tB, 2); cout << endl << "----------- Поиск равновесия Нэша -----------" << endl; nashCheck(tA, tB, tNas, 2); cout << endl << "--------- Нахождение обратных матриц ---------" << endl; int det; n = 2; //Определитель и размер матрицы int** matr = new int*[n]; int** matrb = new int*[n]; //Матрицы значений double** obr_matr = new double*[n]; double** obr_matrb = new double*[n]; //Обратные матрицы double** tobr_matr = new double*[n]; double** tobr_matrb = new double*[n]; //Транспонированные обратные матрицы for (int i = 0; i < n; i++) { matr[i] = new int[n]; matrb[i] = new int[n]; obr_matr[i] = new double[n]; obr_matrb[i] = new double[n]; tobr_matr[i] = new double[n]; tobr_matrb[i] = new double[n]; } SetMtx(matr, tA, n); SetMtx(matrb, tB, n); cout << "Матрица А: " << endl; PrintMtx(matr, n); det = Det(matr, n); cout << "Определитель матрицы = " << det << endl; if (det) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int m = n - 1; int** temp_matr = new int*[m]; for (int k = 0; k < m; k++) temp_matr[k] = new int[m]; Get_matr(matr, n, temp_matr, i, j); obr_matr[i][j] = pow(-1.0, i + j + 2) * Det(temp_matr, m) / det; FreeMem(temp_matr, m); } } } else cout << "Определитель матрицы равен 0 => матрица является вырожденной и обратной нет" << endl; //Транспонирование матрицы TransponMtx(obr_matr, tobr_matr, n); //Печать обратной матрицы после транспонирования cout << "Обратная матрица: " << endl; PrintMtx(tobr_matr, n); cout << "Матрица В: " << endl; PrintMtx(matrb, n); det = Det(matrb, n); cout << "Определитель матрицы = " << det << endl; if (det) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int m = n - 1; int** temp_matrb = new int*[m]; for (int k = 0; k < m; k++) temp_matrb[k] = new int[m]; Get_matr(matrb, n, temp_matrb, i, j); obr_matrb[i][j] = pow(-1.0, i + j + 2) * Det(temp_matrb, m) / det; FreeMem(temp_matrb, m); } } } else cout << "Определитель матрицы равен 0 => матрица является вырожденной и обратной нет" << endl; //Транспонирование матрицы TransponMtx(obr_matrb, tobr_matrb, n); //Печать обратной матрицы после транспонирования cout << "Обратная матрица: " << endl; PrintMtx(tobr_matrb, n); FindMtx(obr_matrb, n); FindMty(obr_matr, n); //Освобождение памяти FreeMem(tobr_matr, n); FreeMem(matr, n); FreeMem(obr_matr, n); FreeMem(tobr_matrb, n); FreeMem(matrb, n); FreeMem(obr_matrb, n); system("Pause"); }
ee2df59b545ffa1e7264c6d87bce7fc378085cd0
0272bb2b79089db5e47b0332bc75a95b96e8ea00
/robosherlock/src/queryanswering/src/RosPrologInterface.cpp
ab57cd2a25995a34d6db01cc92fac1214abe4741
[]
no_license
RoboSherlock/robosherlock
701bc6cd84e2195e7c157b69e031e4efe63f1d72
05f267924175802e7a42008a1125b2e4c7d49c6d
refs/heads/master
2022-06-16T08:28:42.169944
2021-09-23T13:39:02
2021-09-23T13:39:02
44,106,043
28
42
null
2022-03-21T10:52:35
2015-10-12T12:29:16
C++
UTF-8
C++
false
false
10,715
cpp
RosPrologInterface.cpp
#include <robosherlock/queryanswering/RosPrologInterface.h> #ifdef WITH_ROS_PROLOG namespace rs { RosPrologInterface::RosPrologInterface() { outInfo("Creating ROS Service client for rosprolog"); } bool RosPrologInterface::assertValueForKey(const std::string& key, const std::string& value) { std::stringstream assertionQuery; assertionQuery << "assert(rs_query_reasoning:requestedValueForKey(" << key << "," << (value == "" ? "\'\'" : value) << "))"; outInfo("Calling query: " << assertionQuery.str()); PrologQuery bdgs = queryWithLock(assertionQuery.str()); if (bdgs.begin() != bdgs.end()) { outInfo("Asserted: " << assertionQuery.str()); return true; } else { outError("Asserttion: " << assertionQuery.str() << " failed!"); return false; } } bool RosPrologInterface::retractQueryKvPs() { queryWithLock("retract(rs_query_reasoning:requestedValueForKey(_,_))"); return true; } bool RosPrologInterface::checkValidQueryTerm(const std::string& term) { std::stringstream checkTermQuery; checkTermQuery << "rs_query_predicate(" << term << ")"; PrologQuery bindings = queryWithLock(checkTermQuery.str()); if (bindings.begin() != bindings.end()) return true; else return false; } std::string RosPrologInterface::buildPrologQueryFromKeys(const std::vector<std::string>& keys) { std::string prologQuery = "pipeline_from_predicates_with_domain_constraint(["; for (unsigned int i = 0; i < keys.size(); i++) { prologQuery += keys.at(i); if (i < keys.size() - 1) { prologQuery += ","; } } prologQuery += "], A)"; return prologQuery; } bool RosPrologInterface::planPipelineQuery(const std::vector<std::string>& keys, std::vector<std::string>& pipeline) { outInfo("Calling Json Prolog"); PrologQuery bdgs = queryWithLock(buildPrologQueryFromKeys(keys)); if (bdgs.begin() == bdgs.end()) { outInfo("Can't find solution for pipeline planning"); return false; // Indicate failure } for (auto bdg : bdgs) { pipeline = createPipelineFromPrologResult(bdg["A"].toString()); } return true; } std::vector<std::string> RosPrologInterface::createPipelineFromPrologResult(std::string queryResult) { std::vector<std::string> new_pipeline; // Strip the braces from the result queryResult.erase(queryResult.end() - 1); queryResult.erase(queryResult.begin()); std::stringstream resultstream(queryResult); std::string token; while (std::getline(resultstream, token, ',')) { // erase leading whitespaces token.erase(token.begin(), std::find_if(token.begin(), token.end(), std::bind1st(std::not_equal_to<char>(), ' '))); outDebug("Planned Annotator by Prolog Planner " << token); // From the extracted tokens, remove the prefix std::string prefix("http://knowrob.org/kb/rs_components.owl#"); uint8_t prefix_length = prefix.length(); // Erase by length, to avoid string comparison token.erase(0, prefix_length); // outInfo("Annotator name sanitized: " << token ); new_pipeline.push_back(token); } return new_pipeline; } bool RosPrologInterface::q_subClassOf(std::string child, std::string parent) { std::stringstream prologQuery; if (addNamespace(child) && addNamespace(parent)) { prologQuery << "owl_subclass_of(" << child << "," << parent << ")."; outInfo("Asking Query: " << prologQuery.str()); PrologQuery bdgs = queryWithLock(prologQuery.str()); if (bdgs.begin() != bdgs.end()) { outInfo(child << " IS " << parent); return true; } } else { outError("Child or parent are not defined in the ontology under any of the known namespaces"); outError(" Child : " << child); outError(" Parent: " << parent); return false; } return false; } bool RosPrologInterface::retractQueryLanguage() { try { std::stringstream query; query << "retractall(rs_query_reasoning:rs_type_for_predicate(_,_))"; queryWithLock(query.str()); query.str(""); query << "retractall(rs_query_predicate(_))"; queryWithLock(query.str()); } catch (...) { } return true; } bool RosPrologInterface::q_hasClassProperty(std::string subject, std::string relation, std::string object) { if (!addNamespace(object)) { outWarn(object << " is not found under any of the namespaces"); return false; } if (!addNamespace(subject)) { outWarn(subject << " is not found under any of the namespaces"); return false; } if (!addNamespace(relation, "obj-property")) { outWarn(relation << " is not found under any of the namespaces"); return false; } std::stringstream query; query << "owl_has(" << subject << ", rdfs:subClassOf, O)," << "owl_restriction(O, restriction(" << relation << ", some_values_from(" << object << ")))"; PrologQuery bdgs = queryWithLock(query.str()); if (bdgs.begin() != bdgs.end()) { outDebug(subject << " is in " << relation << " with: " << object); return true; } else { outDebug(subject << " is not in " << relation << " with: " << object); return false; } } bool RosPrologInterface::q_getClassProperty(std::string subject, std::string relation, std::string object) { outWarn("GET CLASS PROPERTY IS NOT IMPLEMENTED FOR JSON PROLOG INTERFACE"); return false; } bool RosPrologInterface::assertQueryLanguage( std::vector<std::tuple<std::string, std::vector<std::string>, int>>& query_terms) { for (auto term : query_terms) { std::string q_predicate; std::vector<std::string> types; int type_of_predicate; std::tie(q_predicate, types, type_of_predicate) = term; std::stringstream query; query << "assert(rs_query_predicate(" << q_predicate << "))"; PrologQuery bdgs = queryWithLock(query.str()); bool res1 = false, res2 = false; if (bdgs.begin() != bdgs.end()) { outInfo("Asserted " << q_predicate << " as a query language term"); res1 = true; } if (type_of_predicate == 1) { query.str(""); query << "assert(rs_query_reasoning:key_is_property(" << q_predicate << "))"; bdgs = queryWithLock(query.str()); if (bdgs.begin() != bdgs.end()) { outDebug("Assertion successfull: " << query.str()); outDebug("Asserted " << q_predicate << " as a property request in query language term"); res2 = true; } } for (auto type : types) { std::string token; std::stringstream ss(type), krType; while (std::getline(ss, token, '.')) { std::transform(token.begin(), token.end(), token.begin(), ::tolower); token[0] = std::toupper(token[0]); krType << token; } query.str(""); std::string krTypeClass; KnowledgeEngine::addNamespace(krType.str(), krTypeClass); query << "rdf_global_id(" << krTypeClass << ",A),assert(rs_query_reasoning:rs_type_for_predicate(" << q_predicate << ",A))"; PrologQuery bdgs = queryWithLock(query.str()); if (bdgs.begin() != bdgs.end()) { outInfo("Asserted " << krTypeClass << " as a type for " << q_predicate); } } } return true; } // namespace rs bool RosPrologInterface::instanceFromClass(const std::string& class_name, std::vector<std::string>& individualsOF) { std::stringstream prologQuery; prologQuery << "kb_create(" << class_name << "," << "I)"; PrologQuery bdgs = queryWithLock(prologQuery.str()); for (auto bdg : bdgs) individualsOF.push_back(bdg["I"]); return true; } bool RosPrologInterface::retractAllAnnotators() { std::stringstream query; query << "owl_subclass_of(S,rs_components:'RoboSherlockComponent'),rdf_retractall(_,rdf:type,S)"; queryWithLock(query.str()); return true; } bool RosPrologInterface::expandToFullUri(std::string& entry) { std::stringstream prologQuery; prologQuery << "rdf_global_id(" << entry << ",A)."; PrologQuery bdgs = queryWithLock(prologQuery.str()); for (auto bdg : bdgs) { std::string newentry = bdg["A"]; entry = newentry; return true; } return false; } bool RosPrologInterface::assertInputTypeConstraint(const std::string& individual, const std::vector<std::string>& values, std::string& type) { std::stringstream query; query << "set_annotator_input_type_constraint(" << individual << ",["; std::string separator = ","; for (auto it = values.begin(); it != values.end(); ++it) { if (std::next(it) == values.end()) separator = ""; query << *it << separator; } query << "], " << type << ")."; outInfo("Query: " << query.str()); PrologQuery bdgs = queryWithLock(query.str()); if (bdgs.begin() != bdgs.end()) return true; else return false; } bool RosPrologInterface::assertOutputTypeRestriction(const std::string& individual, const std::vector<std::string>& values, std::string& type) { std::stringstream query; query << "set_annotator_output_type_domain('" << individual << "',["; std::string separator = ","; for (auto it = values.begin(); it != values.end(); ++it) { if (std::next(it) == values.end()) separator = ""; query << *it << separator; } query << "], " << type << ")."; outInfo("Query: " << query.str()); PrologQuery bdgs = queryWithLock(query.str()); if (bdgs.begin() != bdgs.end()) return true; else return false; } bool RosPrologInterface::addNamespace(std::string& entry, std::string entry_type) { if (krNamespaces_.empty()) { std::stringstream getNamespacesQuery; getNamespacesQuery << "rdf_current_ns(A,_)"; PrologQuery bdgs = queryWithLock(getNamespacesQuery.str()); for (auto bdg : bdgs) { std::string ns = bdg["A"].toString(); // ns = ns.substr(0, ns.size() - 1); if (std::find(rs::NS_TO_SKIP.begin(), rs::NS_TO_SKIP.end(), ns) == rs::NS_TO_SKIP.end()) { krNamespaces_.push_back(ns); } } } for (auto ns : krNamespaces_) { std::stringstream prologQuery; if (entry_type == "class") prologQuery << "rdf_has(" << ns << ":'" << entry << "',rdf:type, owl:'Class')."; else if (entry_type == "obj-property") prologQuery << "rdf_has(" << ns << ":'" << entry << "',rdf:type, owl:'ObjectProperty')."; PrologQuery bdgs = queryWithLock(prologQuery.str()); if (bdgs.begin() != bdgs.end()) { entry = ns + ":'" + entry + "'"; return true; } } return false; } PrologQuery RosPrologInterface::queryWithLock(const std::string& query) { std::lock_guard<std::mutex> lock(lock_); return pl_.query(query); } } // namespace rs #endif
582ebe7ffb1d930aeb1bc9dff12b1110c55f24a8
f9185f58ac3d826bad491b7c6a943c65618f48e9
/New folder/characterArray.cpp
663d6bf8696fa6cce693de8f3a606d716019eed4
[]
no_license
ashwani471/c-_opps
315e4accef5309c15af04b0fb882a97a83c7c263
53dd065a2391c2c92864db5901362e5f030dd054
refs/heads/master
2023-08-23T11:20:07.859248
2021-10-18T10:10:19
2021-10-18T10:10:19
401,703,269
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
characterArray.cpp
#include<iostream> using namespace std; int main(){ // char ch[100]; // cin>>ch; // cout<<ch; //check palindrome int n; cin>>n; char arr[n+1]; cin>>arr; bool check=true; for(int i=0;i<n;i++){ if(arr[i]!=arr[n-1-i]){ check =false; break; } } if(check==true){ cout<<"palindrome "<<endl; }else{ cout<<"not palindrome"<<endl; } }
2ce11f88ddc68d3a1ce7b71617624b928a8b93bd
1490797b49fbadcdc17d6ebf4463535e3aee55f4
/RS08_V4/src/FlashProgramming.cpp
7487f350da6d51c4b6acffcc8616e058018b3bfe
[]
no_license
qiaozhou/usbdm-applications
23347aa7a0aa101ac4cd30d88d4ce59f30de5c41
596a2a217f2ccc156890aa60540ec4423532e302
refs/heads/master
2020-05-20T09:46:38.162826
2012-08-20T00:20:02
2012-08-20T00:20:02
5,520,103
3
0
null
null
null
null
UTF-8
C++
false
false
67,219
cpp
FlashProgramming.cpp
/*! \file \brief Utility Routines for programming RS08 Flash FlashProgramming.cpp \verbatim Copyright (C) 2008 Peter O'Donoghue This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \endverbatim \verbatim Change History +============================================================================== | Revision History +============================================================================== | 1 Jun 12 | 4.9.5 Now handles arbitrary number of memory regions - pgo +-----------+------------------------------------------------------------------ | 30 May 12 | 4.9.5 Re-write of DSC programming - pgo +-----------+------------------------------------------------------------------ | 12 Apr 12 | 4.9.4 Changed handling of empty images - pgo +-----------+------------------------------------------------------------------ | 30 Mar 12 | 4.9.4 Added Intelligent security option - pgo +-----------+------------------------------------------------------------------ | 25 Feb 12 | 4.9.1 Fixed alignment rounding problem on partial phrases - pgo +-----------+------------------------------------------------------------------ | 10 Feb 12 | 4.9.0 Major changes for HCS12 (Generalised code) - pgo +-----------+------------------------------------------------------------------ | 20 Nov 11 | 4.8.0 Major changes for Coldfire+ (Generalised code) - pgo +-----------+------------------------------------------------------------------ | 4 Oct 11 | 4.7.0 Added progress dialogues - pgo +-----------+------------------------------------------------------------------ | 23 Apr 11 | 4.6.0 Major changes for CFVx programming - pgo +-----------+------------------------------------------------------------------ | 6 Apr 11 | 4.6.0 Major changes for ARM programming - pgo +-----------+------------------------------------------------------------------ | 3 Jan 11 | 4.4.0 Major changes for XML device files etc - pgo +-----------+------------------------------------------------------------------ | 17 Sep 10 | 4.0.0 Fixed minor bug in isTrimLocation() - pgo +-----------+------------------------------------------------------------------ | 30 Jan 10 | 2.0.0 Changed to C++ - pgo | | Added paged memory support - pgo +-----------+------------------------------------------------------------------ | 15 Dec 09 | 1.1.1 setFlashSecurity() was modifying image unnecessarily - pgo +-----------+------------------------------------------------------------------ | 14 Dec 09 | 1.1.0 Changed Trim to use linear curve fitting - pgo | | FTRIM now combined with image value - pgo +-----------+------------------------------------------------------------------ | 7 Dec 09 | 1.0.3 Changed SOPT value to disable RESET pin - pgo +-----------+------------------------------------------------------------------ | 29 Nov 09 | 1.0.2 Bug fixes after trim testing - pgo +-----------+------------------------------------------------------------------ | 17 Nov 09 | 1.0.0 Created - pgo +============================================================================== \endverbatim */ #define _WIN32_IE 0x0500 //!< Required for common controls? #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string> #include <ctype.h> #include <memory> #include "Common.h" #include "Log.h" #include "FlashImage.h" #include "FlashProgramming.h" #include "USBDM_API.h" #include "TargetDefines.h" #include "Utils.h" #include "ProgressTimer.h" #include "SimpleSRecords.h" #if TARGET == ARM #include "USBDM_ARM_API.h" #include "STM32F100xx.h" #include "ARM_Definitions.h" #elif TARGET == MC56F80xx #include "USBDM_DSC_API.h" #endif #include "usbdmTcl.h" #include "wxPlugin.h" #ifdef GDI #include "GDI.h" #include "MetrowerksInterface.h" #endif #include "Names.h" /* ====================================================================== * Notes on BDM clock source (for default CLKSW): * * CPU BDM clock * ---------------------- * RS08 bus clock * HCS08 bus clock * HC12 bus clock * CFV1 bus clock * */ //============================================================================= #if TARGET == ARM #define WriteMemory(elementSize, byteCount, address, data) ARM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) ARM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) ARM_WriteRegister(ARM_RegPC, (regValue)) #define ReadPC(regValue) ARM_ReadRegister(ARM_RegPC, (regValue)) #define TargetGo() ARM_TargetGo() #define TargetHalt() ARM_TargetHalt() #define TARGET_TYPE T_ARM_JTAG #elif TARGET == MC56F80xx #define WriteMemory(elementSize, byteCount, address, data) DSC_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) DSC_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) DSC_WriteRegister(DSC_RegPC, (regValue)) #define ReadPC(regValue) DSC_ReadRegister(DSC_RegPC, (regValue)) #define TargetGo() DSC_TargetGo() #define TargetHalt() DSC_TargetHalt() #define TARGET_TYPE T_MC56F80xx #elif TARGET == CFVx #define WriteMemory(elementSize, byteCount, address, data) USBDM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) USBDM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) USBDM_WriteCReg(CFVx_CRegPC, (regValue)) #define ReadPC(regValue) USBDM_ReadCReg(CFVx_CRegPC, (regValue)) #define TargetGo() USBDM_TargetGo() #define TargetHalt() USBDM_TargetHalt() #define TARGET_TYPE T_CFVx #elif TARGET == CFV1 #define WriteMemory(elementSize, byteCount, address, data) USBDM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) USBDM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) USBDM_WriteCReg(CFV1_CRegPC, (regValue)) #define ReadPC(regValue) USBDM_ReadCReg(CFV1_CRegPC, (regValue)) #define TargetGo() USBDM_TargetGo() #define TargetHalt() USBDM_TargetHalt() #define TARGET_TYPE T_CFV1 #elif TARGET == HCS12 #define WriteMemory(elementSize, byteCount, address, data) USBDM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) USBDM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) USBDM_WriteReg(HCS12_RegPC, (regValue)) #define ReadPC(regValue) USBDM_ReadReg(HCS12_RegPC, (regValue)) #define TargetGo() USBDM_TargetGo() #define TargetHalt() USBDM_TargetHalt() #define TARGET_TYPE T_HCS12 #elif TARGET == HCS08 #define WriteMemory(elementSize, byteCount, address, data) USBDM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) USBDM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) USBDM_WriteReg(HCS08_RegPC, (regValue)) #define ReadPC(regValue) USBDM_ReadReg(HCS08_RegPC, (regValue)) #define TargetGo() USBDM_TargetGo() #define TargetHalt() USBDM_TargetHalt() #define TARGET_TYPE T_HCS08 #elif TARGET == RS08 #define WriteMemory(elementSize, byteCount, address, data) USBDM_WriteMemory((elementSize), (byteCount), (address), (data)) #define ReadMemory(elementSize, byteCount, address, data) USBDM_ReadMemory((elementSize), (byteCount), (address), (data)) #define WritePC(regValue) USBDM_WriteReg(RS08_RegPC, (regValue)) #define ReadPC(regValue) USBDM_ReadReg(RS08_RegPC, (regValue)) #define TargetGo() USBDM_TargetGo() #define TargetHalt() USBDM_TargetHalt() #define TARGET_TYPE T_RS08 #else #error "Need to define macros for this target" #endif //======================================================================================= inline uint16_t swap16(uint16_t data) { return ((data<<8)&0xFF00) + ((data>>8)&0xFF); } inline uint32_t swap32(uint32_t data) { return ((data<<24)&0xFF000000) + ((data<<8)&0xFF0000) + ((data>>8)&0xFF00) + ((data>>24)&0xFF); } inline uint32_t getData32Be(uint8_t *data) { return (data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3]; } inline uint32_t getData32Le(uint8_t *data) { return (data[3]<<24)+(data[2]<<16)+(data[1]<<8)+data[0]; } inline uint32_t getData16Be(uint8_t *data) { return (data[0]<<8)+data[1]; } inline uint32_t getData16Le(uint8_t *data) { return data[0]+(data[1]<<8); } inline uint32_t getData32Be(uint16_t *data) { return (data[0]<<16)+data[1]; } inline uint32_t getData32Le(uint16_t *data) { return (data[1]<<16)+data[0]; } inline const uint8_t *getData4x8Le(uint32_t data) { static uint8_t data8[4]; data8[0]= data; data8[1]= data>>8; data8[2]= data>>16; data8[3]= data>>24; return data8; } inline const uint8_t *getData4x8Be(uint32_t data) { static uint8_t data8[4]; data8[0]= data>>24; data8[1]= data>>16; data8[2]= data>>8; data8[3]= data; return data8; } inline const uint8_t *getData2x8Le(uint32_t data) { static uint8_t data8[2]; data8[0]= data; data8[1]= data>>8; return data8; } inline const uint8_t *getData2x8Be(uint32_t data) { static uint8_t data8[2]; data8[0]= data>>8; data8[1]= data; return data8; } #if (TARGET == ARM) || (TARGET == MC56F80xx) #define targetToNative16(x) (x) #define targetToNative32(x) (x) #define nativeToTarget16(x) (x) #define nativeToTarget32(x) (x) inline uint32_t getData32Target(uint8_t *data) { return getData32Le(data); } inline uint32_t getData16Target(uint8_t *data) { return *data; } inline uint32_t getData32Target(uint16_t *data) { return getData32Le(data); } inline uint32_t getData16Target(uint16_t *data) { return *data; } #else #define targetToNative16(x) swap16(x) #define targetToNative32(x) swap32(x) #define nativeToTarget16(x) swap16(x) #define nativeToTarget32(x) swap32(x) inline uint32_t getData32Target(uint8_t *data) { return getData32Be(data); } inline uint32_t getData16Target(uint8_t *data) { return getData16Be(data); } #endif //======================================================================= //! Calculate delay value for Flash programming. \n //! See flash program for calculation method. //! //! @param delayValue = Delay value passed to target program //! //! @return error code \n //! BDM_RC_OK => OK \n //! other => Error code - see USBDM_ErrorCode //! USBDM_ErrorCode FlashProgrammer::calculateFlashDelay(uint8_t *delayValue) { unsigned long bdmFrequency; double busFrequency; USBDM_ErrorCode rc; rc = USBDM_GetSpeedHz(&bdmFrequency); if (rc != BDM_RC_OK) { return PROGRAMMING_RC_ERROR_BDM; } busFrequency = bdmFrequency; // The values are chosen to satisfy Tprog including loop overhead above. // The other delays are less critical (minimums only) // Assuming bus freq. = ~4 MHz clock => 250 ns, 4cy = 1us // For 30us@4MHz, 4x30 = 120 cy, N = (4x30-30-10)/4 = 20 double tempValue = round(((busFrequency*30E-6)-30-10)/4); if ((tempValue<0) || (tempValue>255)) { // must be 8 bits return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } *delayValue = tempValue; print("FlashProgrammer::calculateFlashDelay() => busFreq=%f Hz, delValue=%d\n", busFrequency, *delayValue); return PROGRAMMING_RC_OK; } //============================================================================= //! Connects to the target. \n //! - Resets target to special mode //! - Connects //! - Runs initialisation script //! //! @return error code, see \ref USBDM_ErrorCode \n //! BDM_OK => Success \n //! PROGRAMMING_RC_ERROR_SECURED => Device is connected but secured (target connection speed may have been approximated)\n //! USBDM_getStatus() may be used to determine connection method. //! USBDM_ErrorCode FlashProgrammer::resetAndConnectTarget(void) { USBDM_ErrorCode bdmRc; USBDM_ErrorCode rc; print("FlashProgrammer::resetAndConnectTarget()\n"); if (parameters.getTargetName().empty()) { return PROGRAMMING_RC_ERROR_ILLEGAL_PARAMS; } flashReady = false; initTargetDone = false; // Reset to special mode to allow unlocking of Flash #if TARGET == ARM bdmRc = ARM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_DEFAULT)); if ((bdmRc != BDM_RC_OK) && (bdmRc != BDM_RC_SECURED)) bdmRc = ARM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE)); #elif TARGET == MC56F80xx bdmRc = DSC_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_DEFAULT)); if ((bdmRc != BDM_RC_OK) && (bdmRc != BDM_RC_SECURED)) bdmRc = DSC_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE)); #elif (TARGET == CFVx) || (TARGET == HC12) bdmRc = USBDM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_DEFAULT)); if (bdmRc != BDM_RC_OK) bdmRc = USBDM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE)); #else bdmRc = USBDM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_DEFAULT)); if (bdmRc != BDM_RC_OK) bdmRc = USBDM_TargetReset((TargetMode_t)(RESET_SPECIAL|RESET_HARDWARE)); #endif if (bdmRc == BDM_RC_SECURED) { print("FlashProgrammer::resetAndConnectTarget() ... Device is secured\n"); return PROGRAMMING_RC_ERROR_SECURED; } if (bdmRc != BDM_RC_OK) { print( "FlashProgrammer::resetAndConnectTarget() ... Failed Reset, %s!\n", USBDM_GetErrorString(bdmRc)); return PROGRAMMING_RC_ERROR_BDM_CONNECT; } #if TARGET == HC12 // A blank device can be very slow to complete reset // I think this is due to the delay in blank checking the entire Flash // It depends on the target clock so is problem for slow external clocks on HCS12 // Trying to connect at this time upsets this check milliSleep(200); #endif // Try auto Connect to target #if TARGET == ARM bdmRc = ARM_Connect(); #elif TARGET == MC56F80xx bdmRc = DSC_Connect(); #else // BDM_RC_BDM_EN_FAILED usually means a secured device bdmRc = USBDM_Connect(); #endif switch (bdmRc) { case BDM_RC_SECURED: case BDM_RC_BDM_EN_FAILED: // Treat as secured & continue rc = PROGRAMMING_RC_ERROR_SECURED; print( "FlashProgrammer::resetAndConnectTarget() ... Partial Connect, rc = %s!\n", USBDM_GetErrorString(bdmRc)); break; case BDM_RC_OK: rc = PROGRAMMING_RC_OK; break; default: print( "FlashProgrammer::resetAndConnectTarget() ... Failed Connect, rc = %s!\n", USBDM_GetErrorString(bdmRc)); return PROGRAMMING_RC_ERROR_BDM_CONNECT; } #if TARGET == ARM TargetHalt(); #endif // Use TCL script to set up target USBDM_ErrorCode rc2 = initialiseTarget(); if (rc2 != PROGRAMMING_RC_OK) rc = rc2; return rc; } //============================================================================= //! Reads the System Device Identification Register //! //! @param targetSDID - location to return SDID //! @param doInit - reset & re-connect to target first //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note Assumes the target device has already been opened & USBDM options set. //! @note Assumes the target has been reset in SPECIAL mode //! USBDM_ErrorCode FlashProgrammer::readTargetChipId(uint32_t *targetSDID, bool doInit) { uint8_t SDIDValue[4]; print("FlashProgrammer::readTargetSDID()\n"); if (parameters.getTargetName().empty()) { print("FlashProgrammer::readTargetSDID() - target name not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } *targetSDID = 0x0000; if (doInit) { USBDM_ErrorCode rc = resetAndConnectTarget(); if (rc != PROGRAMMING_RC_OK) return rc; } if (ReadMemory(2, 2, parameters.getSDIDAddress(), SDIDValue) != BDM_RC_OK) { return PROGRAMMING_RC_ERROR_BDM_READ; } *targetSDID = getData16Target(SDIDValue); // Do a sanity check on SDID (may get these values if secured w/o any error being signalled) if ((*targetSDID == 0xFFFF) || (*targetSDID == 0x0000)) { return PROGRAMMING_RC_ERROR_BDM_READ; } return PROGRAMMING_RC_OK; } //============================================================================= //! Check the target SDID agrees with device parameters //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note Assumes the target has been connected to //! USBDM_ErrorCode FlashProgrammer::confirmSDID() { uint32_t targetSDID; USBDM_ErrorCode rc; // mtwksDisplayLine("confirmSDID() - #1\n"); if (parameters.getTargetName().empty()) { print("FlashProgrammer::confirmSDID() - Error: device parameters not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } // mtwksDisplayLine("confirmSDID() - #2\n"); // Don't check Target SDID if zero if (parameters.getSDID() == 0x0000) { print("FlashProgrammer::confirmSDID(0x0000) => Skipping check\n"); return PROGRAMMING_RC_OK; } // Get SDID from target rc = readTargetChipId(&targetSDID); if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::confirmSDID(%4.4X) => Failed, error reading SDID, reason = %s\n", parameters.getSDID(), USBDM_GetErrorString(rc)); // Return this error even though the cause may be different return PROGRAMMING_RC_ERROR_WRONG_SDID; } if (!parameters.isThisDevice(targetSDID)) { print("FlashProgrammer::confirmSDID(%4.4X) => Failed (Target SDID=%4.4X)\n", parameters.getSDID(), targetSDID); return PROGRAMMING_RC_ERROR_WRONG_SDID; } print("FlashProgrammer::confirmSDID(%4.4X) => OK\n", targetSDID); return PROGRAMMING_RC_OK; } //============================================================================= //! Prepares the target \n //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note Assumes target has been reset & connected //! USBDM_ErrorCode FlashProgrammer::initialiseTarget() { if (initTargetDone) { print("FlashProgrammer::initialiseTarget() - already done, skipped\n"); return PROGRAMMING_RC_OK; } initTargetDone = true; print("FlashProgrammer::initialiseTarget()\n"); #if (TARGET == HCS08) char args[200] = "initTarget \""; char *argPtr = args+strlen(args); // Add address of each flash region for (int index=0; ; index++) { MemoryRegionPtr memoryRegionPtr = parameters.getMemoryRegion(index); if (memoryRegionPtr == NULL) { break; } if (!memoryRegionPtr->isProgrammableMemory()) { continue; } strcat(argPtr, " 0x"); argPtr += strlen(argPtr); itoa(memoryRegionPtr->getDummyAddress()&0xFFFF, argPtr, 16); argPtr += strlen(argPtr); } *argPtr++ = '\"'; *argPtr++ = '\0'; #elif (TARGET == HCS12) char args[200] = "initTarget \""; char *argPtr = args+strlen(args); // Add address of each flash region for (int index=0; ; index++) { MemoryRegionPtr memoryRegionPtr = parameters.getMemoryRegion(index); if (memoryRegionPtr == NULL) { break; } if (!memoryRegionPtr->isProgrammableMemory()) { continue; } sprintf(argPtr, "{%s 0x%04X} ", memoryRegionPtr->getMemoryTypeName(), memoryRegionPtr->getDummyAddress()&0xFFFF); argPtr += strlen(argPtr); } *argPtr++ = '\"'; *argPtr++ = '\0'; #elif (TARGET == RS08) char args[200] = "initTarget "; char *argPtr = args+strlen(args);sprintf(argPtr, "0x%04X 0x%04X 0x%04X", parameters.getSOPTAddress(), flashMemoryRegionPtr->getFOPTAddress(), flashMemoryRegionPtr->getFLCRAddress() ); argPtr += strlen(argPtr); *argPtr++ = '\0'; #endif USBDM_ErrorCode rc = runTCLCommand(args); if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::initialiseTargetFlash() - initTarget TCL failed\n"); return rc; } return rc; } //============================================================================= //! Prepares the target for Flash and eeprom operations. \n //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note Assumes target has been reset & connected //! USBDM_ErrorCode FlashProgrammer::initialiseTargetFlash() { USBDM_ErrorCode rc; print("FlashProgrammer::initialiseTargetFlash()\n"); // Check if already configured if (flashReady) { return PROGRAMMING_RC_OK; } // Configure the target clock for Flash programming unsigned long busFrequency; rc = configureTargetClock(&busFrequency); if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::initialiseTargetFlash() - Failed to get speed\n"); return rc; } // Convert to kHz targetBusFrequency = (uint32_t)round(busFrequency/1000.0); // this->flashData.frequency = targetBusFrequency; print("FlashProgrammer::initialiseTargetFlash(): Target Bus Frequency = %ld kHz\n", targetBusFrequency); char buffer[100]; sprintf(buffer, "initFlash %d", targetBusFrequency); rc = runTCLCommand(buffer); if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::initialiseTargetFlash() - initFlash TCL failed\n"); return rc; } // Flash is now ready for programming flashReady = TRUE; return PROGRAMMING_RC_OK; } //======================================================================= //! \brief Does Mass Erase of Target memory using TCL script. //! //! @return error code, see \ref USBDM_ErrorCode //! USBDM_ErrorCode FlashProgrammer::massEraseTarget(void) { if (progressTimer != NULL) { progressTimer->restart("Mass Erasing Target"); } USBDM_ErrorCode rc = initialiseTarget(); if (rc != PROGRAMMING_RC_OK) { return rc; } // Do Mass erase using TCL script rc = runTCLCommand("massEraseTarget"); if (rc != PROGRAMMING_RC_OK) { return rc; } // Don't reset device as it may only be temporarily unsecured! return PROGRAMMING_RC_OK; } //============================================================================== //! Program to download to target RAM //! This program is used to program the target Flash from a //! buffer also in target RAM. //! static const uint8_t RS08_flashProgram[48] = { // ;******************************************************************************** // ; Fast RAM ($0 - $D) // ; // ; Programming parameters (values given are dummies for testing) // ; // ; This area of memory is re-written for each block (<= 8 bytes) written to flash // ; The last byte (SourceAddr) is used as a flag to control execution as well as the // ; source buffer address/count. It is the last byte written by the BDM to start programming. // ; The values must lie within a single flash page (64 byte modulo) // ; // ; Example values are for a write of 6 bytes [$11,$22,$33,$44,$55,$66] => [$3F3A..$3F3F] // ; // 0000 FLCRAddress dc.b HIGH_6_13(FLCR) ; Page # for FLCR Reg // 0001 Buffer dc.b $11,$22,$33,$44,$55,$66,$77,$88 ; Buffer for data to program (<= 8 bytes) // 0009 DestinationAddr dc.b MAP_ADDR_6(Destination) ; Address in Paging Window for destination // 000A DestinationPage dc.b HIGH_6_13(Destination) ; Page for destination // 000B DelayValue dc.b 22 ; Delay value (4MHz=>N=22, 8MHz=>N=44) // 000C SourceAddr dc.b Buffer ; Address in Zero Page buffer for source // 000D ByteCount dc.b BufferSize ; # of byte to write <page & buffer size // // ;******************************************************************************** // ; Flash programming code in Z-Page RAM // ; // // org RAMStart // // Start: /* 0000 */ 0x8D, // clr ByteCount ; Set Idle mode // // Idle: /* 0001 */ 0xCD, // lda ByteCount /* 0002 */ 0x37,0xFD, // beq Idle ; Wait for some bytes to program /* 0004 */ 0xC0, // lda FLCRAddress /* 0005 */ 0xFF, // sta PAGESEL ; /* 0006 */ 0x10,0xD1, // bset FLCR_PGM,MAP_ADDR_6(FLCR) ; Enable Flash programming /* 0008 */ 0xCA, // lda DestinationPage ; Set window to page to program /* 0009 */ 0xFF, // sta PAGESEL /* 000A */ 0x3F,0xC0, // clr MAP_ADDR_6(0) ; Dummy write to Flash block /* 000C */ 0xAD,0x1C, // bsr delay30us ; Wait Tnvs /* 000E */ 0x16,0xD1, // bset FLCR_HVEN,MAP_ADDR_6(FLCR) ; Enable Flash high voltage /* 0010 */ 0xAD,0x18, // bsr delay30us ; Wait Tpgs // // Loop: ; Copy byte to flash (program) /* 0012 */ 0xCA, // lda DestinationPage ; 2 cy - Set window to page to program /* 0013 */ 0xFF, // sta PAGESEL ; 2 cy /* 0014 */ 0xCC, // lda SourceAddr ; 3 cy /* 0015 */ 0xEF, // sta X ; 2 cy /* 0016 */ 0xCE, // lda D[X] ; 3 cy /* 0017 */ 0x4E,0x09,0x0F, // mov DestinationAddr,X ; 5 cy /* 001A */ 0xEE, // sta D[X] ; 2 cy /* 001B */ 0xAD,0x0D, // bsr delay30us ; 3 cy - Wait Tprog /* 001D */ 0x29, // inc DestinationAddr ; 4 cy - Update ptrs/counter /* 001E */ 0x2C, // inc SourceAddr /* 001F */ 0x3B,0x0D,0xF0, // dbnz ByteCount,Loop ; 4 cy - Finished? - no, loop for next byte /* 0022 */ 0x11,0xD1, // bclr FLCR_PGM,MAP_ADDR_6(FLCR) ; Disable Flash programming /* 0024 */ 0xAD,0x04, // bsr delay30us ; Wait Tnvh /* 0026 */ 0x17,0xD1, // bclr FLCR_HVEN,MAP_ADDR_6(FLCR) ; Disable High voltage /* 0028 */ 0x30,0xD6, // bra Start ; Back for more // // ;********************************************************************* // ; A short delay (~30us) sufficient to satisfy all the required delays // ; The PAGESEL register is set to point at the FLCR page // ; // ; Tnvs > 5us // ; Tpgs > 10us // ; Tnvh > 5us // ; 40us > Tprog > 20us // ; // ; The delay may be adjusted through DelayValue // ; The values are chosen to satisfy Tprog including loop overhead above (30). // ; The other delays are less critical (minimums only) // ; Example: // ; bus freq. = ~4 MHz clock => 250 ns, 4cy = 1us // ; For 30us@4MHz, 4x30 = 120 cy, so N = (4x30-30-10)/4 = 20 // ; Examples (30xFreq-40)/4: // ; 20 MHz N=140 // ; 8 MHz N=50 // ; 4 MHz N=20 // ; 2 MHz N=5 // // delay30us: /* 002A */ 0xCB, // lda DelayValue ; 3 cy /* 002B */ 0x4B,0xFE, // dbnza * ; 4*N cy /* 002D */ 0xC0, // lda FLCRAddress ; 2 cy /* 002E */ 0xFF, // sta PAGESEL ; 2 cy /* 002F */ 0xBE, // rts ; 3 cy }; //======================================================================= //! Relocate (apply fixups) to program image //! //! @param buffer - writable copy of RS08_flashProgram for patching //! void FlashProgrammer::RS08_doFixups(uint8_t buffer[]) { // A bit ugly buffer[0x07] = RS08_WIN_ADDR(flashMemoryRegionPtr->getFLCRAddress()); buffer[0x0F] = RS08_WIN_ADDR(flashMemoryRegionPtr->getFLCRAddress()); buffer[0x23] = RS08_WIN_ADDR(flashMemoryRegionPtr->getFLCRAddress()); buffer[0x27] = RS08_WIN_ADDR(flashMemoryRegionPtr->getFLCRAddress()); } //======================================================================= //! Loads the Flash programming code to target memory //! //! This routine does the following: //! - Downloads the Flash programming code into the direct memory of //! the RS08 target and then verifies this by reading it back. //! - Starts the target program execution (program will be idle). //! - Instructs the BDM to enable the Flash programming voltage //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note - Assumes the target has been initialised for programming. //! Confirms download and checks RAM upper boundary. //! USBDM_ErrorCode FlashProgrammer::loadAndStartExecutingTargetProgram() { USBDM_ErrorCode BDMrc; uint8_t programImage[sizeof(RS08_flashProgram)]; uint8_t verifyBuffer[sizeof(RS08_flashProgram)]; print("FlashProgrammer::loadAndExecuteTargetProgram()\n"); // Create & patch image of program for target memory memcpy(programImage, RS08_flashProgram, sizeof(RS08_flashProgram)); // Patch relocated addresses RS08_doFixups(programImage); // Write Flash programming code to Target memory BDMrc = USBDM_WriteMemory(1, sizeof(programImage), parameters.getRamStart(), programImage ); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM_WRITE; // Read back to verify BDMrc = USBDM_ReadMemory(1, sizeof(programImage), parameters.getRamStart(), verifyBuffer ); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM_READ; // Verify correctly loaded if (memcmp(verifyBuffer, programImage, sizeof(programImage)) != 0) { print("FlashProgrammer::loadAndExecuteTargetProgram() - program load verify failed\n"); return PROGRAMMING_RC_ERROR_BDM_READ; } // Start flash code on target BDMrc = USBDM_WriteReg(RS08_RegCCR_PC, parameters.getRamStart()); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM_WRITE; BDMrc = USBDM_TargetGo(); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM; BDMrc = USBDM_SetTargetVpp(BDM_TARGET_VPP_STANDBY); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM; BDMrc = USBDM_SetTargetVpp(BDM_TARGET_VPP_ON); if (BDMrc != BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM; return PROGRAMMING_RC_OK; } //================================================================================== //! Write data to RS08 Flash memory - (within a single page of Flash, & buffer size) //! //! @param byteCount = Number of bytes to transfer //! @param address = Memory address //! @param data = Ptr to block of data to write //! @param delayValue = Delay value for target program //! //! @return error code \n //! BDM_RC_OK => OK \n //! other => Error code - see USBDM_ErrorCode //! USBDM_ErrorCode FlashProgrammer::writeFlashBlock( unsigned int byteCount, unsigned int address, unsigned const char *data, uint8_t delayValue) { int rc; uint8_t flashCommand[14] = {0x00}; uint8_t flashStatus; // const uint32_t PTADAddress = 0x10; // const uint32_t PTADDAddress = 0x11; // const uint32_t PTCDAddress = 0x4A; // const uint32_t PTCDDAddress = 0x4B; // const uint8_t zero = 0x00; // const uint8_t allOnes = 0xFF; print("FlashProgrammer::writeFlashBlock(count=0x%X(%d), addr=[0x%06X..0x%06X])\n", byteCount, byteCount, address, address+byteCount-1); printDump(data, byteCount, address); // 0000 FLCRAddress dc.b HIGH_6_13(FLCR) ; Page # for FLCR Reg // 0001 Buffer dc.b $11,$22,$33,$44,$55,$66,$77,$88 ; Buffer for data to program (<= 8 bytes) // 0009 DestinationAddr dc.b MAP_ADDR_6(Destination) ; Address in Paging Window for destination // 000A DestinationPage dc.b HIGH_6_13(Destination) ; Page for destination // 000B DelayValue dc.b 22 ; Delay value (4MHz=>N=22, 8MHz=>N=44) // 000C SourceAddr dc.b Buffer ; Address in Zero Page buffer for source // 000D ByteCount dc.b BufferSize ; # of byte to write <page & buffer size // Set up data to write flashCommand[0x0] = RS08_PAGENO(flashMemoryRegionPtr->getFLCRAddress()); if (byteCount<=8) { // Use tiny buffer unsigned int sub; for(sub=1; sub<=byteCount; sub++) { flashCommand[sub] = *data++; } } flashCommand[0x9] = RS08_WIN_ADDR(address); flashCommand[0xA] = RS08_PAGENO(address); flashCommand[0xB] = delayValue; flashCommand[0xC] = 1; // default to tiny buffer flashCommand[0xD] = byteCount; // If any of the following fail disable flash voltage do { // Transfer data to flash programming code // USBDM_WriteMemory(1, 1, PTADAddress, &allOnes); // USBDM_WriteMemory(1, 1, PTCDAddress, &allOnes); if (byteCount>8) { // Using large buffer rc = USBDM_WriteMemory(1, byteCount, parameters.getRamStart()+sizeof(RS08_flashProgram), data); if (rc != BDM_RC_OK) break; // Set buffer address flashCommand[0xC] = parameters.getRamStart()+sizeof(RS08_flashProgram); } // Write command data - triggers flash write rc = USBDM_WriteMemory(1, sizeof(flashCommand), 0, flashCommand); if (rc != BDM_RC_OK) break; // Poll for completion - should be complete on 1st poll! int reTry = 2; do { if (byteCount>8) { milliSleep( 5 /* ms */); } rc = USBDM_ReadMemory(1, sizeof(flashStatus), 0xD, &flashStatus); } while ((rc == BDM_RC_OK) && (flashStatus != 0) && (reTry-->0) ); // USBDM_WriteMemory(1, 1, PTCDAddress, &zero); if (rc != BDM_RC_OK) break; // Check status if (flashStatus != 0) { rc = BDM_RC_FAIL; break; } } while (FALSE); if (rc != BDM_RC_OK) { // Kill flash voltage on any error USBDM_SetTargetVpp(BDM_TARGET_VPP_OFF); #ifdef LOG { unsigned long temp; // re-sync and try to get some useful info from target USBDM_Connect(); USBDM_ReadMemory(1, sizeof(flashStatus), 0xD, &flashStatus); USBDM_ReadReg(RS08_RegA, &temp); USBDM_ReadMemory(1, sizeof(flashCommand), 0, flashCommand); } #endif return PROGRAMMING_RC_ERROR_FAILED_FLASH_COMMAND; } return PROGRAMMING_RC_OK; } //======================================================================= //! Programs a block of Target Flash memory //! The data is subdivided based upon buffer size and Flash alignment //! //! @param flashImage Description of flash contents to be programmed. //! @param blockSize Size of block to program (bytes) //! @param flashAddress Start address of block to program //! //! @return error code see \ref USBDM_ErrorCode. //! //! @note - Assumes flash programming code has already been loaded to target. //! USBDM_ErrorCode FlashProgrammer::programBlock(FlashImage *flashImage, unsigned int blockSize, uint32_t flashAddress) { unsigned int bufferSize; unsigned int bufferAddress; uint8_t delayValue; unsigned int splitBlockSize; uint8_t buffer[RS08_FLASH_PAGE_SIZE]; USBDM_ErrorCode rc; print("FlashProgrammer::programBlock() [0x%06X..0x%06X]\n", flashAddress, flashAddress+blockSize-1); if (!flashReady) { print("FlashProgrammer::doFlashBlock() - Error, Flash not ready\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } // OK for empty block if (blockSize==0) { return PROGRAMMING_RC_OK; } rc = calculateFlashDelay(&delayValue); if (rc != PROGRAMMING_RC_OK) { return rc; } // // Find flash region to program - this will recurse to handle sub regions // MemoryRegionPtr memoryRegionPtr; for (int index=0; ; index++) { memoryRegionPtr = parameters.getMemoryRegion(index); if (memoryRegionPtr == NULL) { print("FlashProgrammer::programBlock() - Block not within target memory\n"); return PROGRAMMING_RC_ERROR_OUTSIDE_TARGET_FLASH; } uint32_t lastContiguous; if (memoryRegionPtr->findLastContiguous(flashAddress, &lastContiguous)) { // Check if programmable if (!memoryRegionPtr->isProgrammableMemory()) { print("FlashProgrammer::programBlock() - Block not programmable memory\n"); return PROGRAMMING_RC_ERROR_OUTSIDE_TARGET_FLASH; } // Check if block crosses boundary and will need to be split if ((flashAddress+blockSize-1) > lastContiguous) { print("FlashProgrammer::doFlashBlock() - Block crosses FLASH boundary - recursing\n"); uint32_t firstBlockSize = lastContiguous - flashAddress + 1; USBDM_ErrorCode rc; rc = programBlock(flashImage, firstBlockSize, flashAddress); if (rc != PROGRAMMING_RC_OK) { return rc; } flashAddress += firstBlockSize; rc = programBlock(flashImage, blockSize-firstBlockSize, flashAddress); return rc; } break; } } MemType_t memoryType = memoryRegionPtr->getMemoryType(); print("FlashProgrammer::doFlashBlock() - Processing %s\n", MemoryRegion::getMemoryTypeName(memoryType)); // Initially assume buffer directly follows program in direct memory bufferAddress = parameters.getRamStart() + sizeof(RS08_flashProgram); // Calculate available space bufferSize = parameters.getRamEnd() - bufferAddress + 1; if (bufferSize <= 8) { // Use small buffer in Tiny RAM bufferSize = 8; bufferAddress = 1; } // Limit buffer to a single flash page if (bufferSize>RS08_FLASH_PAGE_SIZE) { bufferSize = RS08_FLASH_PAGE_SIZE; } while (blockSize > 0) { // Data block must lie within a single Flash page splitBlockSize = RS08_FLASH_PAGE_SIZE - (flashAddress%RS08_FLASH_PAGE_SIZE); // max # of bytes remaining in this page // Has to fit in buffer if (splitBlockSize>bufferSize) { splitBlockSize = bufferSize; } // Can't write more than we have left if (splitBlockSize>blockSize) { splitBlockSize = blockSize; } // Copy flash data to buffer unsigned int sub; for(sub=0; sub<splitBlockSize; sub++) { buffer[sub] = flashImage->getValue(flashAddress+sub); } // Write block to flash rc = writeFlashBlock(splitBlockSize, flashAddress, buffer, delayValue); if (rc != PROGRAMMING_RC_OK) { return rc; } // Advance to next block of data flashAddress += splitBlockSize; blockSize -= splitBlockSize; progressTimer->progress(splitBlockSize, NULL); }; return PROGRAMMING_RC_OK; } //! \brief Does Blank Check of Target Flash. //! //! @return error code, see \ref USBDM_ErrorCode //! //! @note The target is not reset so current security state persists after erase. //! USBDM_ErrorCode FlashProgrammer::blankCheckTarget() { const unsigned bufferSize = 0x400; uint8_t buffer[bufferSize]; print("FlashProgrammer::blankCheckMemory():Blank checking target memory...\n"); int memoryRegionIndex; MemoryRegionPtr memoryRegionPtr; for (memoryRegionIndex = 0; (memoryRegionPtr = parameters.getMemoryRegion(memoryRegionIndex)); memoryRegionIndex++) { MemType_t memoryType = memoryRegionPtr->getMemoryType(); if ((memoryType == MemFLASH) || (memoryType == MemEEPROM)) { int memoryRangeIndex; const MemoryRegion::MemoryRange *memoryRange; for (memoryRangeIndex = 0; (memoryRange = memoryRegionPtr->getMemoryRange(memoryRangeIndex)); memoryRangeIndex++) { uint32_t address = memoryRange->start; uint32_t memSize = 1 + memoryRange->end-memoryRange->start; while (memSize >0) { unsigned blockSize = memSize; if (blockSize>bufferSize) blockSize = bufferSize; USBDM_ErrorCode rc = ReadMemory(1, blockSize, address, buffer); if (rc != BDM_RC_OK) { print("FlashProgrammer::blankCheckMemory():Memory is not blank!\n"); return PROGRAMMING_RC_ERROR_NOT_BLANK; } for (unsigned index=0; index<blockSize; index++) { if (buffer[index] != 0xFF) return PROGRAMMING_RC_ERROR_NOT_BLANK; } address += blockSize; memSize -= blockSize; } } } } return PROGRAMMING_RC_OK; } //======================================================================= //! Check security state of target //! //! @return PROGRAMMING_RC_OK => device is unsecured \n //! PROGRAMMING_RC_ERROR_SECURED => device is secured \n //! else error code see \ref USBDM_ErrorCode //! //! @note Assumes the target device has already been opened & USBDM options set. //! USBDM_ErrorCode FlashProgrammer::checkTargetUnSecured() { USBDM_ErrorCode rc = initialiseTarget(); if (rc != PROGRAMMING_RC_OK) return rc; if (runTCLCommand("isUnsecure") != PROGRAMMING_RC_OK) { print("FlashProgrammer::checkTargetUnSecured() - secured\n"); return PROGRAMMING_RC_ERROR_SECURED; } print("FlashProgrammer::checkTargetUnSecured() - unsecured\n"); return PROGRAMMING_RC_OK; } static const char *secValues[] = {"default", "secured", "unsecured", "intelligent"}; //============================================================================================== //! Modifies the Security locations in the flash image according to required security options //! //! @param flashImage Flash contents to be programmed. //! @param flashRegion The memory region involved //! //! USBDM_ErrorCode FlashProgrammer::setFlashSecurity(FlashImage &flashImage, MemoryRegionPtr flashRegion) { uint32_t securityAddress = flashRegion->getSecurityAddress(); const uint8_t *data; int size; if (securityAddress == 0) { print("FlashProgrammer::setFlashSecurity(): No security area, not modifying flash image\n"); return PROGRAMMING_RC_OK; } switch (parameters.getSecurity()) { case SEC_SECURED: { // SEC=on SecurityInfoPtr securityInfo = flashRegion->getSecureInfo(); if (securityInfo == NULL) { print("FlashProgrammer::setFlashSecurity(): Error - No settings for security area!\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } size = securityInfo->getSize(); data = securityInfo->getData(); #ifdef LOG print("FlashProgrammer::setFlashSecurity(): Setting image as secured, \n" "mem[0x%06X-0x%06X] = ", securityAddress, securityAddress+size/sizeof(memoryElementType)-1); printDump(data, size, securityAddress); #endif flashImage.loadDataBytes(size, securityAddress, data); } break; case SEC_UNSECURED: { // SEC=off SecurityInfoPtr unsecurityInfo = flashRegion->getUnsecureInfo(); if (unsecurityInfo == NULL) { print("FlashProgrammer::setFlashSecurity(): Error - No settings for security area!\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } size = unsecurityInfo->getSize(); data = unsecurityInfo->getData(); #ifdef LOG print("FlashProgrammer::setFlashSecurity(): Setting image as unsecured, \n" "mem[0x%06X-0x%06X] = ", securityAddress, securityAddress+size/sizeof(memoryElementType)-1); printDump(data, size, securityAddress); #endif flashImage.loadDataBytes(size, securityAddress, data); } break; case SEC_INTELLIGENT: { // SEC=off if not already modified SecurityInfoPtr unsecurityInfo = flashRegion->getUnsecureInfo(); if (unsecurityInfo == NULL) { print("FlashProgrammer::setFlashSecurity(): Error - No settings for security area!\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } size = unsecurityInfo->getSize(); data = unsecurityInfo->getData(); #ifdef LOG print("FlashProgrammer::setFlashSecurity(): Setting image as intelligently unsecured, \n" "mem[0x%06X-0x%06X] = ", securityAddress, securityAddress+size/sizeof(memoryElementType)-1); printDump(data, size, securityAddress); #endif flashImage.loadDataBytes(size, securityAddress, data, true); } break; case SEC_DEFAULT: // Unchanged default: print("FlashProgrammer::setFlashSecurity(): Leaving flash image unchanged\n"); break; } return PROGRAMMING_RC_OK; } //======================================================================= //! Erase Target Flash memory //! //! @param flashImage - Flash image used to determine regions to erase. //! //! @return error code see \ref USBDM_ErrorCode. //! //! @note - Assumes flash programming code has already been loaded to target. //! USBDM_ErrorCode FlashProgrammer::setFlashSecurity(FlashImage &flashImage) { print("FlashProgrammer::setFlashSecurity()\n"); // Process each flash region USBDM_ErrorCode rc = BDM_RC_OK; for (int index=0; ; index++) { MemoryRegionPtr memoryRegionPtr = parameters.getMemoryRegion(index); if (memoryRegionPtr == NULL) { break; } rc = setFlashSecurity(flashImage, memoryRegionPtr); if (rc != BDM_RC_OK) { break; } } return rc; } //======================================================================= //! Checks if a block of Target Flash memory is blank [== 0xFF] //! //! @param flashImage Used to determine memory model //! @param blockSize Size of block to check //! @param flashAddress Start address of block to program //! //! @return error code see \ref USBDM_ErrorCode. //! //! @note - Assumes flash programming code has already been loaded to target. //! USBDM_ErrorCode FlashProgrammer::blankCheckBlock(FlashImage *flashImage, unsigned int blockSize, unsigned int flashAddress){ #define CHECKBUFFSIZE 0x8000 uint8_t buffer[CHECKBUFFSIZE]; unsigned int currentBlockSize; unsigned int index; print("FlashProgrammer::blankCheckBlock() - Blank checking block[0x%04X..0x%04X]\n", flashAddress, flashAddress+blockSize-1); while (blockSize>0) { currentBlockSize = blockSize; if (currentBlockSize > CHECKBUFFSIZE) currentBlockSize = CHECKBUFFSIZE; if (ReadMemory(1, currentBlockSize, flashAddress, buffer)!= BDM_RC_OK) return PROGRAMMING_RC_ERROR_BDM_READ; for (index=0; index<currentBlockSize; index++) { if (buffer[index] != 0xFF) { print("FlashProgrammer::blankCheckBlock() - Blank checking [0x%4.4X] => 0x%2.2X - failed\n", flashAddress+index, buffer[index]); return PROGRAMMING_RC_ERROR_NOT_BLANK; } } flashAddress += currentBlockSize; blockSize -= currentBlockSize; } return PROGRAMMING_RC_OK; } //======================================================================= // Executes a TCL script in the current TCL interpreter // USBDM_ErrorCode FlashProgrammer::runTCLScript(TclScriptPtr script) { print("FlashProgrammer::runTCLScript(): Running TCL Script...\n"); if (tclInterpreter == NULL) return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; if (evalTclScript(tclInterpreter, script->getScript().c_str()) != 0) { print("FlashProgrammer::runTCLScript(): Failed\n"); print(script->toString().c_str()); return PROGRAMMING_RC_ERROR_TCL_SCRIPT; } // print("FlashProgrammer::runTCLScript(): Script = %s\n", // (const char *)script->getScript().c_str()); // print("FlashProgrammer::runTCLScript(): Complete\n"); return PROGRAMMING_RC_OK; } //======================================================================= // Executes a TCL command previously loaded in the TCL interpreter // USBDM_ErrorCode FlashProgrammer::runTCLCommand(const char *command) { print("FlashProgrammer::runTCLCommand(): Running TCL Command '%s'\n", command); if (!useTCLScript) { print("FlashProgrammer::runTCLCommand(): Not using TCL\n"); return PROGRAMMING_RC_OK; } if (tclInterpreter == NULL) { return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } if (evalTclScript(tclInterpreter, command) != 0) { print("FlashProgrammer::runTCLCommand(): TCL Command '%s' failed\n", command); return PROGRAMMING_RC_ERROR_TCL_SCRIPT; } // print("FlashProgrammer::runTCLCommand(): Complete\n"); return PROGRAMMING_RC_OK; } //======================================================================= // Initialises TCL support for current target // USBDM_ErrorCode FlashProgrammer::initTCL(void) { // print("FlashProgrammer::initTCL()\n"); // Set up TCL interpreter only once if (tclInterpreter != NULL) return PROGRAMMING_RC_OK; useTCLScript = false; // FILE *fp = fopen("c:/delme.log", "wt"); // tclInterpreter = createTclInterpreter(TARGET_TYPE, fp); tclInterpreter = createTclInterpreter(TARGET_TYPE, getLogFileHandle()); if (tclInterpreter == NULL) { print("FlashProgrammer::initTCL() - no TCL interpreter\n"); return PROGRAMMING_RC_ERROR_TCL_SCRIPT; } // Run initial TCL script (loads routines) TclScriptPtr script = parameters.getFlashScripts(); if (!script) { print("FlashProgrammer::initTCL() - no TCL script found\n"); return PROGRAMMING_RC_ERROR_TCL_SCRIPT; } #if defined(LOG) && 0 print("FlashProgrammer::initTCL()\n"); print(script->toString().c_str()); #endif USBDM_ErrorCode rc = runTCLScript(script); if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::initTCL() - runTCLScript() failed\n"); return rc; } useTCLScript = true; return PROGRAMMING_RC_OK; } //======================================================================= // Release the current TCL interpreter // USBDM_ErrorCode FlashProgrammer::releaseTCL(void) { if (tclInterpreter != NULL) { freeTclInterpreter(tclInterpreter); tclInterpreter = NULL; } return PROGRAMMING_RC_OK; } //================================================================================== //! doVerify - Verifies the Target memory against memory image //! //! @param flashImage Description of flash contents to be verified. //! //! @return error code see \ref USBDM_ErrorCode //! //! @note Assumes the target device has already been opened & USBDM options set. //! @note Assumes target connection has been established //! @note Assumes callback has been set up if used. //! @note If target clock trimming is enabled then the Non-volatile clock trim //! locations are ignored. //! USBDM_ErrorCode FlashProgrammer::doVerify(FlashImage *flashImage) { const unsigned MAX_BUFFER=0x800; uint8_t buffer[MAX_BUFFER]; int checkResult = TRUE; int blockResult; print("FlashProgrammer::doVerify()\n"); progressTimer->restart("Verifying..."); FlashImage::Enumerator *enumerator = flashImage->getEnumerator(); while (enumerator->isValid()) { uint32_t startBlock = enumerator->getAddress(); // Find end of block to verify enumerator->lastValid(); unsigned regionSize = enumerator->getAddress() - startBlock + 1; print("FlashProgrammer::doVerify() - Verifying Block[0x%8.8X..0x%8.8X]\n", startBlock, startBlock+regionSize-1); while (regionSize>0) { unsigned blockSize = regionSize; if (blockSize > MAX_BUFFER) { blockSize = MAX_BUFFER; } if (ReadMemory(1, blockSize, startBlock, buffer) != BDM_RC_OK) { return PROGRAMMING_RC_ERROR_BDM_READ; } blockResult = TRUE; uint32_t testIndex; for (testIndex=0; testIndex<blockSize; testIndex++) { if (flashImage->getValue(startBlock+testIndex) != buffer[testIndex]) { blockResult = FALSE; #ifndef LOG break; #endif // print("Verifying location[0x%8.8X]=>failed, image=%2.2X != target=%2.2X\n", // startBlock+testIndex, // (uint8_t)(flashImage->getValue(startBlock+testIndex]), // buffer[testIndex]); } } print("FlashProgrammer::doVerify() - Verifying Sub-block[0x%8.8X..0x%8.8X]=>%s\n", startBlock, startBlock+blockSize-1,blockResult?"OK":"FAIL"); checkResult = checkResult && blockResult; regionSize -= blockSize; startBlock += blockSize; progressTimer->progress(blockSize, NULL); #ifndef LOG if (!checkResult) { break; } #endif } #ifndef LOG if (!checkResult) { break; } #endif // Advance to start of next occupied region enumerator->nextValid(); } if (enumerator != NULL) delete enumerator; return checkResult?PROGRAMMING_RC_OK:PROGRAMMING_RC_ERROR_FAILED_VERIFY; } //======================================================================= //! Verify Target Flash memory //! //! @param flashImage - Description of flash contents to be verified. //! @param progressCallBack - Callback function to indicate progress //! //! @return error code see \ref USBDM_ErrorCode //! //! @note Assumes the target device has already been opened & USBDM options set. //! @note If target clock trimming is enabled then the Non-volatile clock trim //! locations are ignored. //! USBDM_ErrorCode FlashProgrammer::verifyFlash(FlashImage *flashImage, CallBackT progressCallBack) { USBDM_ErrorCode rc; if ((this == NULL) || (parameters.getTargetName().empty())) { print("FlashProgrammer::programFlash() - Error: device parameters not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } print("===========================================================\n" "FlashProgrammer::verifyFlash()\n" "\tprogressCallBack = %p\n" "\tDevice = \'%s\'\n" "\tTrim, F=%ld, NVA@%4.4X, clock@%4.4X\n" "\tRam[%4.4X...%4.4X]\n" "\tErase=%s\n" "\tSecurity=%s\n", progressCallBack, parameters.getTargetName().c_str(), parameters.getClockTrimFreq(), parameters.getClockTrimNVAddress(), parameters.getClockAddress(), parameters.getRamStart(), parameters.getRamEnd(), DeviceData::getEraseOptionName(parameters.getEraseOption()), secValues[parameters.getSecurity()]); this->doRamWrites = false; if (progressTimer != NULL) { delete progressTimer; } progressTimer = new ProgressTimer(progressCallBack, flashImage->getByteCount()); progressTimer->restart("Initialising..."); flashReady = FALSE; currentFlashProgram.reset(); rc = initTCL(); if (rc != PROGRAMMING_RC_OK) { return rc; } if (parameters.getTargetName().empty()) { print("FlashProgrammer::verifyFlash() - Error: device parameters not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } // Set up the target for Flash operations rc = resetAndConnectTarget(); if (rc != PROGRAMMING_RC_OK) { return rc; } rc = checkTargetUnSecured(); if (rc != PROGRAMMING_RC_OK) { return rc; } // Modify flash image according to security options - to be consistent with what is programmed rc = setFlashSecurity(*flashImage); if (rc != PROGRAMMING_RC_OK) { return rc; } #if (TARGET == CFV1) || (TARGET == HCS08) // Modify flash image according to trim options - to be consistent with what is programmed rc = dummyTrimLocations(flashImage); if (rc != PROGRAMMING_RC_OK) { return rc; } #endif rc = doVerify(flashImage); print("FlashProgrammer::verifyFlash() - Verifying Time = %3.2f s, rc = %d\n", progressTimer->elapsedTime(), rc); return rc; } //======================================================================= //! Program Target Flash memory //! //! @param flashImage - Description of flash contents to be programmed. //! @param progressCallBack - Callback function to indicate progress //! //! @return error code see \ref USBDM_ErrorCode //! //! @note Assumes the target device has already been opened & USBDM options set. //! @note The FTRIM etc. locations in the flash image may be modified with trim values. //! @note Security locations within the flash image may be modified to effect the protection options. //! USBDM_ErrorCode FlashProgrammer::programFlash(FlashImage *flashImage, CallBackT progressCallBack, bool doRamWrites) { USBDM_ErrorCode rc; bool targetBlank = false; if ((this == NULL) || (parameters.getTargetName().empty())) { print("FlashProgrammer::programFlash() - Error: device parameters not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } #ifdef GDI mtwksDisplayLine("===========================================================\n" "FlashProgrammer::programFlash()\n" "\tDevice = \'%s\'\n" "\tTrim, F=%ld, NVA@%4.4X, clock@%4.4X\n" "\tRam[%4.4X...%4.4X]\n" "\tErase=%s\n" "\tSecurity=%s\n" "\tTotal bytes=%d\n", parameters.getTargetName().c_str(), parameters.getClockTrimFreq(), parameters.getClockTrimNVAddress(), parameters.getClockAddress(), parameters.getRamStart(), parameters.getRamEnd(), DeviceData::getEraseOptionName(parameters.getEraseOption()), secValues[parameters.getSecurity()], flashImage->getByteCount()); #else print("===========================================================\n" "FlashProgrammer::programFlash()\n" "\tprogressCallBack = %p\n" "\tDevice = \'%s\'\n" "\tTrim, F=%ld, NVA@%4.4X, clock@%4.4X\n" "\tRam[%4.4X...%4.4X]\n" "\tErase=%s\n" "\tSecurity=%s\n" "\tTotal bytes=%d\n", progressCallBack, parameters.getTargetName().c_str(), parameters.getClockTrimFreq(), parameters.getClockTrimNVAddress(), parameters.getClockAddress(), parameters.getRamStart(), parameters.getRamEnd(), DeviceData::getEraseOptionName(parameters.getEraseOption()), secValues[parameters.getSecurity()], flashImage->getByteCount()); #endif this->doRamWrites = doRamWrites; if (progressTimer != NULL) { delete progressTimer; } progressTimer = new ProgressTimer(progressCallBack, flashImage->getByteCount()); progressTimer->restart("Initialising..."); flashReady = FALSE; currentFlashProgram.reset(); rc = initTCL(); if (rc != PROGRAMMING_RC_OK) { return rc; } if (parameters.getTargetName().empty()) { print("FlashProgrammer::programFlash() - Error: device parameters not set\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } // Connect to target rc = resetAndConnectTarget(); if (rc != PROGRAMMING_RC_OK) { if ((rc != PROGRAMMING_RC_ERROR_SECURED) || (parameters.getEraseOption() != DeviceData::eraseMass)) return rc; } bool secured = checkTargetUnSecured() != PROGRAMMING_RC_OK; // Check target security if (secured && (parameters.getEraseOption() != DeviceData::eraseMass)) { // Can't program if secured return PROGRAMMING_RC_ERROR_SECURED; } // Check target SDID _before_ erasing device rc = confirmSDID(); if (rc != PROGRAMMING_RC_OK) { return rc; } // Modify flash image according to security options rc = setFlashSecurity(*flashImage); if (rc != PROGRAMMING_RC_OK) { return rc; } // Mass erase if (parameters.getEraseOption() == DeviceData::eraseMass) { rc = massEraseTarget(); if (rc != PROGRAMMING_RC_OK) { return rc; } #if !defined(LOG) || 1 targetBlank = true; #endif } #if (TARGET == RS08) || (TARGET == CFV1) || (TARGET == HCS08) // Calculate clock trim values & update memory image rc = setFlashTrimValues(flashImage); if (rc != PROGRAMMING_RC_OK) { return rc; } #endif // Set up for Flash operations (clock etc) rc = initialiseTargetFlash(); if (rc != PROGRAMMING_RC_OK) { return rc; } // // The above leaves the Flash ready for programming // // Load default flash programming code to target rc = loadAndStartExecutingTargetProgram(); if (rc != PROGRAMMING_RC_OK) { return rc; } print("FlashProgrammer::programFlash() - Erase Time = %3.2f s\n", progressTimer->elapsedTime()); // Program flash FlashImage::Enumerator *enumerator = flashImage->getEnumerator(); progressTimer->restart("Programming..."); print("FlashProgrammer::programFlash() - Total Bytes = %d\n", flashImage->getByteCount()); while(enumerator->isValid()) { // Start address of block to program to flash uint32_t startBlock = enumerator->getAddress(); // Find end of block to program enumerator->lastValid(); uint32_t blockSize = enumerator->getAddress() - startBlock + 1; //print("Block size = %4.4X (%d)\n", blockSize, blockSize); if (blockSize>0) { // Program block [startBlock..endBlock] if (!targetBlank) { // Need to check if range is currently blank // It is not permitted to re-program flash rc = blankCheckBlock(flashImage, blockSize, startBlock); if (rc != PROGRAMMING_RC_OK) { USBDM_SetTargetVpp(BDM_TARGET_VPP_OFF); return rc; } } rc = programBlock(flashImage, blockSize, startBlock); if (rc != PROGRAMMING_RC_OK) { USBDM_SetTargetVpp(BDM_TARGET_VPP_OFF); print("FlashProgrammer::programFlash() - programming failed, Reason= %s\n", USBDM_GetErrorString(rc)); break; } } // Advance to start of next occupied region enumerator->nextValid(); } USBDM_SetTargetVpp(BDM_TARGET_VPP_OFF); delete enumerator; enumerator = NULL; if (rc != PROGRAMMING_RC_OK) { print("FlashProgrammer::programFlash() - erasing failed, Reason= %s\n", USBDM_GetErrorString(rc)); return rc; } #ifdef GDI if (parameters.getClockTrimFreq() != 0) { uint16_t trimValue = parameters.getClockTrimValue(); mtwksDisplayLine("FlashProgrammer::programFlash() - Device Trim Value = %2.2X.%1X\n", trimValue>>1, trimValue&0x01); } mtwksDisplayLine("FlashProgrammer::programFlash() - Programming Time = %3.2f s, Speed = %2.2f kBytes/s, rc = %d\n", progressTimer->elapsedTime(), flashImage->getByteCount()/(1024*progressTimer->elapsedTime()), rc); #endif #ifdef LOG print("FlashProgrammer::programFlash() - Programming Time = %3.2f s, Speed = %2.2f kBytes/s, rc = %d\n", progressTimer->elapsedTime(), flashImage->getByteCount()/(1024*progressTimer->elapsedTime()), rc); #endif rc = doVerify(flashImage); #ifdef GDI mtwksDisplayLine("FlashProgrammer::programFlash() - Verifying Time = %3.2f s, rc = %d\n", progressTimer->elapsedTime(), rc); #endif #ifdef LOG print("FlashProgrammer::programFlash() - Verifying Time = %3.2f s, rc = %d\n", progressTimer->elapsedTime(), rc); #endif return rc; } //======================================================================= //! Set device data for flash operations //! //! @param DeviceData data describing the device //! //! @return error code see \ref USBDM_ErrorCode //! USBDM_ErrorCode FlashProgrammer::setDeviceData(const DeviceData &theParameters) { currentFlashProgram.reset(); parameters = theParameters; print("FlashProgrammer::setDeviceData(%s)\n", parameters.getTargetName().c_str()); releaseTCL(); initTCL(); // Find the flash region to obtain flash parameters for (int index=0; ; index++) { MemoryRegionPtr memoryRegionPtr; memoryRegionPtr = parameters.getMemoryRegion(index); if (memoryRegionPtr == NULL) { break; } if (memoryRegionPtr->isProgrammableMemory()) { flashMemoryRegionPtr = memoryRegionPtr; break; } } if (flashMemoryRegionPtr == NULL) { print("FlashProgrammer::setDeviceData() - No flash memory found\n"); return PROGRAMMING_RC_ERROR_INTERNAL_CHECK_FAILED; } return PROGRAMMING_RC_OK; } //======================================================================= FlashProgrammer::~FlashProgrammer() { // print("~FlashProgrammer()\n"); if (progressTimer != NULL) { delete progressTimer; } releaseTCL(); }
da7207240c6661a33d6bd5d6f6ef3e9a9d6a72ac
fb69a4b90e3e1fd34860ecb360573d4fcf56150b
/include/HarmonicConstantsModule/Model_View/harmonicconstantfrequencytabledelegate.cpp
3ff5c9d4aba325e07128826d892a3fed322f7b32
[]
no_license
ryera89/TideAnalisisPredictionSystem
40da629937ab9dbd7353e05f531ea0aa242e5736
2223446e9b48e741e5072664bbcc539f6953774f
refs/heads/master
2023-07-08T06:57:22.105956
2021-08-07T20:58:43
2021-08-07T20:58:43
393,788,977
1
0
null
null
null
null
UTF-8
C++
false
false
6,337
cpp
harmonicconstantfrequencytabledelegate.cpp
#include "harmonicconstantfrequencytabledelegate.h" #include <QDoubleSpinBox> #include <QLineEdit> #include <QPainter> void HarmonicConstantFrequencyTableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == nameColumn){ QString name = index.model()->data(index,Qt::DisplayRole).toString(); QStyleOptionViewItem myOption = option; myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; initStyleOption(&myOption,index); painter->save(); painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); if (myOption.state & QStyle::State_Selected){ painter->fillRect(myOption.rect,myOption.palette.highlight()); painter->setPen(myOption.palette.highlightedText().color()); }else{ painter->setPen(myOption.palette.windowText().color()); } painter->drawText(myOption.rect.adjusted(0,0,-3,0), name, QTextOption(Qt::AlignVCenter | Qt::AlignRight)); painter->restore(); }else{ if (index.column() == freqColumn){ double frequency = index.model()->data(index,Qt::DisplayRole).toDouble(); QStyleOptionViewItem myOption = option; myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; initStyleOption(&myOption,index); painter->save(); painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); if (myOption.state & QStyle::State_Selected){ painter->fillRect(myOption.rect,myOption.palette.highlight()); painter->setPen(myOption.palette.highlightedText().color()); }else{ painter->setPen(myOption.palette.windowText().color()); } painter->drawText(myOption.rect.adjusted(0,0,-3,0),QString::number(frequency), QTextOption(Qt::AlignVCenter | Qt::AlignRight)); painter->restore(); }else{ if (index.column() == descColumn){ QString description = index.model()->data(index,Qt::DisplayRole).toString(); QStyleOptionViewItem myOption = option; myOption.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter; initStyleOption(&myOption,index); painter->save(); painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); if (myOption.state & QStyle::State_Selected){ painter->fillRect(myOption.rect,myOption.palette.highlight()); painter->setPen(myOption.palette.highlightedText().color()); }else{ painter->setPen(myOption.palette.windowText().color()); } painter->drawText(myOption.rect.adjusted(0,0,-3,0),description, QTextOption(Qt::AlignVCenter | Qt::AlignLeft)); painter->restore(); }else{ QStyledItemDelegate::paint(painter,option,index); } } } } QWidget *HarmonicConstantFrequencyTableDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == nameColumn){ QLineEdit *nameEdit = new QLineEdit(parent); connect(nameEdit,SIGNAL(editingFinished()),this,SLOT(commitAndCloseNameEditor())); return nameEdit; } if (index.column() == freqColumn){ QDoubleSpinBox *freqEdit = new QDoubleSpinBox(parent); freqEdit->setDecimals(6); freqEdit->setRange(-1000000,1000000); connect(freqEdit,SIGNAL(editingFinished()),this,SLOT(commitAndCloseFreqEditor())); return freqEdit; } if (index.column() == descColumn){ QLineEdit *descEdit = new QLineEdit(parent); connect(descEdit,SIGNAL(editingFinished()),this,SLOT(commitAndCloseDescEditor())); return descEdit; } return QStyledItemDelegate::createEditor(parent,option,index); } void HarmonicConstantFrequencyTableDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { if (index.column() == nameColumn){ QString name = index.model()->data(index).toString(); QLineEdit *nameEditor = qobject_cast<QLineEdit*>(editor); //Q_ASSERT(dateEditor); nameEditor->setText(name); }else if (index.column() == freqColumn){ double frequency = index.model()->data(index).toDouble(); QDoubleSpinBox *freqEditor = qobject_cast<QDoubleSpinBox*>(editor); freqEditor->setValue(frequency); }else if (index.column() == descColumn){ QString description = index.model()->data(index).toString(); QLineEdit *descEditor = qobject_cast<QLineEdit*>(editor); descEditor->setText(description); }else{ QStyledItemDelegate::setEditorData(editor,index); } } void HarmonicConstantFrequencyTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (index.column() == nameColumn){ QLineEdit *nameEditor = qobject_cast<QLineEdit*>(editor); model->setData(index, nameEditor->text()); }else if (index.column() == freqColumn){ QDoubleSpinBox *freqEditor = qobject_cast<QDoubleSpinBox*>(editor); model->setData(index,freqEditor->value()); }else if (index.column() == descColumn){ QLineEdit *descEditor = qobject_cast<QLineEdit*>(editor); model->setData(index,descEditor->text()); }else{ QStyledItemDelegate::setModelData(editor,model,index); } } void HarmonicConstantFrequencyTableDelegate::commitAndCloseNameEditor() { QLineEdit *editor = qobject_cast<QLineEdit *>(sender()); emit commitData(editor); emit closeEditor(editor); } void HarmonicConstantFrequencyTableDelegate::commitAndCloseFreqEditor() { QDoubleSpinBox *editor = qobject_cast<QDoubleSpinBox *>(sender()); emit commitData(editor); emit closeEditor(editor); } void HarmonicConstantFrequencyTableDelegate::commitAndCloseDescEditor() { QLineEdit *editor = qobject_cast<QLineEdit *>(sender()); emit commitData(editor); emit closeEditor(editor); }
673564c75d7b61ec44b2ff1f97547bc712e76497
9d3b40ce69eb15ff8f70ca001bdc08d0fb609a75
/integrationtest/src/TupleFeeder.cpp
80c55386147834a9a08026ea60323a0a942e2875
[ "Apache-2.0" ]
permissive
ClockworkOrigins/m2etis
bf6adbbb8f8718b1183ff4827d87c4002c479efe
3b9c0f98c172f48889e75fe0b80a61a0e47670f5
refs/heads/master
2020-05-22T05:43:45.101808
2016-01-24T23:52:51
2016-01-24T23:52:51
50,309,673
2
0
null
null
null
null
UTF-8
C++
false
false
6,964
cpp
TupleFeeder.cpp
/* Copyright (2016) Michael Baer, Daniel Bonrath, 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 "TupleFeeder.h" #include "sys/times.h" #include "sys/vtimes.h" #include "boost/property_tree/info_parser.hpp" #include "boost/property_tree/ptree.hpp" #include "boost/thread.hpp" static clock_t lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; TupleFeeder::TupleFeeder(const std::string & configFile, const std::string & rendezvousIP, int rendezvousPort, int type, const std::string ownIP, int ownPort) : _pubsub(ownIP, static_cast<unsigned short>(ownPort), rendezvousIP, static_cast<unsigned short>(rendezvousPort), {rendezvousIP}), _owner(ownIP), _type(static_cast<NodeType>(type)), _packetSize(), _maxMessages(), _startTime(boost::posix_time::microsec_clock::universal_time()), _currentTime(_startTime), _wholeTime(0), _cinThread(boost::bind(&TupleFeeder::readCin, this)), _objCondExecutable(), _objCondMut(), _objCondUniqLock(_objCondMut), _currentID(0), _tickTime(), _lock(), _running(true), _latencies(), _profiling(), _messages(), _timeList(), _ticksPerSec(), _ticks(), _sent(), _received() { readConfig(configFile); initProfiler(); run(); } TupleFeeder::~TupleFeeder() { } void TupleFeeder::run() { _objCondExecutable.wait(_objCondUniqLock); if (_type == NodeType::SUBSCRIBER || _type == NodeType::PUBSUBER) { _pubsub.subscribe<IntegrationTestEventType>(_usedChannel, *this); } _objCondExecutable.wait(_objCondUniqLock); IntegrationTestEventType e(_packetSize); m2etis::message::M2Message<IntegrationTestEventType>::Ptr msg = _pubsub.createMessage<IntegrationTestEventType>(_usedChannel, e); if (_type == NodeType::PUBLISHER || _type == NodeType::PUBSUBER) { while (_running) { boost::posix_time::ptime tickStart = boost::posix_time::microsec_clock::universal_time(); for (int i = 0; i < _numToSend; i++) { _pubsub.publish<IntegrationTestEventType>(_usedChannel, msg); _sent++; if (_sent == _maxMessages) { _running = false; break; } } boost::this_thread::sleep(boost::posix_time::milliseconds(1000 - static_cast<long>(boost::posix_time::time_period(tickStart, boost::posix_time::microsec_clock::universal_time()).length().total_milliseconds()))); } } if ((_type == NodeType::SUBSCRIBER || _type == NodeType::PUBSUBER) && _running) { _objCondExecutable.wait(_objCondUniqLock); } _endTime = boost::posix_time::microsec_clock::universal_time(); saveMeasurements(); } void TupleFeeder::deliverCallback(const typename m2etis::message::M2Message<IntegrationTestEventType>::Ptr m) { _received++; if (_received == _maxMessages) { _running = false; long l = static_cast<long>(boost::posix_time::time_period(_startTime, boost::posix_time::microsec_clock::universal_time()).length().total_microseconds()) / 1000.0; _timeList.push_back(l); _wholeTime += l; _objCondExecutable.notify_all(); } else if (_received % size_t(_numToSend) == 0) { long l = static_cast<long>(boost::posix_time::time_period(_startTime, boost::posix_time::microsec_clock::universal_time()).length().total_microseconds()) / 1000.0; _timeList.push_back(l); _wholeTime += l; } else if (_received % size_t(_numToSend) == 1) { _startTime = boost::posix_time::microsec_clock::universal_time(); } } int TupleFeeder::parseLine(char * line){ int i = strlen(line); while (*line < '0' || *line > '9') { line++; } line[i - 3] = '\0'; i = atoi(line); return i; } int TupleFeeder::getVRAMValue() { // Note: this value is in KB! FILE * file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != nullptr) { if (strncmp(line, "VmSize:", 7) == 0) { result = parseLine(line); break; } } fclose(file); return result; } int TupleFeeder::getPRAMValue() { // Note: this value is in KB! FILE * file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != nullptr) { if (strncmp(line, "VmRSS:", 6) == 0) { result = parseLine(line); break; } } fclose(file); return result; } void TupleFeeder::initProfiler() { FILE * file; struct tms timeSample; char line[128]; lastCPU = times(&timeSample); lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; file = fopen("/proc/cpuinfo", "r"); numProcessors = 0; while(fgets(line, 128, file) != nullptr) { if (strncmp(line, "processor", 9) == 0) { numProcessors++; } } fclose(file); } double TupleFeeder::getCurrentValue() { struct tms timeSample; clock_t now; double percent; now = times(&timeSample); if (now <= lastCPU || timeSample.tms_stime < lastSysCPU || timeSample.tms_utime < lastUserCPU) { //Overflow detection. Just skip this value. percent = -1.0; } else { percent = (timeSample.tms_stime - lastSysCPU) + (timeSample.tms_utime - lastUserCPU); percent /= (now - lastCPU); percent /= numProcessors; percent *= 100; } lastCPU = now; lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; return percent; } void TupleFeeder::readConfig(const std::string & file) { boost::property_tree::ptree pt; boost::property_tree::read_info(file, pt); unsigned int usedChannel = pt.get("usedChannel", usedChannel); _usedChannel = static_cast<m2etis::pubsub::ChannelName>(usedChannel); _numToSend = pt.get("numToSend", _numToSend); _packetSize = pt.get("packetSize", _packetSize); _maxMessages = pt.get("maxMessages", _maxMessages); _tickTime = 1000000 / _numToSend; _ticksPerSec = _numToSend; } void TupleFeeder::readCin() { std::string s; while (true) { std::getline(std::cin, s); if (s == "s") { _objCondExecutable.notify_all(); } else if (s == "p") { _objCondExecutable.notify_all(); } else if (s == "x") { _lock.lock(); _running = false; _lock.unlock(); break; } } } void TupleFeeder::saveMeasurements() { std::fstream f(_owner + "_messages.xml", std::ios_base::out); for (long l : _timeList) { f << "<event type=\"deliver time\">" << l << "</event>" << std::endl; } f << "<event type=\"average time\">" << _wholeTime / (_maxMessages / _numToSend) << "</event>" << std::endl; f.close(); std::fstream f2(_owner + "_profiling.xml", std::ios_base::out); for (std::tuple<int, int, double> p : _profiling) { f2 << "<profiling><PRAM>" << std::get<0>(p) << "</PRAM><VRAM>" << std::get<1>(p) << "</VRAM><CPU>" << std::get<2>(p) << "</CPU></profiling>" << std::endl; } f2.close(); }
09671806454a039a286a663d14556abe40ee9aae
45e5f37eff4a4cc3ab092194b24f654b137094d0
/小易的升级之路.cpp
45e16c15b990ae0bf860a4b63a5f87ee7447f4fc
[]
no_license
LJComeo/1130
ee0a60061dc1fb03c5ca654ea739ea2572350f3f
95b4794a609e82364e1599bdf1f839083071a14b
refs/heads/master
2020-09-22T01:25:27.059726
2019-12-01T06:14:57
2019-12-01T06:14:57
225,002,484
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
小易的升级之路.cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> using namespace std; int MaxNum(int m, int n) { int tmp; while (n) { tmp = n; n = m % n; m = tmp; } return m; } int main1() { int n,m; while (scanf("%d%d", &n, &m) != EOF) { int num = 0; for (int i = 0; i < n; ++i) { scanf("%d", &num); if (m >= num) { m += num; } else { m += MaxNum(m, num); } } printf("%d\n", m); } return 0; }
ed57d1b8c04ffd3446b4e403ecfdcf69092469c9
3282ccae547452b96c4409e6b5a447f34b8fdf64
/SimModel_Python_API/simmodel_swig/SimModel/framework/SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent.hxx
2d20625fd48682f82f8696d0db52cd391c2b3b7f
[ "MIT" ]
permissive
EnEff-BIM/EnEffBIM-Framework
c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
refs/heads/master
2021-01-18T00:16:06.546875
2017-04-18T08:03:40
2017-04-18T08:03:40
28,960,534
3
0
null
2017-04-18T08:03:40
2015-01-08T10:19:18
C++
UTF-8
C++
false
false
32,946
hxx
SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent.hxx
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef SIM_FLOW_ENERGY_TRANSFER_HEAT_EX_AIR_TO_AIR_SENSIBLE_AND_LATENT_HXX #define SIM_FLOW_ENERGY_TRANSFER_HEAT_EX_AIR_TO_AIR_SENSIBLE_AND_LATENT_HXX #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace schema { namespace simxml { namespace MepModel { class SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent; } } } #include <memory> // ::std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "simflowenergytransfer_heatexairtoair.hxx" namespace schema { namespace simxml { namespace MepModel { class SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent: public ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExAirToAir { public: // SimFlowEnergyTrans_NomSupplyAirFlowRate // typedef ::xml_schema::double_ SimFlowEnergyTrans_NomSupplyAirFlowRate_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_NomSupplyAirFlowRate_type > SimFlowEnergyTrans_NomSupplyAirFlowRate_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_NomSupplyAirFlowRate_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_NomSupplyAirFlowRate_traits; const SimFlowEnergyTrans_NomSupplyAirFlowRate_optional& SimFlowEnergyTrans_NomSupplyAirFlowRate () const; SimFlowEnergyTrans_NomSupplyAirFlowRate_optional& SimFlowEnergyTrans_NomSupplyAirFlowRate (); void SimFlowEnergyTrans_NomSupplyAirFlowRate (const SimFlowEnergyTrans_NomSupplyAirFlowRate_type& x); void SimFlowEnergyTrans_NomSupplyAirFlowRate (const SimFlowEnergyTrans_NomSupplyAirFlowRate_optional& x); // SimFlowEnergyTrans_NomElecPwr // typedef ::xml_schema::double_ SimFlowEnergyTrans_NomElecPwr_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_NomElecPwr_type > SimFlowEnergyTrans_NomElecPwr_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_NomElecPwr_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_NomElecPwr_traits; const SimFlowEnergyTrans_NomElecPwr_optional& SimFlowEnergyTrans_NomElecPwr () const; SimFlowEnergyTrans_NomElecPwr_optional& SimFlowEnergyTrans_NomElecPwr (); void SimFlowEnergyTrans_NomElecPwr (const SimFlowEnergyTrans_NomElecPwr_type& x); void SimFlowEnergyTrans_NomElecPwr (const SimFlowEnergyTrans_NomElecPwr_optional& x); // SimFlowEnergyTrans_SupplyAirInletNodeName // typedef ::xml_schema::string SimFlowEnergyTrans_SupplyAirInletNodeName_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SupplyAirInletNodeName_type > SimFlowEnergyTrans_SupplyAirInletNodeName_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SupplyAirInletNodeName_type, char > SimFlowEnergyTrans_SupplyAirInletNodeName_traits; const SimFlowEnergyTrans_SupplyAirInletNodeName_optional& SimFlowEnergyTrans_SupplyAirInletNodeName () const; SimFlowEnergyTrans_SupplyAirInletNodeName_optional& SimFlowEnergyTrans_SupplyAirInletNodeName (); void SimFlowEnergyTrans_SupplyAirInletNodeName (const SimFlowEnergyTrans_SupplyAirInletNodeName_type& x); void SimFlowEnergyTrans_SupplyAirInletNodeName (const SimFlowEnergyTrans_SupplyAirInletNodeName_optional& x); void SimFlowEnergyTrans_SupplyAirInletNodeName (::std::auto_ptr< SimFlowEnergyTrans_SupplyAirInletNodeName_type > p); // SimFlowEnergyTrans_SupplyAirOutletNodeName // typedef ::xml_schema::string SimFlowEnergyTrans_SupplyAirOutletNodeName_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SupplyAirOutletNodeName_type > SimFlowEnergyTrans_SupplyAirOutletNodeName_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SupplyAirOutletNodeName_type, char > SimFlowEnergyTrans_SupplyAirOutletNodeName_traits; const SimFlowEnergyTrans_SupplyAirOutletNodeName_optional& SimFlowEnergyTrans_SupplyAirOutletNodeName () const; SimFlowEnergyTrans_SupplyAirOutletNodeName_optional& SimFlowEnergyTrans_SupplyAirOutletNodeName (); void SimFlowEnergyTrans_SupplyAirOutletNodeName (const SimFlowEnergyTrans_SupplyAirOutletNodeName_type& x); void SimFlowEnergyTrans_SupplyAirOutletNodeName (const SimFlowEnergyTrans_SupplyAirOutletNodeName_optional& x); void SimFlowEnergyTrans_SupplyAirOutletNodeName (::std::auto_ptr< SimFlowEnergyTrans_SupplyAirOutletNodeName_type > p); // SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_type > SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_traits; const SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow () const; SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow (); void SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow (const SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_type& x); void SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow (const SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_optional& x); // SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_type > SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_traits; const SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow () const; SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow (); void SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow (const SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_type& x); void SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow (const SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_optional& x); // SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_type > SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_traits; const SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow () const; SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow (); void SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow (const SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_type& x); void SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow (const SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_optional& x); // SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_type > SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_traits; const SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow () const; SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow (); void SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow (const SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_type& x); void SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow (const SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_optional& x); // SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_type > SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_traits; const SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow () const; SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow (); void SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow (const SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_type& x); void SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow (const SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_optional& x); // SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_type > SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_traits; const SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow () const; SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow (); void SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow (const SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_type& x); void SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow (const SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_optional& x); // SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_type > SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_traits; const SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow () const; SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_optional& SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow (); void SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow (const SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_type& x); void SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow (const SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_optional& x); // SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow // typedef ::xml_schema::double_ SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_type > SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_traits; const SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow () const; SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_optional& SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow (); void SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow (const SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_type& x); void SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow (const SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_optional& x); // SimFlowEnergyTrans_ExhAirInletNodeName // typedef ::xml_schema::string SimFlowEnergyTrans_ExhAirInletNodeName_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_ExhAirInletNodeName_type > SimFlowEnergyTrans_ExhAirInletNodeName_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_ExhAirInletNodeName_type, char > SimFlowEnergyTrans_ExhAirInletNodeName_traits; const SimFlowEnergyTrans_ExhAirInletNodeName_optional& SimFlowEnergyTrans_ExhAirInletNodeName () const; SimFlowEnergyTrans_ExhAirInletNodeName_optional& SimFlowEnergyTrans_ExhAirInletNodeName (); void SimFlowEnergyTrans_ExhAirInletNodeName (const SimFlowEnergyTrans_ExhAirInletNodeName_type& x); void SimFlowEnergyTrans_ExhAirInletNodeName (const SimFlowEnergyTrans_ExhAirInletNodeName_optional& x); void SimFlowEnergyTrans_ExhAirInletNodeName (::std::auto_ptr< SimFlowEnergyTrans_ExhAirInletNodeName_type > p); // SimFlowEnergyTrans_ExhAirOutletNodeName // typedef ::xml_schema::string SimFlowEnergyTrans_ExhAirOutletNodeName_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_ExhAirOutletNodeName_type > SimFlowEnergyTrans_ExhAirOutletNodeName_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_ExhAirOutletNodeName_type, char > SimFlowEnergyTrans_ExhAirOutletNodeName_traits; const SimFlowEnergyTrans_ExhAirOutletNodeName_optional& SimFlowEnergyTrans_ExhAirOutletNodeName () const; SimFlowEnergyTrans_ExhAirOutletNodeName_optional& SimFlowEnergyTrans_ExhAirOutletNodeName (); void SimFlowEnergyTrans_ExhAirOutletNodeName (const SimFlowEnergyTrans_ExhAirOutletNodeName_type& x); void SimFlowEnergyTrans_ExhAirOutletNodeName (const SimFlowEnergyTrans_ExhAirOutletNodeName_optional& x); void SimFlowEnergyTrans_ExhAirOutletNodeName (::std::auto_ptr< SimFlowEnergyTrans_ExhAirOutletNodeName_type > p); // SimFlowEnergyTrans_SupplyAirOutletTempCntl // typedef ::xml_schema::string SimFlowEnergyTrans_SupplyAirOutletTempCntl_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_SupplyAirOutletTempCntl_type > SimFlowEnergyTrans_SupplyAirOutletTempCntl_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_SupplyAirOutletTempCntl_type, char > SimFlowEnergyTrans_SupplyAirOutletTempCntl_traits; const SimFlowEnergyTrans_SupplyAirOutletTempCntl_optional& SimFlowEnergyTrans_SupplyAirOutletTempCntl () const; SimFlowEnergyTrans_SupplyAirOutletTempCntl_optional& SimFlowEnergyTrans_SupplyAirOutletTempCntl (); void SimFlowEnergyTrans_SupplyAirOutletTempCntl (const SimFlowEnergyTrans_SupplyAirOutletTempCntl_type& x); void SimFlowEnergyTrans_SupplyAirOutletTempCntl (const SimFlowEnergyTrans_SupplyAirOutletTempCntl_optional& x); void SimFlowEnergyTrans_SupplyAirOutletTempCntl (::std::auto_ptr< SimFlowEnergyTrans_SupplyAirOutletTempCntl_type > p); // SimFlowEnergyTrans_HeatExchngType // typedef ::xml_schema::string SimFlowEnergyTrans_HeatExchngType_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_HeatExchngType_type > SimFlowEnergyTrans_HeatExchngType_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_HeatExchngType_type, char > SimFlowEnergyTrans_HeatExchngType_traits; const SimFlowEnergyTrans_HeatExchngType_optional& SimFlowEnergyTrans_HeatExchngType () const; SimFlowEnergyTrans_HeatExchngType_optional& SimFlowEnergyTrans_HeatExchngType (); void SimFlowEnergyTrans_HeatExchngType (const SimFlowEnergyTrans_HeatExchngType_type& x); void SimFlowEnergyTrans_HeatExchngType (const SimFlowEnergyTrans_HeatExchngType_optional& x); void SimFlowEnergyTrans_HeatExchngType (::std::auto_ptr< SimFlowEnergyTrans_HeatExchngType_type > p); // SimFlowEnergyTrans_FrostCntlType // typedef ::xml_schema::string SimFlowEnergyTrans_FrostCntlType_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_FrostCntlType_type > SimFlowEnergyTrans_FrostCntlType_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_FrostCntlType_type, char > SimFlowEnergyTrans_FrostCntlType_traits; const SimFlowEnergyTrans_FrostCntlType_optional& SimFlowEnergyTrans_FrostCntlType () const; SimFlowEnergyTrans_FrostCntlType_optional& SimFlowEnergyTrans_FrostCntlType (); void SimFlowEnergyTrans_FrostCntlType (const SimFlowEnergyTrans_FrostCntlType_type& x); void SimFlowEnergyTrans_FrostCntlType (const SimFlowEnergyTrans_FrostCntlType_optional& x); void SimFlowEnergyTrans_FrostCntlType (::std::auto_ptr< SimFlowEnergyTrans_FrostCntlType_type > p); // SimFlowEnergyTrans_ThreshTemp // typedef ::xml_schema::double_ SimFlowEnergyTrans_ThreshTemp_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_ThreshTemp_type > SimFlowEnergyTrans_ThreshTemp_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_ThreshTemp_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_ThreshTemp_traits; const SimFlowEnergyTrans_ThreshTemp_optional& SimFlowEnergyTrans_ThreshTemp () const; SimFlowEnergyTrans_ThreshTemp_optional& SimFlowEnergyTrans_ThreshTemp (); void SimFlowEnergyTrans_ThreshTemp (const SimFlowEnergyTrans_ThreshTemp_type& x); void SimFlowEnergyTrans_ThreshTemp (const SimFlowEnergyTrans_ThreshTemp_optional& x); // SimFlowEnergyTrans_InitDefrostTimeFract // typedef ::xml_schema::double_ SimFlowEnergyTrans_InitDefrostTimeFract_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_InitDefrostTimeFract_type > SimFlowEnergyTrans_InitDefrostTimeFract_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_InitDefrostTimeFract_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_InitDefrostTimeFract_traits; const SimFlowEnergyTrans_InitDefrostTimeFract_optional& SimFlowEnergyTrans_InitDefrostTimeFract () const; SimFlowEnergyTrans_InitDefrostTimeFract_optional& SimFlowEnergyTrans_InitDefrostTimeFract (); void SimFlowEnergyTrans_InitDefrostTimeFract (const SimFlowEnergyTrans_InitDefrostTimeFract_type& x); void SimFlowEnergyTrans_InitDefrostTimeFract (const SimFlowEnergyTrans_InitDefrostTimeFract_optional& x); // SimFlowEnergyTrans_RateDefrostTimeFractcrease // typedef ::xml_schema::double_ SimFlowEnergyTrans_RateDefrostTimeFractcrease_type; typedef ::xsd::cxx::tree::optional< SimFlowEnergyTrans_RateDefrostTimeFractcrease_type > SimFlowEnergyTrans_RateDefrostTimeFractcrease_optional; typedef ::xsd::cxx::tree::traits< SimFlowEnergyTrans_RateDefrostTimeFractcrease_type, char, ::xsd::cxx::tree::schema_type::double_ > SimFlowEnergyTrans_RateDefrostTimeFractcrease_traits; const SimFlowEnergyTrans_RateDefrostTimeFractcrease_optional& SimFlowEnergyTrans_RateDefrostTimeFractcrease () const; SimFlowEnergyTrans_RateDefrostTimeFractcrease_optional& SimFlowEnergyTrans_RateDefrostTimeFractcrease (); void SimFlowEnergyTrans_RateDefrostTimeFractcrease (const SimFlowEnergyTrans_RateDefrostTimeFractcrease_type& x); void SimFlowEnergyTrans_RateDefrostTimeFractcrease (const SimFlowEnergyTrans_RateDefrostTimeFractcrease_optional& x); // Constructors. // SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent (); SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent (const RefId_type&); SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent (const SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent& operator= (const SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent& x); virtual ~SimFlowEnergyTransfer_HeatExAirToAir_SensibleAndLatent (); // Implementation. // protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: SimFlowEnergyTrans_NomSupplyAirFlowRate_optional SimFlowEnergyTrans_NomSupplyAirFlowRate_; SimFlowEnergyTrans_NomElecPwr_optional SimFlowEnergyTrans_NomElecPwr_; SimFlowEnergyTrans_SupplyAirInletNodeName_optional SimFlowEnergyTrans_SupplyAirInletNodeName_; SimFlowEnergyTrans_SupplyAirOutletNodeName_optional SimFlowEnergyTrans_SupplyAirOutletNodeName_; SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_optional SimFlowEnergyTrans_SensEffectAt100PctHeatingAirFlow_; SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_optional SimFlowEnergyTrans_LatentEffectAt100PctHeatingAirFlow_; SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_optional SimFlowEnergyTrans_SensEffectAt75PctHeatingAirFlow_; SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_optional SimFlowEnergyTrans_LatentEffectAt75PctHeatingAirFlow_; SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_optional SimFlowEnergyTrans_SensEffectAt100PctCoolingAirFlow_; SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_optional SimFlowEnergyTrans_LatentEffectAt100PctCoolingAirFlow_; SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_optional SimFlowEnergyTrans_SensEffectAt75PctCoolingAirFlow_; SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_optional SimFlowEnergyTrans_LatentEffectAt75PctCoolingAirFlow_; SimFlowEnergyTrans_ExhAirInletNodeName_optional SimFlowEnergyTrans_ExhAirInletNodeName_; SimFlowEnergyTrans_ExhAirOutletNodeName_optional SimFlowEnergyTrans_ExhAirOutletNodeName_; SimFlowEnergyTrans_SupplyAirOutletTempCntl_optional SimFlowEnergyTrans_SupplyAirOutletTempCntl_; SimFlowEnergyTrans_HeatExchngType_optional SimFlowEnergyTrans_HeatExchngType_; SimFlowEnergyTrans_FrostCntlType_optional SimFlowEnergyTrans_FrostCntlType_; SimFlowEnergyTrans_ThreshTemp_optional SimFlowEnergyTrans_ThreshTemp_; SimFlowEnergyTrans_InitDefrostTimeFract_optional SimFlowEnergyTrans_InitDefrostTimeFract_; SimFlowEnergyTrans_RateDefrostTimeFractcrease_optional SimFlowEnergyTrans_RateDefrostTimeFractcrease_; }; } } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // SIM_FLOW_ENERGY_TRANSFER_HEAT_EX_AIR_TO_AIR_SENSIBLE_AND_LATENT_HXX
10d3a95473f6b1d529953685dee1ef94a195c8f8
86d79021da256ddbc947bb8bf775289c5f398923
/ui_WPosicionarDos.h
40465d07633eea0be4406b40fb44fc3e40b217d9
[]
no_license
Edgar1us/SnakeQT
825c8bc6926c0f8748f65d9a49603d582e00f007
8e7e16e3569d7de340cd3b70eba2ca18c62a5d99
refs/heads/master
2023-05-23T22:43:02.932245
2021-06-15T10:51:02
2021-06-15T10:51:02
350,343,710
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
h
ui_WPosicionarDos.h
/******************************************************************************** ** Form generated from reading UI file 'WPosicionarDos.ui' ** ** Created by: Qt User Interface Compiler version 5.9.5 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_WPOSICIONARDOS_H #define UI_WPOSICIONARDOS_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_WPosicionarDos { public: void setupUi(QWidget *WPosicionarDos) { if (WPosicionarDos->objectName().isEmpty()) WPosicionarDos->setObjectName(QStringLiteral("WPosicionarDos")); WPosicionarDos->resize(400, 300); retranslateUi(WPosicionarDos); QMetaObject::connectSlotsByName(WPosicionarDos); } // setupUi void retranslateUi(QWidget *WPosicionarDos) { WPosicionarDos->setWindowTitle(QApplication::translate("WPosicionarDos", "Form", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class WPosicionarDos: public Ui_WPosicionarDos {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_WPOSICIONARDOS_H
85222b78d8ebb08a6cf3b703de3c1a796894d728
eca634ce6477e5680987dfc6536f6fdd93c58db6
/DeferredClient/DetailsManager.cpp
0e973242a1504f33d1ff8c18c4763fde3ce9355d
[]
no_license
tectronics/surface-physics
ba2ed585406f9e9955aeabc6d343cedeb41c2f61
f5f2af539aee7483ae28f4edec4b7b62edfa2d61
refs/heads/master
2018-01-11T15:03:08.166454
2014-10-02T19:44:33
2014-10-02T19:44:33
45,230,360
0
0
null
null
null
null
UTF-8
C++
false
false
54,679
cpp
DetailsManager.cpp
#include "TerrainManager.h" DetailsManager::DetailsManager( TerrainManager *_term, PlanetaryConfig *_CFG ) { term = _term; CFG = _CFG; GS_Average = GS_High = GS_City = NULL; PS_Average = PS_High = PS_City = NULL; aTextures_AverageHigh = NULL; VB_AverageHigh = NULL; } DetailsManager::~DetailsManager() { //vegetation: REL( aTextures_AverageHigh ); REL( GS_Average ); REL( PS_Average ); REL( GS_High ); REL( PS_High ); //city: for( int j = 0; j < aMESH.size(); j++ ) { REL( aMESH[j].VB ); REL( aMESH[j].aTextures ); } aMESH.clear(); REL( GS_City ); REL( PS_City ); } UINT DetailsManager::Stride_POINTVERTEX = 52, DetailsManager::Stride_TRIANGLEVERTEX = 48, DetailsManager::ntile_avg = 0, DetailsManager::size_avg = 0, DetailsManager::ntile_high = 0, DetailsManager::size_high = 0, DetailsManager::ntile_city = 0, DetailsManager::size_city = 0; TILERENDERSPEC *DetailsManager::TRS_AVG = NULL, *DetailsManager::TRS_HIGH = NULL, *DetailsManager::TRS_CITY = NULL; ID3D11InputLayout *DetailsManager::IL_POINTVERTEX = NULL, *DetailsManager::IL_TRIANGLEVERTEX = NULL; ID3D11VertexShader *DetailsManager::VS_AverageHigh = NULL, *DetailsManager::VS_City = NULL; DetailsManager::RENDERPARAM DetailsManager::RP; ID3D11Buffer *DetailsManager::VB_AverageHigh = NULL, *DetailsManager::VSCB_Tile = NULL, *DetailsManager::CB_AtmParams = NULL, *DetailsManager::CB_PlanetShadowParams = NULL, *DetailsManager::CB_CoverTypeParams = NULL; ID3D11DepthStencilState *DetailsManager::DSS_Tile = NULL; ID3D11SamplerState *DetailsManager::SS_HeightMap = NULL, //<= TileRenderMgr *DetailsManager::SS_TileTexture = NULL, //<= TileRenderMgr *DetailsManager::SS_TextureAverageHigh = NULL, *DetailsManager::SS_TextureCity = NULL; void DetailsManager::GlobalInit( ID3D11Buffer *_CB_AtmParams, ID3D11Buffer *_CB_EclipseParams ) { CB_AtmParams = _CB_AtmParams; //_CB_EclipseParams HRESULT hr; ID3DBlob *SBlob = NULL, *EBlob = NULL; //average and high detalization vegetation/rocks: D3D11_INPUT_ELEMENT_DESC iedesc[ ] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 36, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT, 0, 44, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 2, DXGI_FORMAT_R32_FLOAT, 0, 48, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\VS_AverageHigh.fx", NULL, NULL, "VS_AverageHigh", vs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateInputLayout( iedesc, 6, SBlob->GetBufferPointer(), SBlob->GetBufferSize(), &IL_POINTVERTEX ) ); HR( Dev->CreateVertexShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &VS_AverageHigh ) ); REL( SBlob ); REL( EBlob ); //cities: D3D11_INPUT_ELEMENT_DESC iedesc_city[ ] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 2, DXGI_FORMAT_R32G32B32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 36, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 1, DXGI_FORMAT_R32_UINT, 0, 44, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\VS_City.fx", NULL, NULL, "VS_City", vs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateInputLayout( iedesc_city, 5, SBlob->GetBufferPointer(), SBlob->GetBufferSize(), &IL_TRIANGLEVERTEX ) ); HR( Dev->CreateVertexShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &VS_City ) ); REL( SBlob ); REL( EBlob ); D3D11_BUFFER_DESC bdesc; D3D11_SUBRESOURCE_DATA sdata; D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc; //======================================================= // Vertex buffer of randomly positioned points //======================================================= memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_SHADER_RESOURCE; bdesc.ByteWidth = Stride_POINTVERTEX*NPOINT; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; bdesc.StructureByteStride = Stride_POINTVERTEX; bdesc.Usage = D3D11_USAGE_DEFAULT; double lat, lng, maxlat = PI05/512.0, maxlng = PI2/2048.0; POINTVERTEX vtx, *VTX = new POINTVERTEX [NPOINT]; for( UINT j = 0; j < NPOINT; j++ ) { lat = maxlat*(double(rand())/double(RAND_MAX)); lng = maxlng*(double(rand())/double(RAND_MAX)); vtx.PosL.x = 1000.0*cos(lng)*cos(lat); vtx.PosL.y = 1000.0*sin(lat); vtx.PosL.z = 1000.0*sin(lng)*cos(lat); D3DXVec3Normalize( &vtx.NormL, &vtx.PosL ); vtx.TangL.x = -1.0*sin(lng)*cos(lat); vtx.TangL.y = cos(lat); vtx.TangL.z = cos(lng)*cos(lat); vtx.TCrd = D3DXVECTOR2( lng/maxlng, lat/maxlat ); vtx.dist = 0.0;//random ? vtx.rnd = double(rand())/double(RAND_MAX); VTX[j] = vtx; } memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = VTX; Dev->CreateBuffer( &bdesc, &sdata, &VB_AverageHigh ); delete [ ] VTX; //constant buffers memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bdesc.ByteWidth = 96; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = 0; bdesc.StructureByteStride = 0; bdesc.Usage = D3D11_USAGE_DEFAULT; Dev->CreateBuffer( &bdesc, &sdata, &VSCB_Tile ); //TILERENDERSPEC buffers TRS_AVG = new TILERENDERSPEC [32]; size_avg = 32; TRS_HIGH = new TILERENDERSPEC [32]; size_high = 32; TRS_CITY = new TILERENDERSPEC [32]; size_city = 32; //samplers: SS_HeightMap = TileRenderMgr::SS_HeightMap; SS_TileTexture = TileRenderMgr::SS_TileTexture; D3D11_SAMPLER_DESC sdesc; //average and high detalization textures memset( &sdesc, 0, sizeof(sdesc) ); sdesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;//<= cfg sdesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; sdesc.MaxAnisotropy = 1; sdesc.MipLODBias = 0; sdesc.MinLOD = 0; sdesc.MaxLOD = D3D11_FLOAT32_MAX; Dev->CreateSamplerState( &sdesc, &SS_TextureAverageHigh ); //building textures memset( &sdesc, 0, sizeof(sdesc) ); sdesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sdesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;//<= cfg sdesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; sdesc.MaxAnisotropy = 1; sdesc.MipLODBias = 0; sdesc.MinLOD = 0; sdesc.MaxLOD = D3D11_FLOAT32_MAX; Dev->CreateSamplerState( &sdesc, &SS_TextureCity ); D3D11_DEPTH_STENCIL_DESC ddesc; //depth-stencil state with enabled depth memset( &ddesc, 0, sizeof(ddesc) ); ddesc.DepthEnable = true; ddesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; ddesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; ddesc.StencilEnable = false; ddesc.StencilReadMask = 0; ddesc.StencilWriteMask = 0; Dev->CreateDepthStencilState( &ddesc, &DSS_Tile ); } void DetailsManager::GlobalExit() { REL( IL_POINTVERTEX ); REL( IL_TRIANGLEVERTEX ); REL( VSCB_Tile ); REL( VB_AverageHigh ); REL( VS_AverageHigh ); REL( VS_City ); delete [ ] TRS_AVG; delete [ ] TRS_HIGH; delete [ ] TRS_CITY; REL( SS_TextureAverageHigh ); REL( SS_TextureCity ); } void DetailsManager::Render( TILERENDERSPEC *TRS, UINT ntile ) { if( !CFG->bTerrainDetails_Average ) return; //create list of average, high and city tiles bool south = false; RP.cpos = term->RP.cpos; RP.objsize = term->RP.objsize; RP.mWorld_tmp = RP.mWorld = term->mWorld_north; RP.grot = term->grot_north; for( int j = 0; j < ntile; j++ ) { if( TRS[j].hemisphere && !south ) { D3DXMatrixMultiply( &RP.mWorld, &term->RSouth, &RP.mWorld ); RP.mWorld_tmp = RP.mWorld; RP.grot.m12 = -RP.grot.m12; RP.grot.m13 = -RP.grot.m13; RP.grot.m22 = -RP.grot.m22; RP.grot.m23 = -RP.grot.m23; RP.grot.m32 = -RP.grot.m32; RP.grot.m33 = -RP.grot.m33; south = true; } ProcessTile( TRS[j].level, TRS[j].hemisphere, TRS[j].ilat, TRS[j].nlat, TRS[j].ilng, TRS[j].nlng, TRS[j].td, TRS[j].RANGE, TRS[j].Tex, TRS[j].RANGE, TRS[j].Tex ); } const UINT VBOffset = 0; iCtx->IASetInputLayout( IL_POINTVERTEX ); iCtx->IASetVertexBuffers( 0, 1, &VB_AverageHigh, &Stride_POINTVERTEX, &VBOffset ); iCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST ); iCtx->VSSetShader( VS_AverageHigh, NULL, 0 ); iCtx->VSSetSamplers( 0, 1, &SS_HeightMap ); iCtx->VSSetConstantBuffers( 0, 1, &VSCB_Tile ); iCtx->RSSetState( RS_CullNone_Solid ); iCtx->OMSetBlendState( BS_SrcAlpha, D3DXVECTOR4( 1, 1, 1, 1 ), 0xFFFFFFFF ); iCtx->OMSetDepthStencilState( DSS_Tile, 0 ); //================================================================================== // Average //================================================================================== iCtx->UpdateSubresource( cb_D3DXMATRIX_x1, 0, NULL, SC->GetVP(), 0, 0 ); iCtx->GSSetShader( GS_Average, NULL, 0 ); iCtx->GSSetConstantBuffers( 0, 1, &cb_D3DXMATRIX_x1 ); iCtx->GSSetConstantBuffers( 1, 1, &CB_CoverTypeParams ); //texture idx etc. data <= TileRenderMgr iCtx->GSSetSamplers( 0, 1, &SS_TileTexture ); iCtx->PSSetShader( PS_Average, NULL, 0 ); //iCtx->PSSetConstantBuffers( 0, 1, &cb_PSCB_per_frame ); iCtx->PSSetConstantBuffers( 1, 1, &CB_CoverTypeParams ); iCtx->PSSetShaderResources( 0, 1, &aTextures_AverageHigh ); iCtx->PSSetSamplers( 0, 1, &SS_TextureAverageHigh ); VSCB_per_tile vbuf; for( int j = 0; j < ntile_avg; j++ ) { vbuf.W = TRS_AVG[j].mWorld; vbuf.TexOff[0] = TRS_AVG[j].RANGE.range_tex.tumax - TRS_AVG[j].RANGE.range_tex.tumin; vbuf.TexOff[1] = TRS_AVG[j].RANGE.range_tex.tumin; vbuf.TexOff[2] = TRS_AVG[j].RANGE.range_tex.tvmax - TRS_AVG[j].RANGE.range_tex.tvmin; vbuf.TexOff[3] = TRS_AVG[j].RANGE.range_tex.tvmin; vbuf.TexOff_height[0] = TRS_AVG[j].RANGE.range_height.tumax - TRS_AVG[j].RANGE.range_height.tumin; vbuf.TexOff_height[1] = TRS_AVG[j].RANGE.range_height.tumin; vbuf.TexOff_height[2] = TRS_AVG[j].RANGE.range_height.tvmax - TRS_AVG[j].RANGE.range_height.tvmin; vbuf.TexOff_height[3] = TRS_AVG[j].RANGE.range_height.tvmin; vbuf.TexOff_lcover[0] = TRS_AVG[j].RANGE.range_lcover.tumax - TRS_AVG[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[1] = TRS_AVG[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[2] = TRS_AVG[j].RANGE.range_lcover.tvmax - TRS_AVG[j].RANGE.range_lcover.tvmin; vbuf.TexOff_lcover[3] = TRS_AVG[j].RANGE.range_lcover.tvmin; iCtx->UpdateSubresource( VSCB_Tile, 0, NULL, &vbuf, 0, 0 ); iCtx->VSSetShaderResources( 0, 1, TRS_AVG[j].Tex.htex->GetTexture() ); iCtx->GSSetShaderResources( 0, 1, TRS_AVG[j].Tex.tex->GetTexture() ); iCtx->GSSetShaderResources( 1, 1, &TRS_AVG[j].Tex.ctex ); iCtx->Draw( NPOINT, 0 ); } //================================================================================== // High //================================================================================== if( !CFG->bTerrainDetails_High ) { iCtx->GSSetShader( NULL, NULL, 0 ); return; } iCtx->GSSetShader( GS_High, NULL, 0 ); iCtx->PSSetShader( PS_High, NULL, 0 ); for( int j = 0; j < ntile_high; j++ ) { vbuf.W = TRS_HIGH[j].mWorld; vbuf.TexOff[0] = TRS_HIGH[j].RANGE.range_tex.tumax - TRS_HIGH[j].RANGE.range_tex.tumin; vbuf.TexOff[1] = TRS_HIGH[j].RANGE.range_tex.tumin; vbuf.TexOff[2] = TRS_HIGH[j].RANGE.range_tex.tvmax - TRS_HIGH[j].RANGE.range_tex.tvmin; vbuf.TexOff[3] = TRS_HIGH[j].RANGE.range_tex.tvmin; vbuf.TexOff_height[0] = TRS_HIGH[j].RANGE.range_height.tumax - TRS_HIGH[j].RANGE.range_height.tumin; vbuf.TexOff_height[1] = TRS_HIGH[j].RANGE.range_height.tumin; vbuf.TexOff_height[2] = TRS_HIGH[j].RANGE.range_height.tvmax - TRS_HIGH[j].RANGE.range_height.tvmin; vbuf.TexOff_height[3] = TRS_HIGH[j].RANGE.range_height.tvmin; vbuf.TexOff_lcover[0] = TRS_HIGH[j].RANGE.range_lcover.tumax - TRS_HIGH[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[1] = TRS_HIGH[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[2] = TRS_HIGH[j].RANGE.range_lcover.tvmax - TRS_HIGH[j].RANGE.range_lcover.tvmin; vbuf.TexOff_lcover[3] = TRS_HIGH[j].RANGE.range_lcover.tvmin; iCtx->UpdateSubresource( VSCB_Tile, 0, NULL, &vbuf, 0, 0 ); iCtx->VSSetShaderResources( 0, 1, TRS_HIGH[j].Tex.htex->GetTexture() ); iCtx->GSSetShaderResources( 0, 1, TRS_HIGH[j].Tex.tex->GetTexture() ); iCtx->GSSetShaderResources( 1, 1, &TRS_HIGH[j].Tex.ctex ); iCtx->Draw( NPOINT, 0 ); } //================================================================================== // Urban //================================================================================== if( !ntile_city ) { iCtx->GSSetShader( NULL, NULL, 0 ); return; } //urban zones //pseudo-random value define idx of mesh: UINT nmesh = aMESH.size(); iCtx->IASetInputLayout( IL_TRIANGLEVERTEX ); iCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST ); iCtx->VSSetShader( VS_City, NULL, 0 ); iCtx->GSSetShader( GS_City, NULL, 0 ); iCtx->PSSetShader( PS_City, NULL, 0 ); iCtx->OMSetBlendState( BS_NoBlend, D3DXVECTOR4( 1, 1, 1, 1 ), 0xFFFFFFFF ); for( int j = 0; j < ntile_city; j++ ) { srand( TRS_CITY[j].ilat + TRS_CITY[j].ilng ); UINT idx = rand() % nmesh; iCtx->IASetVertexBuffers( 0, 1, &aMESH[idx].VB, &Stride_TRIANGLEVERTEX, &VBOffset ); vbuf.W = TRS_CITY[j].mWorld; vbuf.TexOff[0] = TRS_CITY[j].RANGE.range_tex.tumax - TRS_CITY[j].RANGE.range_tex.tumin; vbuf.TexOff[1] = TRS_CITY[j].RANGE.range_tex.tumin; vbuf.TexOff[2] = TRS_CITY[j].RANGE.range_tex.tvmax - TRS_CITY[j].RANGE.range_tex.tvmin; vbuf.TexOff[3] = TRS_CITY[j].RANGE.range_tex.tvmin; vbuf.TexOff_height[0] = TRS_CITY[j].RANGE.range_height.tumax - TRS_CITY[j].RANGE.range_height.tumin; vbuf.TexOff_height[1] = TRS_CITY[j].RANGE.range_height.tumin; vbuf.TexOff_height[2] = TRS_CITY[j].RANGE.range_height.tvmax - TRS_CITY[j].RANGE.range_height.tvmin; vbuf.TexOff_height[3] = TRS_CITY[j].RANGE.range_height.tvmin; vbuf.TexOff_lcover[0] = TRS_CITY[j].RANGE.range_lcover.tumax - TRS_CITY[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[1] = TRS_CITY[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[2] = TRS_CITY[j].RANGE.range_lcover.tvmax - TRS_CITY[j].RANGE.range_lcover.tvmin; vbuf.TexOff_lcover[3] = TRS_CITY[j].RANGE.range_lcover.tvmin; iCtx->UpdateSubresource( VSCB_Tile, 0, NULL, &vbuf, 0, 0 ); iCtx->VSSetShaderResources( 0, 1, TRS_CITY[j].Tex.htex->GetTexture() ); iCtx->GSSetShaderResources( 0, 1, TRS_CITY[j].Tex.tex->GetTexture() ); iCtx->GSSetShaderResources( 1, 1, &TRS_CITY[j].Tex.ctex ); iCtx->Draw( aMESH[idx].nvtx, aMESH[idx].svtx ); } iCtx->GSSetShader( NULL, NULL, 0 ); } void DetailsManager::ProcessTile( UINT8 level, UINT8 hemisphere, UINT ilat, UINT nlat, UINT ilng, UINT nlng, TILEDESC1 *td, TILECRDRANGE RANGE, TILETEX Tex, TILECRDRANGE kbp_RANGE, TILETEX bkp_Tex ) { bool bStepDown = level < DETAILS_TILELVL; D3DXVECTOR3 bpos; D3DXMATRIX mWorld; TileWorldMatrix( hemisphere, ilat, nlat, ilng, nlng, mWorld ); D3DXVec3TransformCoord( &bpos, &td->bsPos, &mWorld ); float dist = D3DXVec3Length( &bpos ); float min_dist = (dist > td->bsRad ? dist - td->bsRad : 0.0f); float max_dist = dist + td->bsRad; if( min_dist > Details_maxdist ) return;//urban > average > high if( bStepDown ) { UINT idx = 0; float du[3] = { (RANGE.range_tex.tumax - RANGE.range_tex.tumin)*0.5f, (RANGE.range_height.tumax - RANGE.range_height.tumin)*0.5f, (RANGE.range_lcover.tumax - RANGE.range_lcover.tumin)*0.5f }; float dv[3] = { (RANGE.range_tex.tvmax - RANGE.range_tex.tvmin)*0.5f, (RANGE.range_height.tvmax - RANGE.range_height.tvmin)*0.5f, (RANGE.range_lcover.tvmax - RANGE.range_lcover.tvmin)*0.5f }; TILECRDRANGE SUBRANGE; static TEXCRDRANGE1 fullrange = { 0.0f, 1.0f, 0.0f, 1.0f }; for( int i = 1; i >= 0; i-- ) { SUBRANGE.range_tex.tvmax = (SUBRANGE.range_tex.tvmin = RANGE.range_tex.tvmin + (1-i)*dv[0]) + dv[0]; SUBRANGE.range_height.tvmax = (SUBRANGE.range_height.tvmin = RANGE.range_height.tvmin + (1-i)*dv[1]) + dv[1]; SUBRANGE.range_lcover.tvmax = (SUBRANGE.range_lcover.tvmin = RANGE.range_lcover.tvmin + (1-i)*dv[2]) + dv[2]; for( int j = 0; j < 2; j++ ) { SUBRANGE.range_tex.tumax = (SUBRANGE.range_tex.tumin = RANGE.range_tex.tumin + j*du[0]) + du[0]; SUBRANGE.range_height.tumax = (SUBRANGE.range_height.tumin = RANGE.range_height.tumin + j*du[1]) + du[1]; SUBRANGE.range_lcover.tumax = (SUBRANGE.range_lcover.tumin = RANGE.range_lcover.tumin + j*du[2]) + du[2]; bool bIsFull = true; TILEDESC1 *subtile = td->subtile[idx]; if( !subtile ) bIsFull = false; else if( subtile->flags & LOAD_TEX ) bIsFull = false; TILECRDRANGE nRANGE, nSUBRANGE; TILETEX nTex, bkp_nTex; if( bIsFull ) bIsFull = (subtile->tex != NULL); //height map if( !(subtile->flags & LOAD_HEIGHT) && subtile->htex ) { bkp_nTex.htex = nTex.htex = subtile->htex.get(); nSUBRANGE.range_height = nRANGE.range_height = fullrange; } else { bkp_nTex.htex = nTex.htex = Tex.htex; nSUBRANGE.range_height = nRANGE.range_height = SUBRANGE.range_height; } //land cover if( !(subtile->flags & LOAD_LCOVER) && subtile->ctex ) { bkp_nTex.ctex = nTex.ctex = subtile->ctex; nSUBRANGE.range_lcover = nRANGE.range_lcover = fullrange; } else { bkp_nTex.ctex = nTex.ctex = Tex.ctex; nSUBRANGE.range_lcover = nRANGE.range_lcover = SUBRANGE.range_lcover; } if( bIsFull ) { nTex.tex = subtile->tex.get(); nTex.ltex = subtile->ltex; bkp_nTex.tex = Tex.tex; bkp_nTex.ltex = Tex.ltex; nRANGE.range_tex = fullrange; nSUBRANGE.range_tex = SUBRANGE.range_tex; ProcessTile( level+1, hemisphere, ilat*2+i, nlat*2, ilng*2+j, nlng*2, subtile, nRANGE, nTex, nSUBRANGE, bkp_nTex ); } else { bkp_nTex.tex = nTex.tex = Tex.tex; bkp_nTex.ltex = nTex.ltex = Tex.ltex; nRANGE.range_tex = SUBRANGE.range_tex; nSUBRANGE.range_tex = SUBRANGE.range_tex; ProcessTile( level+1, hemisphere, ilat*2+i, nlat*2, ilng*2+j, nlng*2, subtile, nRANGE, nTex, nSUBRANGE, bkp_nTex ); } idx++; } } } else { if( min_dist < CFG->TerrainDetails_Average_maxdist && CFG->TerrainDetails_High_maxdist < max_dist ) { if( ntile_avg == size_avg ) ExpandTRSBuffer( TRS_AVG, size_avg ); TRS_AVG[ntile_avg].mWorld = mWorld; TRS_AVG[ntile_avg].ilat = ilat; TRS_AVG[ntile_avg].nlat = nlat; TRS_AVG[ntile_avg].ilng = ilng; TRS_AVG[ntile_avg].nlng = nlng; TRS_AVG[ntile_avg].hemisphere = hemisphere; TRS_AVG[ntile_avg].level = level; TRS_AVG[ntile_avg].RANGE = RANGE; TRS_AVG[ntile_avg].Tex = Tex; ntile_avg++; } if( CFG->bTerrainDetails_High && min_dist < CFG->TerrainDetails_High_maxdist ) { if( ntile_high == size_high ) ExpandTRSBuffer( TRS_HIGH, size_high ); TRS_HIGH[ntile_high].mWorld = mWorld; TRS_HIGH[ntile_high].ilat = ilat; TRS_HIGH[ntile_high].nlat = nlat; TRS_HIGH[ntile_high].ilng = ilng; TRS_HIGH[ntile_high].nlng = nlng; TRS_HIGH[ntile_high].hemisphere = hemisphere; TRS_HIGH[ntile_high].level = level; TRS_HIGH[ntile_high].RANGE = RANGE; TRS_HIGH[ntile_high].Tex = Tex; ntile_high++; } if( CFG->bTerrainDetails_Urban && (td->flags & CITY_CTYPE) && min_dist < CFG->TerrainDetails_Urban_maxdist ) { if( ntile_city == size_city ) ExpandTRSBuffer( TRS_CITY, size_city ); TRS_CITY[ntile_city].mWorld = mWorld; TRS_CITY[ntile_city].ilat = ilat; TRS_CITY[ntile_city].nlat = nlat; TRS_CITY[ntile_city].ilng = ilng; TRS_CITY[ntile_city].nlng = nlng; TRS_CITY[ntile_city].hemisphere = hemisphere; TRS_CITY[ntile_city].level = level; TRS_CITY[ntile_city].RANGE = RANGE; TRS_CITY[ntile_city].Tex = Tex; ntile_city++; } } } void DetailsManager::ExpandTRSBuffer( TILERENDERSPEC *TRS, UINT &size ) { TILERENDERSPEC *trs = new TILERENDERSPEC [size + 32]; memcpy( trs, TRS, size ); delete [ ] TRS; TRS = trs; size += 32; } void DetailsManager::TileWorldMatrix( UINT8 hemisphere, UINT ilat, UINT nlat, UINT ilng, UINT nlng, D3DXMATRIX &mWorld ) { //returns tile-specific world matrix // void MatrixRotY1( D3DXMATRIX *out, float angle ); D3DXMATRIX rtile, wtrans; double lng = PI2*(double)ilng/(double)nlng + PI; MatrixRotY1( &rtile, (float)lng ); if( nlat > 8 ) { double lat = PI05*(double)ilat/(double)nlat; double s = RP.objsize; double dx = s*cos(lng)*cos(lat); double dy = s*sin(lat); double dz = s*sin(lng)*cos(lat); RP.mWorld_tmp._41 = (float)(dx*RP.grot.m11 + dy*RP.grot.m12 + dz*RP.grot.m13 + RP.cpos.x); RP.mWorld_tmp._42 = (float)(dx*RP.grot.m21 + dy*RP.grot.m22 + dz*RP.grot.m23 + RP.cpos.y); RP.mWorld_tmp._43 = (float)(dx*RP.grot.m31 + dy*RP.grot.m32 + dz*RP.grot.m33 + RP.cpos.z); D3DXMatrixMultiply( &mWorld, &rtile, &RP.mWorld_tmp ); } else D3DXMatrixMultiply( &mWorld, &rtile, &RP.mWorld ); } /* void MatrixRotY( D3DXMATRIX *out, float angle ) { double sinr = sin( angle ), cosr = cos( angle ); memset( out, 0, 64 ); out->_11 = out->_33 = (float)cosr; out->_31 = -( out->_13 = (float)sinr ); out->_22 = out->_44 = 1.0f; }*/ void DetailsManager::InitResources() { char fname[256], cpath[256]; D3D10_SHADER_MACRO macro; std::vector<D3D10_SHADER_MACRO> SM; HRESULT hr; ID3DBlob *SBlob = NULL, *EBlob = NULL; ID3D11Texture2D *tex2; D3D11_TEXTURE2D_DESC tdesc; D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc; //============================================= // Average/High vegetation/rocks //============================================= if( CFG->bTerrainDetails_Average ) { BYTE *data; std::vector<BYTE*> TEX; UINT twidth[2] = { 0 }, theight[2] = { 0 }, nmip = 0; UINT cnt = 0; for( int j = 0; j < CFG->CTP.size(); j++ ) { for( int i = 0; i < 4; i++ ) { sprintf( fname, "%s%s_%d_high_%d.dds", TERRAIN_TEXTURE_FOLDER, term->objname, j, i ); if( gc->TexturePath( fname, cpath ) && ReadTexture( &data, cpath, twidth[0], theight[0] ) ) { if( !AddTexture( TEX, data, twidth, theight, nmip ) ) break; else { CFG->CTP[j].midx = TEX.size() - i - 1; cnt++; } } } } //texture array if( TEX.size() ) { //macro. /* macro.Name = "LOW_DETAILS_MICROTEX_MULT"; sprintf( line[13], "%0.1ff", CFG->TerrainLowDetailsMicroTex_mult ); macro.Definition = line[13]; SM.push_back( macro );*/ memset( &tdesc, 0, sizeof(tdesc) ); tdesc.ArraySize = TEX.size(); tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; tdesc.CPUAccessFlags = 0; tdesc.Format = DXGI_FORMAT_BC3_UNORM; tdesc.Height = twidth[0]; tdesc.Width = theight[0]; tdesc.MipLevels = nmip; tdesc.MiscFlags = 0; tdesc.SampleDesc.Count = 1; tdesc.Usage = D3D11_USAGE_DEFAULT; if( S_OK == Dev->CreateTexture2D( &tdesc, NULL, &tex2 ) ) { memset( &srvdesc, 0, sizeof(srvdesc) ); srvdesc.Format = DXGI_FORMAT_BC3_UNORM; srvdesc.Texture2DArray.ArraySize = TEX.size(); srvdesc.Texture2DArray.FirstArraySlice = 0; srvdesc.Texture2DArray.MipLevels = nmip; srvdesc.Texture2DArray.MostDetailedMip = 0; srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; if( S_OK == Dev->CreateShaderResourceView( tex2, &srvdesc, &aTextures_AverageHigh ) ) { for( int j = 0; j < TEX.size(); j++ ) iCtx->UpdateSubresource( tex2, j*nmip, NULL, TEX[j], twidth[0]/2, 0 ); D3DX11FilterTexture( iCtx, tex2, 0, D3DX11_FILTER_LINEAR ); } REL( tex2 ); } //shaders for average detalization (billboards): ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\GS_Details_AverageHigh.cfg", &SM[0], NULL, "GS_Average", gs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateGeometryShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &GS_Average ) ); REL( SBlob ); REL( EBlob ); ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\PS_Details_AverageHigh.cfg", &SM[0], NULL, "PS_Average", ps_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreatePixelShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &PS_Average ) ); REL( SBlob ); REL( EBlob ); //shaders for high detalization (ultra-lowpoly meshes) if( CFG->bTerrainDetails_High ) { ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\GS_Details_AverageHigh.cfg", &SM[0], NULL, "GS_High", gs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateGeometryShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &GS_High ) ); REL( SBlob ); REL( EBlob ); ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\PS_Details_AverageHigh.cfg", &SM[0], NULL, "PS_High", ps_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreatePixelShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &PS_High ) ); REL( SBlob ); REL( EBlob ); } } } /* //cities if( CFG->bTerrainDetails_Urban ) { //meshes with number of groups == number of buildings UINT idx = 0; FILE *file; ID3D11Buffer *VB; ID3D11Texture2D *tex; ID3D11ShaderResourceView *SRV; UINT nmip = 0; std::vector<BYTE*> TEX; UINT twidth[2] = { 0 }, theight[2] = { 0 }; sprintf( fname, "%s%s_city_0.msh", "Meshes\\Terrain\\", term->objname ); while( gc->TexturePath( fname, cpath ) && (file = fopen( cpath, "rb" )) ) { fclose( file ); sprintf( fname, "%s%s_city_%d", "Terrain\\", term->objname, idx ); MESHHANDLE hMesh = oapiLoadMesh( fname ); UINT ngrp = oapiMeshGroupCount( hMesh ); UINT nvtx = 0; TRIANGLE_VERTEX *data; for( int j = 0; j < ngrp; j++ ) { MESHGROUPEX *grp = oapiMeshGroupEx( hMesh, j ); VERTEX_URBAN *ndata = new VERTEX_URBAN [nvtx + grp->nVtx]; memset( ndata, 0, 20*(nvtx + grp->nVtx) ); memcpy( ndata, data, nvtx*20 ); delete [ ] data; data = ndata; ndata = data + nvtx; MATERIAL *mat = oapiMeshMaterial( hMesh, grp->MtrlIdx ); for( int i = 0; i < grp->nVtx; i++ ) { ndata[i].PosL = D3DXVECTOR3( grp->Vtx[i].x, grp->Vtx[i].y, grp->Vtx[i].z ); ndata[i].spower = mat->power; ndata[i].tidx = grp->TexIdx; BYTE *tdata; sprintf( fname, "%s%s_city_%d_group_%d.dds", TERRAIN_TEXTURE_FOLDER, term->objname, j, i ); if( gc->TexturePath( fname, cpath ) && ReadTexture( &tdata, cpath, twidth[0], theight[0] ) ) { if( !AddTextureUrban( TEX, tdata, twidth, theight, nmip ) ) { for( int i = 0; i < TEX.size(); i++ ) delete [ ] TEX[i]; TEX.clear(); goto skip; } } } nvtx++; } D3D11_BUFFER_DESC bdesc; D3D11_SUBRESOURCE_DATA sdata; //triangle vertex buffer (=> geometry shader) memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bdesc.ByteWidth = nvtx*20; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = 0; bdesc.StructureByteStride = 0; bdesc.Usage = D3D11_USAGE_IMMUTABLE; memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = data; Dev->CreateBuffer( &bdesc, NULL, &VB ); VB_Urban.push_back( VB ); //texture arrays (one per mesh) memset( &tdesc, 0, sizeof(tdesc) ); tdesc.ArraySize = TEX.size(); tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; tdesc.CPUAccessFlags = 0; tdesc.Format = DXGI_FORMAT_BC1_UNORM; tdesc.Height = theight[0]; tdesc.MipLevels = nmip; tdesc.MiscFlags = 0; tdesc.SampleDesc.Count = 1; tdesc.Usage = D3D11_USAGE_IMMUTABLE; tdesc.Width = twidth[0]; Dev->CreateTexture2D( &tdesc, NULL, &tex ); memset( &srvdesc, 0, sizeof(srvdesc) ); srvdesc.Format = DXGI_FORMAT_BC1_UNORM; srvdesc.Texture2DArray.ArraySize = TEX.size(); srvdesc.Texture2DArray.FirstArraySlice = 0; srvdesc.Texture2DArray.MipLevels = nmip; srvdesc.Texture2DArray.MostDetailedMip = 0; srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; Dev->CreateShaderResourceView( tex, &srvdesc, &SRV ); for( int i = 0; i < oapiMeshTextureCount( hMesh ); i++ ) iCtx->UpdateSubresource( tex, i*nmip, NULL, TEX[i], 0, 0 ); D3DX11FilterTexture( iCtx, tex, 0, D3DX11_FILTER_LINEAR ); aTextures_Urban.push_back( SRV ); for( int i = 0; i < TEX.size(); i++ ) delete [ ] TEX[i]; TEX.clear(); oapiDeleteMesh( hMesh ); idx++; sprintf( fname, "%s%s_city_%d.msh", "Meshes\\", term->objname, idx ); } //shaders: ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\GS_Urban.cfg", &SM[0], NULL, "GS_Urban", gs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateGeometryShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &GS_Urban ) ); REL( SBlob ); REL( EBlob ); ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\PS_Urban.cfg", &SM[0], NULL, "PS_Urban", ps_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreatePixelShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &PS_Urban ) ); REL( SBlob ); REL( EBlob ); }*/ skip: ; } bool DetailsManager::AddTexture( std::vector<BYTE*> &TEX, BYTE *data, UINT *twidth, UINT *theight, UINT &nmip ) { D3D11_SUBRESOURCE_DATA sdata; //check dimesions if( twidth[0] != twidth[1] || theight[0] != theight[1] ) { if( !twidth[1] && !theight[1] ) { //first array element twidth[1] = twidth[0]; theight[1] = theight[0]; } else { oapiWriteLog( "Error: dimensions of microtextures must be equal to each other." ); for( int j = 0; j < CFG->CTP.size(); j++ ) CFG->CTP[j].flags = 0; for( int j = 0; j < TEX.size(); j++ ) delete [ ] TEX[j]; TEX.clear(); return false; } } TEX.push_back( data ); if( !nmip ) GetMipMapNumber( twidth[0], theight[0], nmip ); return true; } bool DetailsManager::AddTextureUrban( std::vector<BYTE*> &TEX, BYTE *data, UINT *twidth, UINT *theight, UINT &nmip ) { D3D11_SUBRESOURCE_DATA sdata; //check dimesions if( twidth[0] != twidth[1] || theight[0] != theight[1] ) { if( !twidth[1] && !theight[1] ) { //first array element twidth[1] = twidth[0]; theight[1] = theight[0]; } else { oapiWriteLog( "Error: dimensions of microtextures must be equal to each other." ); for( int j = 0; j < CFG->CTP.size(); j++ ) CFG->CTP[j].flags = 0; for( int j = 0; j < TEX.size(); j++ ) delete [ ] TEX[j]; TEX.clear(); return false; } } TEX.push_back( data ); if( !nmip ) GetMipMapNumber( twidth[0], theight[0], nmip ); return true; } /* UINT DetailsManager::Stride_POINTVERTEX = 52, DetailsManager::Stride_ArgBuffer = 20, DetailsManager::Stride_MESHVERTEX = 44, DetailsManager::Stride_INSTANCEDATA = 24; ID3D11InputLayout *DetailsManager::IL_POINTVERTEX = NULL, *DetailsManager::IL_MESHVERTEX = NULL; ID3D11VertexShader *DetailsManager::VS_Average = NULL, *DetailsManager::VS_High = NULL; ID3D11Buffer *DetailsManager::CB_AtmParams = NULL, *DetailsManager::CB_PlanetShadowParams = NULL, *DetailsManager::CB_LightingHigh = NULL, *DetailsManager::VB_Average = NULL, *DetailsManager::ArgumentBuffer = NULL, *DetailsManager::VB_InstanceData = NULL, *DetailsManager::VSCB_Average = NULL, *DetailsManager::CSCB_High = NULL; ID3D11Resource *DetailsManager::aHeightMaps4, *DetailsManager::aLCoverMaps4, *DetailsManager::aTextures4; ID3D11ShaderResourceView *DetailsManager::VB_AverageSRV = NULL, *DetailsManager::LCoverDistortionSRV = NULL, *DetailsManager::aTextures4SRV = NULL, *DetailsManager::aLCoverMaps4SRV = NULL, *DetailsManager::aHeightMaps4SRV = NULL; ID3D11DepthStencilState *DetailsManager::DSS_Details = NULL; ID3D11SamplerState *DetailsManager::SS_TileTexture = NULL, *DetailsManager::SS_BillBoardTexture = NULL, *DetailsManager::SS_MeshTexture = NULL; ID3D11UnorderedAccessView *DetailsManager::ArgumentBufferUAV = NULL, *DetailsManager::InstanceDataUAV = NULL; void DetailsManager::GlobalInit( ID3D11Buffer *_CB_AtmParams, ID3D11Buffer *_CB_PlanetShadowParams ) { DWORD j; HRESULT hr; ID3DBlob *SBlob = NULL, *EBlob = NULL; CB_AtmParams = _CB_AtmParams; CB_PlanetShadowParams = _CB_PlanetShadowParams; CB_CTypePatams = NULL; D3D11_INPUT_ELEMENT_DESC iedesc[ ] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 2, DXGI_FORMAT_R32_FLOAT, 0, 36, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\VS_Details.fx", NULL, NULL, "VS_Average", vs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateInputLayout( iedesc, 6, SBlob->GetBufferPointer(), SBlob->GetBufferSize(), &IL_POINTVERTEX ) ); HR( Dev->CreateVertexShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &VS_Average ) ); REL( SBlob ); REL( EBlob ); D3D11_BUFFER_DESC bdesc; D3D11_SUBRESOURCE_DATA sdata; D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc; //======================================================= // Vertex buffer of randomly positioned points //======================================================= memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_SHADER_RESOURCE; bdesc.ByteWidth = Stride_POINTVERTEX*NPOINT; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; bdesc.StructureByteStride = Stride_POINTVERTEX; bdesc.Usage = D3D11_USAGE_DEFAULT; double lat, lng, maxlat = PI05/512.0, maxlng = PI2/2048.0; POINTVERTEX vtx, *VTX = new POINTVERTEX [NPOINT]; for( UINT j = 0; j < NPOINT; j++ ) { lat = maxlat*(double(rand())/double(RAND_MAX)); lng = maxlng*(double(rand())/double(RAND_MAX)); vtx.PosL.x = 1000.0*cos(lng)*cos(lat); vtx.PosL.y = 1000.0*sin(lat); vtx.PosL.z = 1000.0*sin(lng)*cos(lat); D3DXVec3Normalize( &vtx.NormL, &vtx.PosL ); vtx.TangL.x = -1.0*sin(lng)*cos(lat); vtx.TangL.y = cos(lat); vtx.TangL.z = cos(lng)*cos(lat); vtx.TCrd = D3DXVECTOR2( lng/maxlng, lat/maxlat ); vtx.dist = 0.0;//random ? vtx.rnd = double(rand())/double(RAND_MAX); VTX[j] = vtx; } memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = VTX; Dev->CreateBuffer( &bdesc, &sdata, &VB_Average ); delete [ ] VTX; //samplers and dss } void DetailsManager::GlobalExit() { REL( IL_POINTVERTEX ); REL( IL_MESHVERTEX ); REL( VS_Average ); REL( VS_High ); REL( CB_LightingHigh ); REL( VB_Average ); REL( ArgumentBuffer ); REL( VB_InstanceData ); REL( VSCB_Average ); REL( VB_AverageSRV ); REL( LCoverDistortionSRV ); REL( ArgumentBufferUAV ); REL( InstanceDataUAV ); REL( SS_TileTexture ); REL( SS_BillBoardTexture ); REL( SS_MeshTexture ); REL( DSS_Details ); } /* DetailsManager::DetailsManager( TerrainManager *_term, PlanetaryConfig *_CFG ) { GS_Average = NULL; PS_Average = NULL; CS_High = NULL; PS_High = NULL; VB_MeshHigh = IB_MeshHigh = NULL; CB_CoverTypeParams = NULL; CB_MeshParams = NULL; MeshParamsSRV = NULL; aTexturesAverage = NULL; aTexturesHigh = NULL; term = _term; CFG = _CFG; } DetailsManager::~DetailsManager() { REL( GS_Average ); REL( PS_Average ); REL( CS_High ); REL( PS_High ); REL( MeshParamsSRV ); REL( aTexturesAverage ); REL( aTexturesHigh ); REL( VB_MeshHigh ); REL( IB_MeshHigh ); REL( CB_CoverTypeParams ); REL( CB_MeshParams ); } void DetailsManager::Render( TILERENDERSPEC *TRS, UINT ntile ) { if( !CFG->bTerrainDetails_Average ) return; UINT j = 0; const UINT VBOffset = 0; //=================================================== // Average //=================================================== //... iCtx->UpdateSubresource( cb_D3DXVECTOR4, 0, NULL, 0, 0, 0 );//! iCtx->UpdateSubresource( cb_D3DXMATRIX_x1, 0, NULL, SC->GetVP(), 0, 0 ); iCtx->IASetInputLayout( IL_POINTVERTEX ); iCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST ); iCtx->IASetVertexBuffers( 0, 1, &VB_Average, &Stride_POINTVERTEX, &VBOffset ); iCtx->VSSetShader( VS_Average, NULL, 0 ); iCtx->VSSetSamplers( 0, 1, &SS_TileTexture ); iCtx->VSSetConstantBuffers( 0, 1, &VSCB_Average ); iCtx->GSSetShader( GS_Average, NULL, 0 ); iCtx->GSSetSamplers( 0, 1, &SS_TileTexture ); // if( CFG->DistortCoords ) iCtx->GSSetShaderResources( 1, 1, &LCoverDistortionSRV ); ??? iCtx->GSSetConstantBuffers( 0, 1, &cb_D3DXMATRIX_x1 ); iCtx->GSSetConstantBuffers( 1, 1, &CB_CoverTypeParams ); if( CFG->AtmosphereType == BASIC_ATMOSPHERE ) iCtx->GSSetConstantBuffers( 2, 1, &CB_AtmParams ); iCtx->PSSetShader( PS_Average, NULL, 0 ); iCtx->PSSetSamplers( 0, 1, &SS_TileTexture ); iCtx->PSSetSamplers( 1, 1, &SS_BillBoardTexture ); iCtx->PSSetConstantBuffers( 0, 1, &cb_D3DXVECTOR4 ); iCtx->PSSetConstantBuffers( 1, 1, &CB_CoverTypeParams ); iCtx->PSSetShaderResources( 1, 1, &aTexturesAverage ); iCtx->OMSetBlendState( BS_SrcAlpha, D3DXVECTOR4( 1, 1, 1, 1 ), 0xFFFFFFFF ); iCtx->OMSetDepthStencilState( DSS_Details, 0 ); iCtx->RSSetState( RS_CullNone_Solid ); VSCB_per_tile vbuf; for( j = 0; j < ntile; j++ ) { vbuf.W = TRS[j].mWorld; vbuf.flags = 0; vbuf.TexOff[0] = TRS[j].RANGE.range_tex.tumax - TRS[j].RANGE.range_tex.tumin; vbuf.TexOff[1] = TRS[j].RANGE.range_tex.tumin; vbuf.TexOff[2] = TRS[j].RANGE.range_tex.tvmax - TRS[j].RANGE.range_tex.tvmin; vbuf.TexOff[3] = TRS[j].RANGE.range_tex.tvmin; if( TRS[j].Tex.htex ) { iCtx->VSSetShaderResources( 0, 1, &TRS[j].Tex.htex ); vbuf.flags = 2; vbuf.TexOff_height[0] = TRS[j].RANGE.range_height.tumax - TRS[j].RANGE.range_height.tumin; vbuf.TexOff_height[1] = TRS[j].RANGE.range_height.tumin; vbuf.TexOff_height[2] = TRS[j].RANGE.range_height.tvmax - TRS[j].RANGE.range_height.tvmin; vbuf.TexOff_height[3] = TRS[j].RANGE.range_height.tvmin; } if( TRS[j].Tex.ctex ) { iCtx->GSSetShaderResources( 0, 1, &TRS[j].Tex.ctex ); vbuf.TexOff_lcover[0] = TRS[j].RANGE.range_lcover.tumax - TRS[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[1] = TRS[j].RANGE.range_lcover.tumin; vbuf.TexOff_lcover[2] = TRS[j].RANGE.range_lcover.tvmax - TRS[j].RANGE.range_lcover.tvmin; vbuf.TexOff_lcover[3] = TRS[j].RANGE.range_lcover.tvmin; iCtx->UpdateSubresource( VSCB_Average, 0, NULL, &vbuf, 0, 0 ); iCtx->Draw( NPOINT, 0 ); } } iCtx->GSSetShader( NULL, NULL, 0 ); //=================================================== // High details - computing indirect args //=================================================== if( !CFG->bTerrainDetails_High ) return; /* //fill texture arrays... static TILERENDERSPEC *TRS4[4] = { NULL }, *TRS4_old[4] = { NULL }; static double td_adist[4] = { 0.0 }; memset( TRS4, 0, sizeof(TILERENDERSPEC*)*4 ); memset( td_adist, 0, 8*4 ); double cam_lng, cam_lat, cam_rad, tile_lng, tile_lat, tile_rad; oapiGlobalToEqu( term->obj, SC->CamPos, &cam_lng, &cam_lat, &cam_rad ); //find 4 nearest tiles: for( UINT j = 0; j < ntile; j++ ) { tile_lng = PI2/double(TRS[j].nlng); tile_lng = PI2*(double(TRS[j].ilng)/double(TRS[j].nlng)) + tile_lng/2.0; tile_lat = PI05/double(TRS[j].nlat); tile_lat = PI05*(double(TRS[j].ilat)/double(TRS[j].nlat)) + tile_lat/2.0; double dlng = abs( tile_lng - cam_lng ); double dlat = abs( tile_lat - cam_lat ); double adist = sqrt( dlng*dlng + dlat*dlat ); if( adist > td_adist[0] ) { TRS4[0] = &TRS[j]; td_adist[0] = adist; } else if( adist > td_adist[1] ) { TRS4[1] = &TRS[j]; td_adist[1] = adist; } else if( adist > td_adist[2] ) { TRS4[2] = &TRS[j]; td_adist[2] = adist; } else if( adist > td_adist[3] ) { TRS4[3] = &TRS[j]; td_adist[3] = adist; } } //copy texture and world matrix data: CSCB_High_per_frame cbuf; cbuf.V = *SC->GetV(); float ap = (float)SC->GetCamAperture(); cbuf.h = tan( ap ); cbuf.dfr = 0.0015f*cbuf.h; cbuf.hf = 1.0f/cos( ap ); float as = cfg->Aspect; cbuf.w = cbuf.h*as; cbuf.wf = cbuf.hf*as; cbuf.ntile = 4; ID3D11Resource *res; for( UINT j = 0; j < 4; j++ ) { if( TRS4[j] != TRS4_old[j] ) { cbuf.W[j] = TRS4[j]->mWorld; TRS4[j]->Tex.htex->GetResource( &res ); iCtx->CopySubresourceRegion( aHeightMaps4, j, 0, 0, 0, res, 0, NULL ); TRS4[j]->Tex.ctex->GetResource( &res ); iCtx->CopySubresourceRegion( aLCoverMaps4, j, 0, 0, 0, res, 0, NULL ); TRS4[j]->Tex.tex->GetResource( &res ); iCtx->CopySubresourceRegion( aTextures4, j, 0, 0, 0, res, 0, NULL ); } } memcpy( TRS4_old, TRS4, sizeof(TILERENDERSPEC*)*4 ); iCtx->UpdateSubresource( CSCB_High, 0, NULL, &cbuf, 0, 0 ); const UINT UAVInitCount = 0; iCtx->CSSetShader( CS_High, NULL, 0 ); iCtx->CSSetConstantBuffers( 0, 1, &CSCB_High ); iCtx->CSSetConstantBuffers( 1, 1, &CB_MeshParams ); iCtx->CSSetSamplers( 0, 1, &SS_TileTexture ); iCtx->CSSetShaderResources( 0, 1, &aHeightMaps4SRV ); iCtx->CSSetShaderResources( 1, 1, &aLCoverMaps4SRV ); iCtx->CSSetShaderResources( 2, 1, &VB_AverageSRV ); iCtx->CSSetUnorderedAccessViews( 0, 1, &ArgumentBufferUAV, &UAVInitCount ); iCtx->CSSetUnorderedAccessViews( 1, 1, &InstanceDataUAV, &UAVInitCount ); iCtx->Dispatch( 1, NPOINT/64, 1 ); iCtx->CSSetShader( NULL, NULL, 0 ); //=================================================== // High details - indirect instanced draw //=================================================== //... //... iCtx->UpdateSubresource( CB_LightingHigh, 0, NULL, 0, 0, 0 );//! iCtx->UpdateSubresource( cb_D3DXMATRIX_x1, 0, NULL, SC->GetVP(), 0, 0 ); iCtx->UpdateSubresource( cb_D3DXVECTOR4, 0, NULL, 0, 0, 0 );//! iCtx->IASetInputLayout( IL_MESHVERTEX ); iCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); iCtx->IASetVertexBuffers( 0, 1, &VB_MeshHigh, &Stride_MESHVERTEX, &VBOffset ); iCtx->IASetVertexBuffers( 1, 1, &VB_InstanceData, &Stride_INSTANCEDATA, &VBOffset ); iCtx->VSSetShader( VS_High, NULL, 0 ); iCtx->VSSetConstantBuffers( 0, 1, &cb_D3DXMATRIX_x1 ); iCtx->PSSetShader( PS_High, NULL, 0 ); iCtx->PSSetConstantBuffers( 0, 1, &cb_D3DXVECTOR4 ); iCtx->PSSetConstantBuffers( 1, 1, &CB_LightingHigh ); iCtx->PSSetConstantBuffers( 2, 1, &CB_MeshParams ); iCtx->PSSetShaderResources( 0, 1, &aTexturesHigh ); iCtx->PSSetShaderResources( 1, 1, &aTextures4SRV ); iCtx->PSSetSamplers( 0, 1, &SS_MeshTexture ); iCtx->PSSetSamplers( 1, 1, &SS_TileTexture ); iCtx->OMSetBlendState( BS_SrcAlpha, D3DXVECTOR4( 1, 1, 1, 1 ), 0xFFFFFFFF ); iCtx->OMSetDepthStencilState( DSS_Details, 0 ); iCtx->RSSetState( RS_CullNone_Solid ); for( UINT j = 0; j < MAX_INDIRECT_TYPE; j++ ) iCtx->DrawIndexedInstancedIndirect( ArgumentBuffer, j*Stride_ArgBuffer );*/ //} /* Earth_micro_disp_flat.dds A8 Earth_micro_disp_coarse.dds ` A8 Earth_micro_flat.dds dxt1 Earth_micro_coarse.dds dxt1 Earth_micro_norm_flat.dds dxt1 Earth_micro_norm_coarse.dds dxt1 from: Earth_low_0.dds dxt1 Earth_low_0_norm.dds Earth_average_0.dds dxt5 Earth_average_0_norm.dds Earth_high_0.dds dxt5 Earth_high_0.msh to: Earth_low_10.dds dxt1 Earth_low_0_norm.dds Earth_average_10.dds dxt5 Earth_average_0_norm.dds Earth_high_10.dds dxt5 Earth_high_10.msh */ /* if( !CFG->bTerrainDetails_Average ) return; char fname[256], cpath[256]; BYTE *data = NULL; UINT twidth[2] = { 0 }, theight[2] = { 0 }, nmip = 0; D3D11_TEXTURE2D_DESC tdesc; D3D11_SUBRESOURCE_DATA sdata; std::vector<D3D11_SUBRESOURCE_DATA> SRDATA; std::vector<BYTE*> TEX; D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc; ID3D11Texture2D *tex; D3D11_BUFFER_DESC bdesc; std::vector<D3D10_SHADER_MACRO> SM; D3D10_SHADER_MACRO macro; //============================== // Average - Diffuse //============================== /* for( int j = 0; j < CFG->CTP.size(); j++ ) { sprintf( fname, "%s%s_average_%d.dds", TERRAIN_TEXTURE_FOLDER, term->objname, j ); if( !gc->TexturePath( fname, cpath ) || !ReadTexture( &data, cpath, twidth[0], theight[0] ) ) continue; else if( !AddTexture( TEX, data, twidth, theight, nmip ) ) goto skip; CFG->CTP[j].tidx = j; } for( int j = 0; j < CFG->CTP.size(); j++ ) { sprintf( fname, "%s%s_average_%d_norm.dds", TERRAIN_TEXTURE_FOLDER, term->objname, j ); if( !gc->TexturePath( fname, cpath ) || !ReadTexture( &data, cpath, twidth[0], theight[0] ) ) continue; else if( !AddTexture( TEX, data, twidth, theight, nmip ) ) goto skip; CFG->CTP[j].nidx = j; }*/ /* if( TEX.size() ) { memset( &tdesc, 0, sizeof(tdesc) ); tdesc.ArraySize = TEX.size(); tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; tdesc.CPUAccessFlags = 0; tdesc.Format = DXGI_FORMAT_BC3_UNORM; tdesc.Height = theight[0]; tdesc.Width = twidth[0]; tdesc.MipLevels = nmip; tdesc.MiscFlags = 0; tdesc.SampleDesc.Count = 1; tdesc.Usage = D3D11_USAGE_DEFAULT; if( S_OK == Dev->CreateTexture2D( &tdesc, NULL, &tex ) ) { memset( &srvdesc, 0, sizeof(srvdesc) ); srvdesc.Format = DXGI_FORMAT_BC3_UNORM; srvdesc.Texture2DArray.ArraySize = TEX.size(); srvdesc.Texture2DArray.FirstArraySlice = 0; srvdesc.Texture2DArray.MipLevels = nmip; srvdesc.Texture2DArray.MostDetailedMip = 0; srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; if( S_OK == Dev->CreateShaderResourceView( tex, &srvdesc, &aTexturesAverage ) ) { for( int j = 0; j < TEX.size(); j++ ) iCtx->UpdateSubresource( tex, j*nmip, NULL, TEX[j], twidth[0], 0 ); D3DX11FilterTexture( iCtx, tex, 0, D3DX11_FILTER_LINEAR ); } } for( int j = 0; j < TEX.size(); j++ ) delete [ ] TEX[j]; TEX.clear(); } skip: switch( CFG->AtmosphereType ) { case NO_ATMOSPHERE: macro.Name = "NO_ATMOSPHERE"; break; case BASIC_ATMOSPHERE: macro.Name = "BASIC_ATMOSPHERE"; break; case PAS_ATMOSPHERE: macro.Name = "PAS_ATMOSPHERE"; break; } macro.Definition = "1"; SM.push_back( macro ); //terrain shadows: if( CFG->bTerrainShadows ) { macro.Name = "TERRAIN_SHADOWS"; macro.Definition = "1"; SM.push_back( macro ); } //planetary shadows: if( CFG->bPlanetaryShadows ) { macro.Name = "PLANETARY_SHADOWS"; macro.Definition = "1"; SM.push_back( macro ); } //ring shadows: if( CFG->bRingShadows ) { macro.Name = "RING_SHADOWS"; macro.Definition = "1"; SM.push_back( macro ); } char line[32]; macro.Name = "MAXCTYPE"; sprintf( line, "%d", CFG->CTP.size() ); macro.Definition = line; SM.push_back( macro ); macro.Name = NULL; macro.Definition = NULL; SM.push_back( macro ); HRESULT hr; ID3DBlob *SBlob = NULL, *EBlob = NULL; ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\GS_Details_Average.cfg", &SM[0], NULL, "GS_Average", gs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreateGeometryShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &GS_Average ) ); REL( SBlob ); REL( EBlob ); ::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\PS_Details_Average.cfg", &SM[0], NULL, "PS_Average", ps_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr ); ShowShaderCompilationError( hr, EBlob ); HR( Dev->CreatePixelShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &PS_Average ) ); REL( SBlob ); REL( EBlob ); memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bdesc.ByteWidth = CFG->CTP.size()*32; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = 0; bdesc.StructureByteStride = 0; bdesc.Usage = D3D11_USAGE_DEFAULT; memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = &CFG->CTP[0]; Dev->CreateBuffer( &bdesc, &sdata, &CB_CoverTypeParams ); //========================================== // High //========================================== if( !CFG->bTerrainDetails_High ) return;*/ /* //meshes: MESHPARAM mp; std::vector<MESHHANDLE> MSH; std::vector<MESHPARAM> MP; std::vector<MESHGROUPEX*> MGEx; UINT nmsh = 0, ngrp = 0, sidx = 0, svtx = 0; MESHHANDLE hMesh = NULL; dim = ntex = j = 0; while( hMesh ) { sprintf( fname, "Terrain\\%s_high_%d", term->objname, nmsh ); hMesh = oapiLoadMesh( fname ); ngrp = oapiMeshGroupCount( hMesh ); sprintf( fname, "Terrain\\%s_high_%d.dds", term->objname, nmsh ); if( ngrp == 1 && gc->TexturePath( fname, cpath ) && ReadTexture( &data, fname, dim ) ) { MESHGROUPEX *grp = oapiMeshGroupEx( hMesh, 0 ); MGEx.push_back( grp ); mp.nidx = grp->nIdx; mp.nvtx = grp->nVtx; mp.sidx = sidx; mp.svtx = svtx; sidx += grp->nIdx; svtx += grp->nVtx; MP.push_back( mp ); MSH.push_back( hMesh ); //diffuse texture SR data: TEX.push_back( data ); sdata.pSysMem = data; sdata.SysMemPitch = dim/2; SRDATA.push_back( sdata ); if( nmsh < CFG->CTP.size() ) CFG->CTP[nmsh].hidx = nmsh; if( SRDATA.size() == 1 ) nmip = GetTextureMipMapCount( dim ); memset( &sdata, 0, sizeof(sdata) ); for( j = 0; j < nmip; j++ ) SRDATA.push_back( sdata ); sprintf( fname, "Terrain\\%s_high_%d_norm.dds", term->objname, nmsh ); if( gc->TexturePath( fname, cpath ) && ReadTexture( &data, fname, dim ) ) { NTEX.push_back( data ); } ntex++; } else hMesh = NULL; nmsh++; } if( MSH.size() ) { //mesh vertex/index data: NTVERTEX *Vtx = new NTVERTEX [svtx], *vtx; vtx = Vtx; for( j = 0; j < nmsh; j++ ) { memcpy( vtx, MGEx[j]->Vtx, MP[j].nvtx ); vtx += MP[j].nvtx; } WORD *Idx = new WORD [sidx], *idx; idx = Idx; for( j = 0; j < nmsh; j++ ) { memcpy( idx, MGEx[j]->Idx, MP[j].nidx ); idx += MP[j].nidx; } memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bdesc.ByteWidth = 32*svtx; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = 0; bdesc.StructureByteStride = 0; bdesc.Usage = D3D11_USAGE_IMMUTABLE; memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = Vtx; Dev->CreateBuffer( &bdesc, &sdata, &VB_MeshHigh ); memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bdesc.ByteWidth = 2*sidx; bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = 0; bdesc.StructureByteStride = 0; bdesc.Usage = D3D11_USAGE_IMMUTABLE; memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = Idx; Dev->CreateBuffer( &bdesc, &sdata, &IB_MeshHigh ); for( j = 0; j < nmsh; j++ ) oapiDeleteMesh( MSH[j] ); MGEx.clear(); MSH.clear(); //mesh params buffer: memset( &bdesc, 0, sizeof(bdesc) ); bdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; bdesc.ByteWidth = 16*MP.size(); bdesc.CPUAccessFlags = 0; bdesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; bdesc.StructureByteStride = 16; bdesc.Usage = D3D11_USAGE_IMMUTABLE; memset( &sdata, 0, sizeof(sdata) ); sdata.pSysMem = &MP[0]; // Dev->CreateBuffer( &bdesc, &sdata, &MeshParams ); memset( &srvdesc, 0, sizeof(srvdesc) ); srvdesc.Format = DXGI_FORMAT_UNKNOWN; srvdesc.Buffer.ElementOffset = 0; srvdesc.Buffer.ElementWidth = 16; srvdesc.Buffer.FirstElement = 0; srvdesc.Buffer.NumElements = MP.size(); // Dev->CreateShaderResourceView( MeshParams, &srvdesc, &MeshParamsSRV ); MP.clear(); //textures: //add normal maps if they were loaded correctly: if( TEX.size() == NTEX.size() ) { for( j = 0; j < NTEX.size(); j++ ) { sdata.pSysMem = NTEX[j]; sdata.SysMemPitch = dim/2; SRDATA.push_back( sdata ); memset( &sdata, 0, sizeof(sdata) ); for( j = 0; j < nmip; j++ ) SRDATA.push_back( sdata ); ntex++; } } memset( &tdesc, 0, sizeof(tdesc) ); tdesc.ArraySize = ntex; tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; tdesc.CPUAccessFlags = 0; tdesc.Format = DXGI_FORMAT_BC3_UNORM; tdesc.Height = dim; tdesc.MipLevels = nmip; tdesc.MiscFlags = 0; tdesc.SampleDesc.Count = 1; tdesc.Usage = D3D11_USAGE_IMMUTABLE; tdesc.Width = dim; Dev->CreateTexture2D( &tdesc, &SRDATA[0], &tex ); memset( &srvdesc, 0, sizeof(srvdesc) ); srvdesc.Format = DXGI_FORMAT_BC3_UNORM; srvdesc.Texture2DArray.ArraySize = TEX.size() + NTEX.size(); srvdesc.Texture2DArray.FirstArraySlice = 0; srvdesc.Texture2DArray.MipLevels = nmip; srvdesc.Texture2DArray.MostDetailedMip = 0; srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; Dev->CreateShaderResourceView( tex, &srvdesc, &aTexturesHigh ); SRDATA.clear(); //cleanup: for( j = 0; j < TEX.size(); j++ ) delete [ ] TEX[j]; TEX.clear(); if( NTEX.size() ) { for( j = 0; j< NTEX.size(); j++ ) delete [ ] NTEX[j]; NTEX.clear(); } delete [ ] Vtx; delete [ ] Idx; }*/ //}
596f355d4ad3bd6872aeaf3d60dcfdd00037b812
c9b51989bc5db196a3590b840f60d0c2aa16c999
/lab1/rle/rle/rle.cpp
1a2321a3fc2def24d37974d24ad1f18ca708c2b7
[]
no_license
artyRay12/OOP
0d6a7e573c8aee2aae19fd62d78f186ae8b5856b
3100ef5c2b54467a554f78641876b498eeea1b6f
refs/heads/master
2021-01-08T02:31:16.936680
2020-08-20T17:41:07
2020-08-20T17:41:07
241,879,747
0
0
null
null
null
null
UTF-8
C++
false
false
2,057
cpp
rle.cpp
#include <iostream> #include <fstream> #include <optional> #include <string> #include <vector> #include <sstream> #include <map> #include <iterator> #include <iomanip> #include <bitset> using namespace std; struct Args { string inputFileName; string outputFileName; }; optional<Args> ParseArgs(int argc, char* argv[]) { Args args; if ((argc != 3)) { cout << "Invalid number of parametres \n usage extract.txt <input File> <output File>" << endl; return nullopt; } args.inputFileName = argv[1]; args.outputFileName = argv[2]; return args; } bool Encode(ifstream& input, ofstream& output) { char ch; string line; /*multimap<char, int> rleInfo; map<char, int> rleInfo; rleInfo.clear(); map<char, int>::iterator it; while (input.get(ch)) { cout << setw(4) << int(ch); if (rleInfo.find(ch) == rleInfo.end()) { rleInfo.emplace(ch , 1); } else { rleInfo[ch]++; } } for (auto it = rleInfo.begin(); it != rleInfo.end(); ++it) { cout << it->first << " : " << it->second << endl; }*/ string letters; while (getline(input, line)) { for (int j = 0; j < line.size(); j++) { cout << bitset<8>(int(line[j])) << endl; int count = 1; /*while (line[j] == line[j + 1]) { count++; j++; }*/ } } stringstream str(letters); while (str.get(ch)) { //cout << (ch); } return true; } bool Rle(const string& inputFileName, const string& outputFileName) { ifstream input; input.open(inputFileName, ios::binary); if (!input.is_open()) { cout << "cant open input file" << endl; return false; } ofstream output; output.open(outputFileName); if (!output.is_open()) { cout << "cant open output file" << endl; return false; } if (!Encode(input, output)) { } cout << endl; input.close(); input.open(inputFileName, ios::binary); char ch; } int main(int argc, char* argv[]) { auto args = ParseArgs(argc, argv); if (!args) { return 1; } if (!Rle(args->inputFileName, args->outputFileName)) { cout << "SomeThingWrong"; } return 0; }
fb4498fd17a098b233e1a4aaefca6502a1ec6be7
b665ef5258bfc2cedc382300b9bfb95ffb1b15b2
/source/Koopa.cpp
d4751d3b807aa04ad9f101baa8146b3b07b828cc
[]
no_license
aminb7/SuperMario
423f401d0d98e56affc778c18f2d36b5772834b6
ddd2b2ba56937d4373d1975da3136f422f48e9af
refs/heads/master
2022-12-04T01:25:18.629819
2020-08-29T10:29:14
2020-08-29T10:29:14
291,249,053
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
Koopa.cpp
#include "Koopa.hpp" Koopa::Koopa(Point _position ) :position(_position){} Point Koopa::getPosition(){ return position; } void Koopa::setDirection(string _direction){ direction = _direction; } void Koopa::setSituation(string _situation){ situation = _situation; } void Koopa::setFallingVelocity(int velocity){ fallingVelocity = velocity; } void Koopa::setKickingSituation(int _kickingSituation){ kickingSituation = _kickingSituation; } string Koopa::getSituation(){ return situation; } int Koopa::getWidth(){ return width; } int Koopa::getHeight(){ return height; } string Koopa::getDirection(){ return direction; } int Koopa::getKickingSituation(){ return kickingSituation; } string Koopa::imageAddress(){ string imageAddress = KOOPA_ADDRESS; imageAddress.append(SLASH); imageAddress.append(situation); if(situation != DYING){ imageAddress.append(MINUS); imageAddress.append(direction); } imageAddress.append(".png"); return imageAddress; } void Koopa::move(){ if(direction == RIGHT) position = Point(position.x + 2, position.y); if(direction == LEFT) position = Point(position.x - 2, position.y); } void Koopa::kick(){ if(direction == RIGHT) position = Point(position.x + 10, position.y); if(direction == LEFT) position = Point(position.x - 10, position.y); } void Koopa::fall(){ position = Point(position.x , position.y + fallingVelocity); } void Koopa::changWalkingStyle(){ if(situation == WALKING_TYPE1){ situation = WALKING_TYPE2; return; } if(situation == WALKING_TYPE2){ situation = WALKING_TYPE1; return; } }
9463ab1e2e38160e9fca4fd9014776aac1b15191
863b62b6ca534479773c1bc2051f875e0120e259
/Unreal/CarlaUE4/Plugins/Carla/Source/Carla/FBXImport/MapProcessCommandlet.h
a94c05418855842a54f3da9fe42d0cb2ae14332e
[ "MIT", "CC-BY-4.0" ]
permissive
fredxu93/carla
c295b375bc11c4961e08abd32f1548a1499c1d05
9183ef91960c2d8b66dde58c7e1081678b2066d8
refs/heads/master
2020-06-11T03:50:07.978434
2019-06-25T13:14:14
2019-06-25T14:08:57
193,842,795
1
0
MIT
2019-06-26T06:27:14
2019-06-26T06:27:14
null
UTF-8
C++
false
false
3,907
h
MapProcessCommandlet.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "Commandlets/Commandlet.h" #include <Engine/World.h> #include <UObject/Package.h> #include <Misc/PackageName.h> #include "CoreMinimal.h" #include <Runtime/Engine/Classes/Engine/ObjectLibrary.h> #include "Carla/OpenDrive/OpenDriveActor.h" #if WITH_EDITORONLY_DATA #include <Developer/AssetTools/Public/IAssetTools.h> #include <Developer/AssetTools/Public/AssetToolsModule.h> #include <AssetRegistry/Public/AssetRegistryModule.h> #endif //WITH_EDITORONLY_DATA #include <Runtime/Engine/Classes/Engine/StaticMeshActor.h> #include "MapProcessCommandlet.generated.h" UCLASS() class UMapProcessCommandlet : public UCommandlet { GENERATED_BODY() public: /** Default constructor. */ UMapProcessCommandlet(); #if WITH_EDITORONLY_DATA /** * Parses the command line parameters * @param InParams - The parameters to parse */ bool ParseParams(const FString& InParams); /** * Move meshes from one folder to another. It only works with StaticMeshes * @param SrcPath - Source folder from which the StaticMeshes will be obtained * @param DestPath - Posible folder in which the Meshes will be ordered following * the semantic segmentation. It follows ROAD_INDEX, MARKINGLINE_INDEX, TERRAIN_INDEX * for the position in which each path will be stored. */ void MoveMeshes(const FString &SrcPath, const TArray<FString> &DestPath); /** * Loads a UWorld object from a given path into a asset data structure. * @param SrcPath - Folder in which the world is located. * @param AssetData - Structure in which the loaded UWorld will be saved. */ void LoadWorld(const FString &SrcPath, FAssetData& AssetData); /** * Add StaticMeshes from a folder into the World loaded as UPROPERTY. * @param SrcPath - Array containing the folders from which the Assets will be loaded * @param bMaterialWorkaround - Flag that will trigger a change in the materials to fix a known bug * in RoadRunner. */ void AddMeshesToWorld(const TArray<FString> &SrcPath, bool bMaterialWorkaround); /** * Save a given Asset containing a World into a given path with a given name. * @param AssetData - Contains all the info about the World to be saved * @param DestPath - Path in which the asset will be saved. * @param WorldName - Name for the saved world. */ bool SaveWorld(FAssetData& AssetData, FString &DestPath, FString &WorldName); public: /** * Main method and entry of the commandlet * @param Params - Parameters of the commandlet. */ virtual int32 Main(const FString &Params) override; #endif //WITH_EDITORONLY_DATA private: /** Materials for the workaround */ /** * Workaround material for MarkingNodes mesh */ UMaterial* MarkingNodeMaterial; /** * Workaround material for the RoadNode mesh */ UMaterial* RoadNodeMaterial; /** * Workaround material for the second material for the MarkingNodes */ UMaterial* MarkingNodeMaterialAux; /** * Workaround material for the TerrainNodes */ UMaterial* TerrainNodeMaterial; /** * Index in which everything related to the road will be stored in inclass arrays */ static const int ROAD_INDEX = 0; /** * Index in which everything related to the marking lines will be stored in inclass arrays */ static const int MARKINGLINE_INDEX = 1; /** * Index in which everything related to the terrain will be stored in inclass arrays */ static const int TERRAIN_INDEX = 2; UPROPERTY() bool bOverrideMaterials; //UProperties are necesary or else the GC will eat everything up UPROPERTY() FString MapName; UPROPERTY() UObjectLibrary* MapObjectLibrary; UPROPERTY() TArray<FAssetData> AssetDatas; UPROPERTY() UWorld* World; UPROPERTY() UObjectLibrary* AssetsObjectLibrary; UPROPERTY() TArray<FAssetData> MapContents; };
c6395a5bc3ebf1eba5e9850c07ba698e5547a933
3b11cdd45dbe774bbb749975fd2d5fedbff6b1e3
/src/Network.h
3dcfe59f5612172eafb6a60e5f357f38626acfbb
[]
no_license
MartinUbl/kiv-psi-vtpgui
91bceab7cf6b50501c1b70cea3e1f1cb4e77cb26
c2d052413c3a2574a50de33da68c76abb86b232a
refs/heads/master
2021-01-20T14:29:19.943425
2017-05-09T10:41:33
2017-05-09T10:41:51
90,618,419
0
0
null
null
null
null
UTF-8
C++
false
false
2,674
h
Network.h
/******************************** * KIV/PSI: VTP node * * Semestral work * * * * Author: Martin UBL * * A16N0026P * * ublm@students.zcu.cz * ********************************/ #ifndef NETWORK_H #define NETWORK_H #include "Singleton.h" #include "NetworkDefs.h" #include <pcap.h> #include <list> #include <thread> // enumerator of used templates for sending enum class SendingTemplate { NET_SEND_TEMPLATE_NONE = 0, NET_SEND_TEMPLATE_8023 = 1, // 802.3 Ethernet NET_SEND_TEMPLATE_DOT1Q = 2 // 802.1Q encapsulation }; /* * Container structure for network interface description */ struct NetworkDeviceListEntry { // name used for PCAP opening std::string pcapName; // system interface description std::string pcapDesc; // list of IPv4 addresses of this interface std::list<std::string> addresses; }; /* * Class maintaining network-related services, encapsulation to MAC/LLC frames, etc. */ class NetworkService : public CSingleton<NetworkService> { private: // network thread used std::thread* m_networkThread; // PCAP device of opened interface pcap_t* m_dev; // sending template used in outgoing traffic SendingTemplate m_sendingTemplate; // outgoing traffic header uint8_t* m_header; // outgoing traffic header length uint16_t m_headerLenght; // pointer to header length field uint16_t* m_headerDataLengthField; // pointer to source MAC field uint8_t* m_sourceMacField; // is the thread still running? bool m_running; protected: // thread function void _Run(); public: NetworkService(); // retrieves all device list and puts it into supplied list int GetDeviceList(std::list<NetworkDeviceListEntry>& target); // selects specified device to operate on int SelectDevice(const char* pcapName, std::string& err); // run network worker void Run(); // finalize network worker void Finalize(); // do we have sending template set? bool HasSendingTemplate(); // sets sending template to be used in outgoing traffic void SetSendingTemplate(SendingTemplate templType, uint16_t vlanId = 0); // sends frame with supplied data void SendUsingTemplate(uint8_t* data, uint16_t dataLength); }; #define sNetwork NetworkService::getInstance() #endif
2c0a9bc84b6fe1d50fa8077b999f2abbdaa80e68
fb07649e1d33962aaf631ef1c4024314f8bfd4a9
/THOR__chassis.cpp
60f5f2040cd9d077f47252332a8592a80488b32a
[]
no_license
krylenko/embedded
653923fe51ccc25e7ff7c6f085c3d5c689ca4188
518d1261c55801dd0e2ac9bc0551addd63550ecb
refs/heads/master
2016-09-05T20:58:32.263316
2015-05-13T17:52:58
2015-05-13T17:52:58
34,310,661
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
cpp
THOR__chassis.cpp
// (c) daniel ford, daniel.jb.ford@gmail.com // chassis node // communicates with PIC18F4580 to get and update state of chassis (motors, gripper, LEDs, etc.) #include "ros/ros.h" #include "chassis.h" int main(int argc, char **argv) { // init chassis object Chassis thor; thor.init(); // initialize state variables // set up ros publisher ros::init(argc, argv, "chassis"); // init publisher node ros::NodeHandle n; // init node handle // create publisher handle // topic name in quotes ros::Publisher chassis_pub = n.advertise<thor::stateMsg>("chassis_state", 1000); ros::Rate loop_rate(10); // specify loop rate (10 Hz here) // set up ros service ros::init(argc, argv, "chassisStateUpdate"); // init service node ros::NodeHandle s; // init node handle ros::ServiceServer service = s.advertiseService("chassis_state_update", &Chassis::updateState, &thor); // loop while roscore is running while (ros::ok()) { // get state from PIC, update state in Chassis object, fill state message thor::stateMsg state = thor.getState(); chassis_pub.publish(state); // publish message // flush data to callbacks (not needed here, but generally useful) ros::spinOnce(); // sleep until woken again by loop_rate code loop_rate.sleep(); } return 0; }
48271e4b1411eb46b15c4e0c13e15fe5c0774c3c
9c97b447f9294671b3c9b28fc67b6cbc0724a668
/subversion/bindings/javahl/native/jniwrapper/jni_string_map.cpp
2fb9a8439cfa8adb808099c892ebc2ef62b08626
[ "LicenseRef-scancode-unicode", "HPND-Markus-Kuhn", "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "X11" ]
permissive
ezdev128/svn
1d69fa158a417ac868fc0700750e58fdd6d032d7
a5bdbda4d6ab2bd4e7ae87a86e4967e33968aa38
refs/heads/master
2021-01-10T20:39:57.918993
2015-01-30T10:44:16
2015-01-30T10:44:16
30,067,743
0
0
null
null
null
null
UTF-8
C++
false
false
5,191
cpp
jni_string_map.cpp
/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * @endcopyright */ #include <stdexcept> #include "jni_string.hpp" #include "jni_string_map.hpp" #include "svn_private_config.h" namespace Java { // Class Java::BaseMap const char* const BaseMap::m_class_name = "java/util/Map"; BaseMap::ClassImpl::ClassImpl(Env env, jclass cls) : Object::ClassImpl(env, cls), m_mid_size(env.GetMethodID(cls, "size", "()I")), m_mid_entry_set(env.GetMethodID(cls, "entrySet", "()Ljava/util/Set;")) {} BaseMap::ClassImpl::~ClassImpl() {} const char* const BaseMap::Set::m_class_name = "java/util/Set"; BaseMap::Set::ClassImpl::ClassImpl(Env env, jclass cls) : Object::ClassImpl(env, cls), m_mid_iterator(env.GetMethodID(cls, "iterator", "()Ljava/util/Iterator;")) {} BaseMap::Set::ClassImpl::~ClassImpl() {} const char* const BaseMap::Iterator::m_class_name = "java/util/Iterator"; BaseMap::Iterator::ClassImpl::ClassImpl(Env env, jclass cls) : Object::ClassImpl(env, cls), m_mid_has_next(env.GetMethodID(cls, "hasNext", "()Z")), m_mid_next(env.GetMethodID(cls, "next", "()Ljava/lang/Object;")) {} BaseMap::Iterator::ClassImpl::~ClassImpl() {} const char* const BaseMap::Entry::m_class_name = "java/util/Map$Entry"; BaseMap::Entry::ClassImpl::ClassImpl(Env env, jclass cls) : Object::ClassImpl(env, cls), m_mid_get_key(env.GetMethodID(cls, "getKey", "()Ljava/lang/Object;")), m_mid_get_value(env.GetMethodID(cls, "getValue", "()Ljava/lang/Object;")) {} BaseMap::Entry::ClassImpl::~ClassImpl() {} jobject BaseMap::operator[](const std::string& index) const { somap::const_iterator it = m_contents.find(index); if (it == m_contents.end()) { std::string msg(_("Map does not contain key: ")); msg += index; throw std::out_of_range(msg.c_str()); } return it->second; } BaseMap::somap BaseMap::convert_to_map(Env env, jobject jmap) { const ClassImpl* pimpl = dynamic_cast<const ClassImpl*>(ClassCache::get_map(env)); if (!env.CallIntMethod(jmap, pimpl->m_mid_size)) return somap(); // Get an iterator over the map's entry set const jobject entries = env.CallObjectMethod(jmap, pimpl->m_mid_entry_set); const jobject iterator = env.CallObjectMethod(entries, Set::impl(env).m_mid_iterator); const Iterator::ClassImpl& iterimpl = Iterator::impl(env); const Entry::ClassImpl& entimpl = Entry::impl(env); // Yterate over the map, filling the native map somap contents; while (env.CallBooleanMethod(iterator, iterimpl.m_mid_has_next)) { const jobject entry = env.CallObjectMethod(iterator, iterimpl.m_mid_next); const String keystr( env, jstring(env.CallObjectMethod(entry, entimpl.m_mid_get_key))); const jobject value( env.CallObjectMethod(entry, entimpl.m_mid_get_value)); const String::Contents key(keystr); contents.insert(somap::value_type(key.c_str(), value)); } return contents; } // Class Java::BaseMutableMap const char* const BaseMutableMap::m_class_name = "java/util/HashMap"; BaseMutableMap::ClassImpl::ClassImpl(Env env, jclass cls) : Object::ClassImpl(env, cls), m_mid_ctor(env.GetMethodID(cls, "<init>", "(I)V")), m_mid_put(env.GetMethodID(cls, "put", "(Ljava/lang/Object;Ljava/lang/Object;)" "Ljava/lang/Object;")), m_mid_clear(env.GetMethodID(cls, "clear", "()V")), m_mid_has_key(env.GetMethodID(cls, "containsKey", "(Ljava/lang/Object;)Z")), m_mid_get(env.GetMethodID(cls, "get", "(Ljava/lang/Object;)Ljava/lang/Object;")), m_mid_size(env.GetMethodID(cls, "size", "()I")) {} BaseMutableMap::ClassImpl::~ClassImpl() {} jobject BaseMutableMap::operator[](const std::string& index) const { const String key(m_env, index); if (!m_env.CallBooleanMethod(m_jthis, impl().m_mid_has_key, key.get())) { std::string msg(_("Map does not contain key: ")); msg += index; throw std::out_of_range(msg.c_str()); } return m_env.CallObjectMethod(m_jthis, impl().m_mid_get, key.get()); } } // namespace Java
f22184bfbcbd6c5a6fc509844eed9fe95ff56659
7b86ed0a2dd5f920608c799a7378bce40e620218
/Amicable/Platform_GCC_Linux.h
d89fe84dc313130f314d2e4926652f4f9d8dd8a3
[]
no_license
justinas2/Amicable
f1a1aa1d8b2499d6269f99e8d8f8db8364915d15
d4efb90faf64a6b18bb29a44d33c9f94f96d39fb
refs/heads/master
2020-03-31T08:36:15.929040
2018-01-06T16:02:58
2018-01-06T16:02:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,000
h
Platform_GCC_Linux.h
#pragma once #ifndef NOINLINE #define NOINLINE __attribute__ ((noinline)) #endif #ifdef FORCEINLINE #undef FORCEINLINE #endif #define FORCEINLINE __attribute__((always_inline)) inline #define CACHE_ALIGNED __attribute__((aligned(64))) #define THREAD_LOCAL thread_local template <typename T, number N> char(*ArraySizeHelper(T(&)[N]))[N]; #define ARRAYSIZE(A) (sizeof(*ArraySizeHelper(A))) typedef unsigned long DWORD; typedef long long __int64; FORCEINLINE void _BitScanReverse64(unsigned long* index, unsigned long long mask) { *index = static_cast<unsigned long>(63 - __builtin_clzll(mask)); } FORCEINLINE void _BitScanForward64(unsigned long* index, unsigned long long mask) { *index = static_cast<unsigned long>(__builtin_ctzll(mask)); } FORCEINLINE number _rotr64(number value, int shift) { return (value >> shift) | (value << (64 - shift)); } #include <pthread.h> #include <string.h> #include <sys/mman.h> #include <fenv.h> #include <cpuid.h> #include <time.h> #include <alloca.h> #define CRITICAL_SECTION pthread_mutex_t #define CRITICAL_SECTION_INITIALIZER PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #define InitializeCriticalSection(X) ((void)(X)) #define DeleteCriticalSection(X) ((void)(X)) FORCEINLINE int TryEnterCriticalSection(CRITICAL_SECTION* lock) { return (pthread_mutex_trylock(lock) == 0) ? 1 : 0; } FORCEINLINE int EnterCriticalSection(CRITICAL_SECTION* lock) { return (pthread_mutex_lock(lock) == 0) ? 1 : 0; } FORCEINLINE int LeaveCriticalSection(CRITICAL_SECTION* lock) { return (pthread_mutex_unlock(lock) == 0) ? 1 : 0; } #define IF_CONSTEXPR(X) \ static_assert((X) || !(X), "Error: "#X" is not a constexpr"); \ if (X) #define __popcnt64 __builtin_popcountll #define ASSUME(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) #define UNLIKELY(cond) __builtin_expect(cond, 0) #define _InterlockedIncrement(X) (__sync_fetch_and_add(X, 1) + 1) #define sscanf_s sscanf #define TRY #define EXCEPT(X) class Timer { public: FORCEINLINE explicit Timer() { clock_gettime(CLOCK_REALTIME, &t1); } FORCEINLINE double getElapsedTime() const { timespec t2; clock_gettime(CLOCK_REALTIME, &t2); return (t2.tv_sec - t1.tv_sec) + (t2.tv_nsec - t1.tv_nsec) * 1e-9; } private: timespec t1; }; FORCEINLINE void Sleep(DWORD ms) { Timer t0; for (;;) { const double sleepTime = ms / 1000.0 - t0.getElapsedTime(); if (sleepTime <= 0) { return; } timespec t; t.tv_sec = static_cast<time_t>(sleepTime); t.tv_nsec = static_cast<long>((sleepTime - t.tv_sec) * 1e9); nanosleep(&t, nullptr); } } FORCEINLINE bool IsPopcntAvailable() { unsigned int cpuid_data[4] = {}; __get_cpuid(1, &cpuid_data[0], &cpuid_data[1], &cpuid_data[2], &cpuid_data[3]); return (cpuid_data[2] & (1 << 23)) != 0; } FORCEINLINE void* AllocateSystemMemory(number size, bool is_executable) { return mmap(0, size, is_executable ? (PROT_READ | PROT_WRITE | PROT_EXEC) : (PROT_READ | PROT_WRITE), MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } FORCEINLINE void DisableAccessToMemory(void* ptr, number size) { mprotect(ptr, size, PROT_NONE); } FORCEINLINE void ForceRoundUpFloatingPoint() { fesetround(FE_UPWARD); } // All code that doesn't pass "-Wpedantic" must be below this comment #pragma GCC system_header FORCEINLINE number _umul128(number a, number b, number* h) { const unsigned __int128 result = static_cast<unsigned __int128>(a) * b; *h = static_cast<number>(result >> 64); return static_cast<number>(result); } FORCEINLINE number udiv128(number numhi, number numlo, number den, number* rem) { const unsigned __int128 n = (static_cast<unsigned __int128>(numhi) << 64) + numlo; const number result = n / den; *rem = n % den; return result; } FORCEINLINE number mulmod64(number a, number b, number n) { return (static_cast<unsigned __int128>(a) * b) % n; } FORCEINLINE void add128(number a_lo, number a_hi, number b_lo, number b_hi, number* result_lo, number* result_hi) { const unsigned __int128 result = ((static_cast<unsigned __int128>(a_hi) << 64) + a_lo) + ((static_cast<unsigned __int128>(b_hi) << 64) + b_lo); *result_lo = static_cast<number>(result); *result_hi = static_cast<number>(result >> 64); } FORCEINLINE void sub128(number a_lo, number a_hi, number b_lo, number b_hi, number* result_lo, number* result_hi) { const unsigned __int128 result = ((static_cast<unsigned __int128>(a_hi) << 64) + a_lo) - ((static_cast<unsigned __int128>(b_hi) << 64) + b_lo); *result_lo = static_cast<number>(result); *result_hi = static_cast<number>(result >> 64); } FORCEINLINE byte leq128(number a_lo, number a_hi, number b_lo, number b_hi) { return (static_cast<__int128>(((static_cast<unsigned __int128>(a_hi) << 64) + a_lo) - ((static_cast<unsigned __int128>(b_hi) << 64) + b_lo)) <= 0) ? 1 : 0; } FORCEINLINE void shr128(number& lo, number& hi, unsigned char count) { unsigned __int128 t = (static_cast<unsigned __int128>(hi) << 64) + lo; t >>= count; lo = static_cast<number>(t); hi = static_cast<number>(t >> 64); }
9d84e7ea23a7a2d7e7cd3783218315549876969f
f0bd42c8ae869dee511f6d41b1bc255cb32887d5
/Codeforces/479B. Towers.cpp
55c8bb0f587ac2daba783dbe4e5d7585103ca7a9
[]
no_license
osamahatem/CompetitiveProgramming
3c68218a181d4637c09f31a7097c62f20977ffcd
a5b54ae8cab47b2720a64c68832a9c07668c5ffb
refs/heads/master
2021-06-10T10:21:13.879053
2020-07-07T14:59:44
2020-07-07T14:59:44
113,673,720
3
1
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
479B. Towers.cpp
/* * 479B. Towers.cpp * * Created on: Jun 11, 2016 * Author: Osama Hatem */ #include <bits/stdtr1c++.h> #include <ext/numeric> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); // freopen("out.out", "w", stdout); #endif int n, k; set<pair<int, int>> all; cin >> n >> k; for (int i = 1; i <= n; i++) { int x; cin >> x; all.insert(make_pair(x, i)); } vector<pair<int, int>> ops; for (int i = 0; i < k; i++) { pair<int, int> mini = *all.begin(); pair<int, int> maxi = *all.rbegin(); if (maxi.first - mini.first < 2) break; all.erase(all.begin()); all.erase(--all.end()); mini.first++, maxi.first--; ops.push_back(make_pair(maxi.second, mini.second)); all.insert(mini); all.insert(maxi); } pair<int, int> mini = *all.begin(); pair<int, int> maxi = *all.rbegin(); cout << maxi.first - mini.first << " " << ops.size() << endl; for (int i = 0; i < (int) ops.size(); i++) cout << ops[i].first << " " << ops[i].second << endl; return 0; }
d13502e8799a923f070fe641c6966bdc80c55260
21355ad1da114531103e1b3344ee69b36b45766b
/TheWhiteDeath/Source/TheWhiteDeath/Private/HitBoxComponent.cpp
8e9274c1781cf4344135988338d1119b32a793e7
[]
no_license
ACPLMaverick/Wawrzonowski_Samples
306a96102d4031c76cead1f0eca560bf6fa0f6d1
0d48ff3dc199fe409a958cd825253e79fe55c777
refs/heads/master
2021-07-21T07:16:14.602554
2017-10-30T08:22:11
2017-10-30T08:22:11
107,714,116
1
0
null
null
null
null
UTF-8
C++
false
false
4,628
cpp
HitBoxComponent.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TheWhiteDeath.h" #include "HitBoxComponent.h" #include "Components/BoxComponent.h" #include "Components/DecalComponent.h" #include "Components/MeshComponent.h" #include "Components/SkeletalMeshComponent.h" #include "TheWhiteDeathProjectile.h" #include "TheWhiteDeathCharacter.h" #include "Public/Gun.h" #include "ParticleDefinitions.h" // Sets default values UHitBoxComponent::UHitBoxComponent() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryComponentTick.bCanEverTick = true; Bounds.BoxExtent = FVector(32.0f, 32.0f, 32.0f); SetCollisionProfileName(TEXT("OverlapAll")); SetSimulatePhysics(false); OnComponentHit.AddDynamic(this, &UHitBoxComponent::OnHit); Decal = CreateDefaultSubobject<UDecalComponent>(TEXT("Decal")); Decal->SetupAttachment(this); Decal->DecalSize = FVector(1.0f, 1.0f, 1.0f); Particles = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("Particles")); Particles->SetupAttachment(this); } // Called when the game starts or when spawned void UHitBoxComponent::BeginPlay() { Super::BeginPlay(); Particles->DeactivateSystem(); if (GetOwner() != NULL) { _mesh = Cast<UMeshComponent>(GetOwner()->GetComponentByClass(UMeshComponent::StaticClass())); _skMesh = Cast<USkeletalMeshComponent>(GetOwner()->GetComponentByClass(USkeletalMeshComponent::StaticClass())); } } // Called every frame void UHitBoxComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); TickComponentsToDestroy(DeltaTime); } void UHitBoxComponent::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { if (OtherActor->IsA<ATheWhiteDeathProjectile>()) { OnHitByProjectile(Cast<ATheWhiteDeathProjectile>(OtherActor), OtherComp, NormalImpulse, Hit); } } void UHitBoxComponent::TickComponentsToDestroy(float deltaTime) { for (int i = 0; i < _componentsToDestroy.Num(); ++i) { _componentsToDestroy[i].Timer += deltaTime; if (_componentsToDestroy[i].Timer >= _componentsToDestroy[i].TimeToDestroy) { if (_componentsToDestroy[i].Component != NULL && !_componentsToDestroy[i].Component->IsBeingDestroyed()) { _componentsToDestroy[i].Component->DestroyComponent(); } _componentsToDestroy.RemoveAt(i, 1, false); } } } void UHitBoxComponent::OnHitByProjectile(ATheWhiteDeathProjectile * OtherActor, UPrimitiveComponent * OtherComp, FVector NormalImpulse, const FHitResult & Hit) { // apply damage if actor is whitedeathcharacter AGun* gun = OtherActor->GetOwningGun(); FVector dir(0.0f, 0.0f, 1.0f); ATheWhiteDeathCharacter* owner = NULL; if (gun != NULL) { dir = GetComponentLocation() - gun->GetActorLocation(); dir = dir.GetSafeNormal(); owner = Cast<ATheWhiteDeathCharacter>(GetOwner()); if (owner != NULL) { // set damage float totalDamage = (OtherActor->GetDamage() + gun->GetDamageBase()) * DamageMultiplier; owner->OnHit(totalDamage, dir); } } // calculate hit position on mesh (if available) FVector hitPosition = Hit.Location; FVector hitOnBody = Hit.Location; if (_skMesh != NULL) { _skMesh->GetClosestPointOnCollision(hitPosition, hitOnBody); } else if (_mesh != NULL) { _mesh->GetClosestPointOnCollision(hitPosition, hitOnBody); } hitPosition = hitOnBody; // add hit decal if (Decal != NULL) { UDecalComponent* SpawnedDecal = NewObject<UDecalComponent>(GetOwner()->GetRootComponent(), NAME_None, RF_NoFlags, Decal); if (SpawnedDecal) { _componentsToDestroy.Add(FHitBoxDestructionPair(SpawnedDecal, DecalLifeSeconds)); SpawnedDecal->RegisterComponent(); SpawnedDecal->SetWorldLocation(hitPosition); SpawnedDecal->SetWorldScale3D(FVector(DecalSize)); SpawnedDecal->SetFadeOut(DecalLifeSeconds * 0.75f, DecalLifeSeconds * 0.25f, false); SpawnedDecal->Activate(); } } // fire particle if (Particles != NULL) { UParticleSystemComponent* SpawnedParticles = NewObject<UParticleSystemComponent>(this, NAME_None, RF_NoFlags, Particles); if (SpawnedParticles) { _componentsToDestroy.Add(FHitBoxDestructionPair(SpawnedParticles, 3.0f)); SpawnedParticles->RegisterComponent(); SpawnedParticles->SetWorldLocation(hitPosition); SpawnedParticles->Activate(); SpawnedParticles->ActivateSystem(); } } // fire sound if (Sound != NULL) { UGameplayStatics::PlaySoundAtLocation(this, Sound, GetComponentLocation()); } }
21aff4bf35f68e2ddbf7a6e55ff004352801f8f8
ee9efe92303f92e75cc902378ff5d1ae43c1eaa7
/include/exceptions/exceptions.h
39f20b61343d684c0d117172877a07190ce303cd
[ "MIT" ]
permissive
S-1-T/pascal-c-compiler
1329e39b285e2b7966ab33fb3fb24600d3a71ca0
d5f95f31b2a15bf551d2a67f3ba23b8d99939a2d
refs/heads/master
2022-12-15T12:40:06.184391
2020-09-11T01:33:08
2020-09-11T01:33:08
263,371,277
1
0
null
null
null
null
UTF-8
C++
false
false
1,031
h
exceptions.h
// // Created by 69118 on 2020/9/10. // #ifndef PASCAL_C_COMPILER_EXCEPTIONS_H #define PASCAL_C_COMPILER_EXCEPTIONS_H #include <exception> using std::exception; class TypeException : public exception { const char* what() const noexcept override { return "无效的 Type"; } }; class StatementException : public exception { const char* what() const noexcept override { return "无效的 Statement"; } }; class FactorException : public exception { const char* what() const noexcept override { return "无效的 Factor"; } }; class UminusException : public exception { const char* what() const noexcept override { return "无效的 Uminus"; } }; class ConstException : public exception { const char* what() const noexcept override { return "无效的 Const"; } }; class OperatorException : public exception { const char* what() const noexcept override { return "无效的 Operator"; } }; #endif //PASCAL_C_COMPILER_EXCEPTIONS_H
e9044e4a0376b84418b496e2f2259a2a666f2435
316a6d4a905da881063c9712a0fa5ed6860ae5d9
/402. Remove K Digits.cpp
a01816011c63ad4510a9a0b508a8c1bfb15102e4
[]
no_license
alexliuyi/Leetcode
0f7a217c2c8a63a10039424561aa474c424f70a1
389954c6c31ae49ce0674513905e3696fb7f49d2
refs/heads/master
2020-04-18T13:53:32.314264
2019-02-06T22:50:47
2019-02-06T22:50:47
167,573,884
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
402. Remove K Digits.cpp
#include <vector> class Solution { public: string removeKdigits(string num, int k) { std::vector<int> S; std::string result=""; for(int i=0;i < num.length();i++){ int number = num[i] - '0'; while(S.size()!=0 && S[S.size()-1] > number && k>0){ S.pop_back(); k--; } if(number!=0||S.size()!=0){ S.push_back(number); } } while(S.size()!=0 && k>0){ S.pop_back(); k--; } for(int i=0;i<S.size();i++){ result.append(1,'0'+S[i]); } if(result == ""){ result="0"; } return result; } };
e915e5749c6e16bbe6dda46c30926d3b8494011e
66c6c2d054777c3738297e6606c1385737345b90
/codeforces/578div2/A.cpp
0b3a8bfd17b50e4f3ab4aaf1d0acc3d2dc6abb20
[ "MIT" ]
permissive
xenowits/cp
f4a72bea29defd77f2412d6dee47c3e17f4d4e81
963b3c7df65b5328d5ce5ef894a46691afefb98c
refs/heads/master
2023-01-03T18:19:29.859876
2020-10-23T10:35:48
2020-10-23T10:35:48
177,056,380
0
1
null
null
null
null
UTF-8
C++
false
false
1,361
cpp
A.cpp
#include<bits/stdc++.h> using namespace std; #define fori(i,a,b) for (long int i = a; i <= b ; ++i) #define ford(i,a,b) for(long int i = a;i >= b ; --i) #define mk make_pair #define mod 1000000007 #define pb push_back #define vec vector<long long int> #define ll long long #define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count()) #define pi pair<int,int> #define sc second #define fs first int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; string s; cin >> s; vector<int> v(10,0); int l = 0, r = 9; for (int i = 0 ; i < s.length(); ++i) { if (s[i] == 'L') { v[l] = 1; for (int x = 0; x < 10; ++x) { if (v[x] == 0) { l = x; break; } } } else if (s[i] == 'R') { v[r] = 1; for (int x = 9; x >= 0; --x) { if (v[x] == 0) { r = x; break; } } } else { ll temp = s[i]-'0'; v[temp] = 0; for (int x = 0; x < 10; ++x) { if (v[x] == 0) { l = x; break; } } for (int x = 9; x >= 0; --x) { if (v[x] == 0) { r = x; break; } } } } fori(i,0,9) cout << v[i]; return 0; }
37e0e66624e8cc19cda3ceb3964b8a16e5db49e4
711aa9c343b397d21ebd9532acc950ee15546d5f
/Manager.h
ab109063cbd68a25accf798fa6d204562a0b6f1e
[]
no_license
vkhakham/backgammon-cpp
48484feff2b12a5984742f462e1a3b5382d287e0
fbcf485efa4fec84bb2a5776d716edcf18e170dc
refs/heads/master
2021-01-10T01:29:59.420519
2015-12-26T18:10:54
2015-12-26T18:10:54
48,293,071
0
1
null
null
null
null
UTF-8
C++
false
false
1,706
h
Manager.h
#ifndef _MANAGER_H_ #define _MANAGER_H_ #pragma once #define DICENUM_VERSION1 46 #define DICENUM_VERSION2 72 #define PLAYINGAGAINSMAYANDROTEM 0 #define HOWMANYGAMESINAROW 0 #define DEBUG val->msg4="move from "+std::to_string(_move.first)+" to "+std::to_string(_move.second); #define PLAYER1 0 #define PLAYER2 0 #define TREELEVELS 2 #define INF 10000 #define INIT_HEURISTIC_VAL_MIN numeric_limits<double>::lowest() #define INIT_HEURISTIC_VAL_MAX numeric_limits<double>::max() #include <iostream> #include <string> #include <vector> typedef std::pair<int, int> my_pair; typedef int dice_matrix[7][7]; using namespace std; #include "Board.h" #include "Player.h" #include "Validator.h" #include "strategy.h" #include <assert.h> #include <time.h> #include <stdlib.h> class Board; class Validator; class Player; class strategy; //singleton class Manager { public: static Manager* instance(); static void ResetInstance(); void initPointersOfMembers(); void runGame(); void showHelp(); void swapDice(); ~Manager(void); void gameOver(string msg1 = " ",string msg2= " " ,string msg3= " ",string msg4= " "); void playDice(); //void playRegularDice(); string sDice; bool bIsWhiteTurn; bool bSwapDice; bool bCurrentDiceDubel; bool isDiceLegal; pair<int , int> _move; pair<int , int> _dice; int turns; int* currentDice; Board *b; Player *pWhite; Player *pBlack; Player *currentPlayer; Validator *val; int maxDepth; int games; int dice_version; strategy *strategy_ptr; bool alpha_beta; int player1; int player2; private: static Manager* m_instance; Manager(void); }; #endif
d6bd45ea84a2943780c65c97506dfec52e0661e1
fb30c306a52b88044730909a7a4f82f03c9359de
/MS_BuildFight/source/administer/Maneger.h
e3ec94ad7ec0b25fd4357fb617d091d293a90495
[]
no_license
yumina1021/miso1510
03cb988537f5a6a91065190efe887a3b720864ac
9ab6917578c73bcbec315714a46950bf8e330911
refs/heads/master
2020-05-27T06:15:47.636456
2016-01-17T16:37:00
2016-01-17T16:37:00
41,708,868
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
6,394
h
Maneger.h
//============================================================================= // // MS_BuildFight [CManager.h] // 15/08/20 // Author : YOSHIKI ITOU // //============================================================================= #ifndef _CMANAGER_H_ #define _CMANAGER_H_ //***************************************************************************** // インクルードファイル //***************************************************************************** #include <windows.h> #include "../common.h" #include "wiicon/WiiRemote.h" #define SCENE_MAX (10) typedef enum //フェーズの種類 { PHASETYPE_TITLE =0, PHASETYPE_TUTRIAL, PHASETYPE_SELECT, PHASETYPE_STAGE_SELECT, PHASETYPE_LOAD, PHASETYPE_GAME, PHASETYPE_RESULT, PHASETYPE_CLEAR, PHASETYPE_GAMEOVER, PHASETYPE_VSEND, PHASETYPE_MAX }PHASETYPE; typedef enum { PLAYER1_WIN = 0, PLAYER2_WIN, PLAYER_DRAW }JUDGETYPE; struct RenderTagets //レンダーターゲット { LPDIRECT3DTEXTURE9 texture; //テクスチャ用ポインタ LPDIRECT3DSURFACE9 surface; //カラーバッファ用サーフェス LPDIRECT3DSURFACE9 surfaceDepth; //Zバッファ用サーフェス LPDIRECT3DVERTEXBUFFER9 vtxBuff; // 頂点バッファインターフェースへのポインタ }; //***************************************************************************** // クラス定義 //***************************************************************************** class CInputKeyboard; //前方宣言 class CInputMouse; class CInputJoypad; class CSound; class CScene; class CCamera; class CGame; class Cform; class CLight; class CEffect; class CTexture; class Live2DManager; class RenderTarget; #ifdef _DEBUG class CDebugProc; #endif class CManager { public: CManager(void); //コンストラクタ ~CManager(void); //デストラクタ HRESULT Init(HINSTANCE hInstance,HWND hWnd,BOOL bWindow); //初期化 void Uninit(void); //終了 void Update(void); //更新 void Draw(void); //描画 void Addform(Cform* pform); //シーンの登録用 static void SetAfterScene(PHASETYPE phase){m_afterSceneType=phase;}; //次のフェーズ受け取り static CInputKeyboard* GetInputKeyboard(void){ return m_pKeyboard; }; static CInputMouse* GetInputMouse(void){ return m_pMouse; }; static CInputJoypad* GetInputJoypad(void){ return m_pJoypad; }; static CSound *GetSound(void){ return m_pSound; }; static CScene *GetScene(void){ return m_pScene; }; static CCamera* GetCamera(void){ return m_pCamera; }; static CLight *GetLight(void){ return m_pLight; } static LPDIRECT3DDEVICE9 GetDevice(void){ return m_pD3DDevice; }; //デバイスの取得 void SetDevice(LPDIRECT3DDEVICE9 device){ m_pD3DDevice = device; }; //デバイスの取得 static PHASETYPE GetSceneType(void){ return m_phaseType; }; static PHASETYPE GetAfetrSceneType(void){ return m_afterSceneType; }; static void SetpauseFlag(bool pause){m_pauseFlag =pause;}; static bool GetpauseFlag(void){return m_pauseFlag;}; static void SetgameEndFlag(bool pause){m_gameEndFlag =pause;}; static bool GetgameEndFlag(void){return m_gameEndFlag;}; static void Setnight0PlayFlag(bool pause){m_night0PlayFlag =pause;}; static bool Getnight0PlayFlag(void){return m_night0PlayFlag;}; static void SetWndHandle(HWND paramWnd){ m_hwnd = paramWnd; }; static HWND GetWndHandle(void){ return m_hwnd; }; static void SetSelectMap(int paramMap){ m_nSelectMap = paramMap; }; static int GetSelectMap(void){ return m_nSelectMap; }; static void SetSelectChar(int paramSetPlayer, int paramMap){ m_nSelectChar[paramSetPlayer] = paramMap; }; static int GetSelectChar(int paramSetPlayer){ return m_nSelectChar[paramSetPlayer]; }; int SetRenderTargets(float width, float height); void RemoveRenderTargets(int i); RenderTagets* GetRenderTargets(int i){ return m_renderTargets[i]; }; static void SetWin(int win){ m_gamewin = win; } static int GetWin(void){ return m_gamewin; } static WiiRemote* GetWii(int id){ return wiimote[id]; } static Live2DManager* GetL2DManager(){ return l2dManager; }; private: void RenderTargetDraw(void); HRESULT RenderInit(HWND hWnd, BOOL bWindow); HRESULT SetShader(void); void ChangeScene(void); //フェーズの変更 LPDIRECT3D9 m_pD3D; // Direct3Dオブジェクト static LPDIRECT3DDEVICE9 m_pD3DDevice; // pDeviceオブジェクト(描画に必要) Cform* m_apforms[SCENE_MAX]; //シーン登録用ポインタ int m_nCountform; //登録数 bool m_bWirerFlag; //ワイヤーフレーム表示フラグ static CInputKeyboard* m_pKeyboard; //キーボードへのポインタ static CInputMouse* m_pMouse; //マウスへのポインタ static CInputJoypad* m_pJoypad; //ジョイパッドへのポインタ static CSound* m_pSound; //サウンドのポインター static CScene* m_pScene; //フェーズのポインター static CScene* m_pSceneT; //フェーズのポインター static CCamera* m_pCamera; //カメラのポインタ static CLight* m_pLight; // ライトへのポインタ static PHASETYPE m_phaseType; //現在のフェーズタイプ static PHASETYPE m_afterSceneType; //次のフェーズタイプ static HWND m_hwnd; static WiiRemote* wiimote[2]; CTexture* m_ptexture; static Live2DManager* l2dManager; #ifdef _DEBUG static CDebugProc *m_pDebugProc; //デバッグ処理へのポインタ #endif static bool m_pauseFlag; //ポーズをしているかのフラグ static bool m_gameEndFlag; //ゲーム終了中かのフラグ static bool m_night0PlayFlag; //ナイト0と戦ったかどうか? int m_nFrameNum; int m_nEnemyNum; RenderTagets* m_renderTargets[5]; RenderTarget* backBuff; LPDIRECT3DSURFACE9 m_pSurfaceBack; //バックバッファ用サーフェス LPDIRECT3DSURFACE9 m_pSurfaceBackD;//バックバッファ用サーフェス D3DVIEWPORT9 m_pViewport; //ビューポート保存用 LPDIRECT3DPIXELSHADER9 _ps[3]; //ピクセルシェーダー LPD3DXCONSTANTTABLE _psc[3]; //ピクセルシェーダー用コンスタントテーブル static int m_nSelectMap; //選んだマップ static int m_nSelectChar[2]; //選んだキャラ static int m_gamewin; }; #endif /////////////EOF////////////
0b910376c28cb6cb03a0f85d691186d0a4496da8
e278115aeb38b23598c6f94c805067bd7fbfac01
/Modules/GUI/source/sqlnewprojectdialog.cpp
7b97c3903249c34de285b9aa873ce623cf478a09
[]
no_license
gdrealm/TTT
e44cf12f4f1845dc0be40b3508d758bbed003e90
e0b773fed9c72dd7ec9f205b1f83ba8262504dac
refs/heads/master
2020-03-08T05:06:43.563369
2015-07-03T16:09:06
2015-07-03T16:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,796
cpp
sqlnewprojectdialog.cpp
#include "sqlnewprojectdialog.h" #include "ui_sqlnewprojectdialog.h" #include <itkImage.h> #include <itkImageFileReader.h> #include <qfiledialog.h> SQLNewProjectDialog::SQLNewProjectDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SQLNewProjectDialog) { m_Accepted=false; ui->setupUi(this); } SQLNewProjectDialog::~SQLNewProjectDialog() { delete ui; } void SQLNewProjectDialog::accept(){ typedef itk::Image<unsigned char,3> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader=ReaderType::New(); m_NewProject = new TissueTrackingProject; std::string name = this->ui->projectNameLabel->text().toStdString(); std::string projectPath = this->ui->wdLineEdit->text().toStdString(); double spacingX = (double)atof(this->ui->xSpacingLineEdit->text().toStdString().c_str()); double spacingY = (double)atof(this->ui->yLineEdit->text().toStdString().c_str()); double spacingZ = (double)atof(this->ui->zLineEdit->text().toStdString().c_str()); double timeDelta = atof(this->ui->timeDeltaLineEdit->text().toStdString().c_str()); int sizeX= atoi(this->ui->selectedFilesTable->item(0,4)->text().toStdString().c_str()); int sizeY= atoi(this->ui->selectedFilesTable->item(0,5)->text().toStdString().c_str()); int sizeZ= atoi(this->ui->selectedFilesTable->item(0,6)->text().toStdString().c_str()); m_NewProject->openDB(); m_NewProject->NewProject(name,projectPath,spacingX,spacingY,spacingZ,timeDelta,sizeX,sizeY,sizeZ); for(int row=0; row<this->ui->selectedFilesTable->rowCount();row++){ m_NewProject->NewFrame(row); QString file= this->ui->selectedFilesTable->item(row,0)->text(); reader->SetFileName(file.toStdString()); reader->Update(); m_NewProject->SetRawImage(reader->GetOutput()); m_NewProject->SetFrame(row); } m_Accepted=true; QDialog::accept(); } void SQLNewProjectDialog::selectWorkingDirectory(){ QString dir=QFileDialog::getExistingDirectory(this,tr("Select woking directory..."),QDir::currentPath(),QFileDialog::ShowDirsOnly); this->ui->wdLineEdit->setText(dir); } void SQLNewProjectDialog::addFiles(){ typedef itk::Image<unsigned char,3> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader=ReaderType::New(); QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Tiff Files to add..."), QDir::currentPath(),"Images (*.mha *.tif *.tiff )"); QStringList list = files; QStringList::Iterator it = list.begin(); int row=this->ui->selectedFilesTable->rowCount(); while(it != list.end()) { this->ui->selectedFilesTable->setRowCount(row+1); QTableWidgetItem *newItem = new QTableWidgetItem(*it); this->ui->selectedFilesTable->setItem(row,0 , newItem); reader->SetFileName(it->toStdString()); reader->Update(); ImageType::SpacingType spacing= reader->GetOutput()->GetSpacing(); newItem = new QTableWidgetItem(tr("%1").arg(spacing[0])); this->ui->selectedFilesTable->setItem(row,1 , newItem); newItem = new QTableWidgetItem(tr("%1").arg(spacing[1])); this->ui->selectedFilesTable->setItem(row,2 , newItem); newItem = new QTableWidgetItem(tr("%1").arg(spacing[2])); this->ui->selectedFilesTable->setItem(row,3 , newItem); ImageType::SizeType size= reader->GetOutput()->GetLargestPossibleRegion().GetSize(); newItem = new QTableWidgetItem(tr("%1").arg(size[0])); this->ui->selectedFilesTable->setItem(row,4 , newItem); newItem = new QTableWidgetItem(tr("%1").arg(size[1])); this->ui->selectedFilesTable->setItem(row,5 , newItem); newItem = new QTableWidgetItem(tr("%1").arg(size[2])); this->ui->selectedFilesTable->setItem(row,6 , newItem); it++; row++; } }
931aaa7b0215534c179a8a54ff6e2fec7ac65310
1ca3440ec13e8f00bd15d2d072fee105b74c9487
/tests/unit/Common/test_TaskScheduler.cpp
581784a385dc7468fe013f920108b12cf78ac2ce
[]
no_license
ronj/teensy-dash
85b6b619ba9c4814724eb2e8a18ab1369d268b98
f963b2e6ea70478275f46c02b661c1f9a553ac58
refs/heads/master
2021-01-18T21:46:51.967531
2015-08-15T13:31:59
2015-08-15T13:31:59
33,808,060
0
0
null
null
null
null
UTF-8
C++
false
false
1,964
cpp
test_TaskScheduler.cpp
#include "yaffut.h" #include "Common/Task.h" #include "Common/TimedTask.h" #include "Common/TaskScheduler.h" #include <functional> // Not using hippomocks here since hippomocks won't call // the constructor for us. class TaskImpl : public Common::Task { public: virtual bool CanRun(uint32_t now) { return Runnable(now); } virtual void Run(uint32_t now) { OnRun(now); } std::function<bool(uint32_t)> Runnable; std::function<void(uint32_t)> OnRun; }; class TimedTaskImpl : public Common::TimedTask { public: TimedTaskImpl(uint32_t now) : Common::TimedTask(now) {} virtual void Run(uint32_t now) { OnRun(now); } std::function<void(uint32_t)> OnRun; }; struct TaskSchedulerTest { TaskImpl taskA; TaskImpl taskB; }; TEST(TaskSchedulerTest, should_run_task_when_runnable) { Common::TaskScheduler scheduler; scheduler.Add(taskA); scheduler.Add(taskB); taskA.Runnable = [](uint32_t now) { return now % 2 == 0; }; taskB.Runnable = [](uint32_t now) { return now % 2 == 1; }; taskA.OnRun = [](uint32_t now) { CHECK(now % 2 == 0); }; taskB.OnRun = [](uint32_t now) { CHECK(now % 2 == 1); }; for (int i = 0; i < 10; ++i) { scheduler.Run(i); } } TEST(TaskSchedulerTest, should_only_run_highest_priority_task) { Common::TaskScheduler scheduler; scheduler.Add(taskA); scheduler.Add(taskB); taskA.Runnable = [](uint32_t) { return true; }; taskB.Runnable = [](uint32_t) { return true; }; taskA.OnRun = [](uint32_t) { CHECK(true); }; taskB.OnRun = [](uint32_t) { FAIL("Task should not be called"); }; for (int i = 0; i < 10; ++i) { scheduler.Run(i); } } TEST(TaskSchedulerTest, should_run_timed_task_with_correct_interval) { TimedTaskImpl timedTask(0); const uint32_t interval = 5; Common::TaskScheduler scheduler; scheduler.Add(timedTask); timedTask.OnRun = [&timedTask, interval](uint32_t now) { CHECK(now % interval == 0); timedTask.IncrementRunTime(interval); }; for (int i = 0; i < 50; ++i) { scheduler.Run(i); } }
92a93552579c0ea1c1f2de2213ddbd8e57215862
4c1fc67a7060fb554e951c47bdc1e1239e893524
/Helper.h
f59b291644ed3693f3ed18c30e215dd62a48999c
[]
no_license
csarigul/crboard
ffb0a98cbf349ff3f92002a7f87ccfcdb856d4a5
0de36f6c6aeb067fd24e3068ab9e5c91781ea884
refs/heads/master
2020-12-24T09:55:26.676657
2018-09-30T09:28:44
2018-09-30T09:28:44
73,259,903
0
0
null
null
null
null
UTF-8
C++
false
false
962
h
Helper.h
// Helper.h #ifndef _HELPER_h #define _HELPER_h #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif #endif #include "LiquidCrystal.h" class Helper { public: /* Check methods */ /* Array methods */ static void PrintArray(byte obj[], byte length); static void PrintArray(char obj[], byte length); static void ArraySubstring(char source[], char result[], int pos, int pos2); static int ArrayIndexOf(char source[], char key[], int keyLength, int charLength); static void ClearArray(byte obj[], int length); static void ClearArray(char* obj, int length); /* Other Methods */ static void InitalizeScreen(LiquidCrystal* lcd); static void InitalizeIO(); static void DebugWrite(char method[], char message[]); static void LcdWrite(const __FlashStringHelper *msg); static void LcdWrite(char* msg); static void LcdWrite(int x, int y, const __FlashStringHelper *msg); static void LcdStatus(byte status); };
83b204b117692122869f0027a11a0ea27890b776
665e68033f9cee9419f6e6a604c9e0fb2bda5324
/include/utils.h
329c39260ff692b8c8479b564027f4481303d5f6
[]
no_license
dronbonpon/FindWordInDictionary
6f275ab9c72c1f736173fedc7ca34e2a6ae1d545
3ab55bc93dc237d50d5a73006075db45cab0fffc
refs/heads/main
2023-04-02T06:12:28.463507
2021-04-12T22:25:31
2021-04-12T22:25:31
356,640,678
0
0
null
null
null
null
UTF-8
C++
false
false
896
h
utils.h
#pragma once #include <vector> #include <string> namespace utils { // Разделить строку по сепаратору delimiter в вектор void Split( std::vector<std::string>& result, const std::string& str, const std::string& delimiter ); // Проверка на то, что строка является подпоследовательностью другой строки bool IsSubSequence( const std::string& sequence, const std::string& subsequence ); // Преобразовать вектор в строку с заданным количеством слов в строке и разделителем delimiter void VectorToString( const std::vector<std::string>& data, std::string& result, int wordsInLine, const std::string& delimiter = ", " ); } // namespace utils
545c8dfff83dd04bbcb7cbcbe8cb12f9605197a9
efb739bb2dd3c9dd07cc26d62ffa46973760b7f2
/src/fheroes2/heroes/skill.cpp
f758ae25e46ad904e09a88dfd521f58fc83efdbd
[]
no_license
infsega/fheroes2-playbook
a6c2bb632ac1582a6acd056326fd14831d9bdb44
a1c2e43b6f7ce72a3e3eec29aad95ea6613200a9
refs/heads/master
2020-06-02T07:42:52.494152
2012-06-28T23:09:43
2012-06-28T23:09:43
4,770,518
5
1
null
null
null
null
UTF-8
C++
false
false
34,324
cpp
skill.cpp
/*************************************************************************** * Copyright (C) 2009 by Andrey Afletdinov <fheroes2@gmail.com> * * * * Part of the Free Heroes2 Engine: * * http://sourceforge.net/projects/fheroes2 * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <cstring> #include <algorithm> #include "gamedefs.h" #include "race.h" #include "agg.h" #include "cursor.h" #include "dialog.h" #include "editor_dialogs.h" #include "heroes.h" #include "settings.h" #include "skill.h" #ifdef WITH_XML #include "xmlccwrap.h" #endif namespace Skill { u8 SecondaryGetWeightSkillFromRace(u8 race, u8 skill); u8 SecondaryPriorityFromRace(u8, const std::vector<u8> &); std::vector<u8> SecondarySkills(void); } struct level_t { u16 basic; u16 advanced; u16 expert; }; struct primary_t { u8 attack; u8 defense; u8 power; u8 knowledge; }; struct secondary_t { u8 archery; u8 ballistics; u8 diplomacy; u8 eagleeye; u8 estates; u8 leadership; u8 logistics; u8 luck; u8 mysticism; u8 navigation; u8 necromancy; u8 pathfinding; u8 scouting; u8 wisdom; }; struct skillstats_t { const char* id; primary_t captain_primary; primary_t initial_primary; u8 initial_book; u8 initial_spell; secondary_t initial_secondary; u8 over_level; primary_t mature_primary_under; primary_t mature_primary_over; secondary_t mature_secondary; }; struct skillvalues_t { const char *id; level_t values; }; skillstats_t _skillstats[] = { { "knight", { 1, 1, 1, 1 }, { 2, 2, 1, 1 }, 0, 0, { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, 10, {35,45,10,10 }, {25,25,25,25 }, { 2, 4, 3, 1, 3, 5, 3, 1, 1, 2, 0, 3, 2, 2 } }, { "barbarian", { 1, 1, 1, 1 }, { 3, 1, 1, 1 }, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0 }, 10, {55,35, 5, 5 }, {30,30,20,20 }, { 3, 3, 2, 1, 2, 3, 3, 2, 1, 3, 0, 4, 4, 1 } }, { "sorceress", { 0, 0, 2, 2 }, { 0, 0, 2, 3 }, 1,15, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1 }, 10, {10,10,30,50 }, {20,20,30,30 }, { 3, 3, 2, 2, 2, 1, 2, 3, 3, 4, 0, 2, 1, 4 } }, { "warlock", { 0, 0, 2, 2 }, { 0, 0, 3, 2 }, 1,19, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1 }, 10, {10,10,50,30 }, {20,20,30,30 }, { 1, 3, 2, 3, 2, 1, 2, 1, 3, 2, 1, 2, 4, 5 } }, { "wizard", { 0, 0, 2, 2 }, { 0, 1, 2, 2 }, 1,17, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2 }, 10, {10,10,40,40 }, {20,20,30,30 }, { 1, 3, 2, 3, 2, 2, 2, 2, 4, 2, 0, 2, 2, 5 } }, { "necromancer", { 0, 0, 2, 2 }, { 1, 0, 2, 2 }, 1,10, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 }, 10, {15,15,35,35 }, {25,25,25,25 }, { 1, 3, 2, 3, 2, 0, 2, 1, 3, 2, 5, 3, 1, 4 } }, { NULL, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 10, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } } }; skillvalues_t _skillvalues[] = { { "pathfinding", { 25, 50,100} }, { "archery", { 10, 25, 50} }, { "logistics", { 10, 20, 30} }, { "scouting", { 1, 2, 3} }, { "diplomacy", { 25, 50,100} }, { "navigation", { 33, 66,100} }, { "leadership", { 1, 2, 3} }, { "wisdom", { 3, 4, 5} }, { "mysticism", { 2, 3, 4} }, { "luck", { 1, 2, 3} }, { "ballistics", { 0, 0, 0} }, { "eagleeye", { 20, 30, 40} }, { "necromancy", { 10, 20, 30} }, { "estates", {100,250,500} }, { NULL, { 0, 0, 0} }, }; secondary_t _from_witchs_hut = { /* archery */ 1, /* ballistics */ 1, /* diplomacy */ 1, /* eagleeye */ 1, /* estates */ 1, /* leadership */ 0, /* logistics */ 1, /* luck */ 1, /* mysticism */ 1, /* navigation */ 1, /* necromancy*/ 0, /* pathfinding */ 1, /* scouting */ 1, /* wisdom */ 1 }; /* struct defaulthero_t { const char* name; primary_t primary; secondary_t sec; // default army // default art // default spells Surface port30x22; Surface port50x46; Surface port101x93; }; */ const skillstats_t* GetSkillStats(u8 race) { const char* id = NULL; switch(race) { case Race::KNGT: id = "knight"; break; case Race::BARB: id = "barbarian"; break; case Race::SORC: id = "sorceress"; break; case Race::WRLK: id = "warlock"; break; case Race::WZRD: id = "wizard"; break; case Race::NECR: id = "necromancer"; break; default: DEBUG(DBG_GAME, DBG_WARN, "is NULL"); break; } const skillstats_t* ptr = &_skillstats[0]; while(ptr->id && id && std::strcmp(id, ptr->id)) ++ptr; return id ? ptr : NULL; } #ifdef WITH_XML void LoadPrimarySection(const TiXmlElement* xml, primary_t & skill) { if(!xml) return; int value; xml->Attribute("attack", &value); skill.attack = value; xml->Attribute("defense", &value); skill.defense = value; xml->Attribute("power", &value); skill.power = value; xml->Attribute("knowledge", &value); skill.knowledge = value; } void LoadSecondarySection(const TiXmlElement* xml, secondary_t & sec) { if(!xml) return; int value; xml->Attribute("archery", &value); sec.archery = value; xml->Attribute("ballistics", &value); sec.ballistics = value; xml->Attribute("diplomacy", &value); sec.diplomacy = value; xml->Attribute("eagleeye", &value); sec.eagleeye = value; xml->Attribute("estates", &value); sec.estates = value; xml->Attribute("leadership", &value); sec.leadership = value; xml->Attribute("logistics", &value); sec.logistics = value; xml->Attribute("luck", &value); sec.luck = value; xml->Attribute("mysticism", &value); sec.mysticism = value; xml->Attribute("navigation", &value); sec.navigation = value; xml->Attribute("necromancy", &value); sec.necromancy = value; xml->Attribute("pathfinding", &value); sec.pathfinding = value; xml->Attribute("scouting", &value); sec.scouting = value; xml->Attribute("wisdom", &value); sec.wisdom = value; } #endif void Skill::UpdateStats(const std::string & spec) { #ifdef WITH_XML // parse skills.xml TiXmlDocument doc; const TiXmlElement* xml_skills = NULL; if(doc.LoadFile(spec.c_str()) && NULL != (xml_skills = doc.FirstChildElement("skills"))) { const TiXmlElement* xml_captain = xml_skills->FirstChildElement("captain"); const TiXmlElement* xml_initial = xml_skills->FirstChildElement("initial"); const TiXmlElement* xml_maturity = xml_skills->FirstChildElement("maturity"); const TiXmlElement* xml_secondary = xml_maturity ? xml_maturity->FirstChildElement("secondary") : NULL; const TiXmlElement* xml_primary = xml_maturity ? xml_maturity->FirstChildElement("primary") : NULL; const TiXmlElement* xml_under = xml_primary ? xml_primary->FirstChildElement("under") : NULL; const TiXmlElement* xml_over = xml_primary ? xml_primary->FirstChildElement("over") : NULL; skillstats_t *ptr = &_skillstats[0]; int value; while(ptr->id) { const TiXmlElement* initial_race = xml_initial ? xml_initial->FirstChildElement(ptr->id) : NULL; if(initial_race) { LoadPrimarySection(initial_race, ptr->initial_primary); LoadSecondarySection(initial_race, ptr->initial_secondary); initial_race->Attribute("book", &value); ptr->initial_book = value; initial_race->Attribute("spell", &value); ptr->initial_spell = value; } const TiXmlElement* captain_race = xml_captain ? xml_captain->FirstChildElement(ptr->id) : NULL; if(captain_race) LoadPrimarySection(captain_race, ptr->captain_primary); const TiXmlElement* under_race = xml_under ? xml_under->FirstChildElement(ptr->id) : NULL; if(under_race) LoadPrimarySection(under_race, ptr->mature_primary_under); const TiXmlElement* over_race = xml_over ? xml_over->FirstChildElement(ptr->id) : NULL; if(over_race) { LoadPrimarySection(over_race, ptr->mature_primary_over); over_race->Attribute("level", &value); if(value) ptr->over_level = value; } const TiXmlElement* secondary_race = xml_secondary ? xml_secondary->FirstChildElement(ptr->id) : NULL; if(secondary_race) LoadSecondarySection(secondary_race, ptr->mature_secondary); ++ptr; } xml_secondary = xml_skills->FirstChildElement("secondary"); if(xml_secondary) { skillvalues_t* ptr2 = &_skillvalues[0]; while(ptr2->id) { const TiXmlElement* xml_sec = xml_secondary->FirstChildElement(ptr2->id); if(xml_sec) { xml_sec->Attribute("basic", &value); ptr2->values.basic = value; xml_sec->Attribute("advanced", &value); ptr2->values.advanced = value; xml_sec->Attribute("expert", &value); ptr2->values.expert = value; } ++ptr2; } } const TiXmlElement* xml_witchs_hut = xml_skills->FirstChildElement("witchs_hut"); if(xml_witchs_hut) LoadSecondarySection(xml_witchs_hut, _from_witchs_hut); } else VERBOSE(spec << ": " << doc.ErrorDesc()); #endif } u16 Skill::Secondary::GetValues(void) const { switch(Level()) { case Level::BASIC: return _skillvalues[Skill() - 1].values.basic; case Level::ADVANCED: return _skillvalues[Skill() - 1].values.advanced; case Level::EXPERT: return _skillvalues[Skill() - 1].values.expert; default: break; } return 0; } Skill::Primary::Primary() : attack(0), defense(0), power(0), knowledge(0) { } void Skill::Primary::LoadDefaults(u8 type, u8 race) { const skillstats_t* ptr = GetSkillStats(race); if(ptr) switch(type) { case CAPTAIN: attack = ptr->captain_primary.attack; defense = ptr->captain_primary.defense; power = ptr->captain_primary.power; knowledge = ptr->captain_primary.knowledge; break; case HEROES: attack = ptr->initial_primary.attack; defense = ptr->initial_primary.defense; power = ptr->initial_primary.power; knowledge = ptr->initial_primary.knowledge; break; default: break; } } u8 Skill::Primary::GetInitialSpell(u8 race) { const skillstats_t* ptr = GetSkillStats(race); return ptr ? ptr->initial_spell : 0; } u8 Skill::Primary::LevelUp(u8 race, u8 level) { Rand::Queue percents(MAXPRIMARYSKILL); const skillstats_t* ptr = GetSkillStats(race); if(ptr) { if(ptr->over_level > level) { percents.Push(ATTACK, ptr->mature_primary_under.attack); percents.Push(DEFENSE, ptr->mature_primary_under.defense); percents.Push(POWER, ptr->mature_primary_under.power); percents.Push(KNOWLEDGE, ptr->mature_primary_under.knowledge); } else { percents.Push(ATTACK, ptr->mature_primary_over.attack); percents.Push(DEFENSE, ptr->mature_primary_over.defense); percents.Push(POWER, ptr->mature_primary_over.power); percents.Push(KNOWLEDGE, ptr->mature_primary_over.knowledge); } } u8 result = percents.Size() ? percents.Get() : UNKNOWN; switch(result) { case ATTACK: ++attack; break; case DEFENSE: ++defense; break; case POWER: ++power; break; case KNOWLEDGE: ++knowledge; break; default: break; } return result; } const char* Skill::Primary::String(u8 skill) { const char* str_skill[] = { _("Attack"), _("Defense"), _("Power"), _("Knowledge"), "Unknown" }; switch(skill) { case ATTACK: return str_skill[0]; case DEFENSE: return str_skill[1]; case POWER: return str_skill[2]; case KNOWLEDGE: return str_skill[3]; default: break; } return str_skill[4]; } const char* Skill::Level::String(u8 level) { const char* str_level[] = { "None", _("skill|Basic"), _("skill|Advanced"), _("skill|Expert") }; switch(level) { case BASIC: return str_level[1]; case ADVANCED: return str_level[2]; case EXPERT: return str_level[3]; default: break; } return str_level[0]; } Skill::Secondary::Secondary() : std::pair<u8, u8>(UNKNOWN, Level::NONE) { } Skill::Secondary::Secondary(u8 skill, u8 level) : std::pair<u8, u8>(UNKNOWN, Level::NONE) { SetSkill(skill); SetLevel(level); } void Skill::Secondary::Reset(void) { first = UNKNOWN; second = Level::NONE; } void Skill::Secondary::Set(const Secondary & skill) { first = skill.first; second = skill.second; } void Skill::Secondary::SetSkill(u8 skill) { first = skill <= ESTATES ? skill : UNKNOWN; } void Skill::Secondary::SetLevel(u8 level) { second = level <= Level::EXPERT ? level : Level::NONE; } void Skill::Secondary::NextLevel(void) { switch(second) { case Level::NONE: second = Level::BASIC; break; case Level::BASIC: second = Level::ADVANCED; break; case Level::ADVANCED: second = Level::EXPERT; break; default: break; } } u8 Skill::Secondary::Skill(void) const { return first; } u8 Skill::Secondary::Level(void) const { return second; } bool Skill::Secondary::isLevel(u8 level) const { return level == second; } bool Skill::Secondary::isSkill(u8 skill) const { return skill == first; } bool Skill::Secondary::isValid(void) const { return Skill() != UNKNOWN && Level() != Level::NONE; } u8 Skill::Secondary::RandForWitchsHut(void) { std::vector<u8> v; v.reserve(14); if(_from_witchs_hut.archery) v.push_back(ARCHERY); if(_from_witchs_hut.ballistics) v.push_back(BALLISTICS); if(_from_witchs_hut.diplomacy) v.push_back(DIPLOMACY); if(_from_witchs_hut.eagleeye) v.push_back(EAGLEEYE); if(_from_witchs_hut.estates) v.push_back(ESTATES); if(_from_witchs_hut.leadership) v.push_back(LEADERSHIP); if(_from_witchs_hut.logistics) v.push_back(LOGISTICS); if(_from_witchs_hut.luck) v.push_back(LUCK); if(_from_witchs_hut.mysticism) v.push_back(MYSTICISM); if(_from_witchs_hut.navigation) v.push_back(NAVIGATION); if(_from_witchs_hut.necromancy) v.push_back(NECROMANCY); if(_from_witchs_hut.pathfinding) v.push_back(PATHFINDING); if(_from_witchs_hut.scouting) v.push_back(SCOUTING); if(_from_witchs_hut.wisdom) v.push_back(WISDOM); return v.empty() ? UNKNOWN : *Rand::Get(v); } /* index sprite from SECSKILL */ u8 Skill::Secondary::GetIndexSprite1(void) const { return Skill() <= ESTATES ? Skill() : 0; } /* index sprite from MINISS */ u8 Skill::Secondary::GetIndexSprite2(void) const { return Skill() <= ESTATES ? Skill() - 1 : 0xFF; } const char* Skill::Secondary::String(u8 skill) { const char* str_skill[] = { _("Pathfinding"), _("Archery"), _("Logistics"), _("Scouting"), _("Diplomacy"), _("Navigation"), _("Leadership"), _("Wisdom"), _("Mysticism"), _("Luck"), _("Ballistics"), _("Eagle Eye"), _("Necromancy"), _("Estates"), "Unknown" }; switch(skill) { case PATHFINDING: return str_skill[0]; case ARCHERY: return str_skill[1]; case LOGISTICS: return str_skill[2]; case SCOUTING: return str_skill[3]; case DIPLOMACY: return str_skill[4]; case NAVIGATION: return str_skill[5]; case LEADERSHIP: return str_skill[6]; case WISDOM: return str_skill[7]; case MYSTICISM: return str_skill[8]; case LUCK: return str_skill[9]; case BALLISTICS: return str_skill[10]; case EAGLEEYE: return str_skill[11]; case NECROMANCY: return str_skill[12]; case ESTATES: return str_skill[13]; default: break; } return str_skill[14]; } const char* Skill::Secondary::GetName(void) const { const char* name_skill[] = { _("Basic Pathfinding"), _("Advanced Pathfinding"), _("Expert Pathfinding"), _("Basic Archery"), _("Advanced Archery"), _("Expert Archery"), _("Basic Logistics"), _("Advanced Logistics"), _("Expert Logistics"), _("Basic Scouting"), _("Advanced Scouting"), _("Expert Scouting"), _("Basic Diplomacy"), _("Advanced Diplomacy"), _("Expert Diplomacy"), _("Basic Navigation"),_("Advanced Navigation"), _("Expert Navigation"), _("Basic Leadership"), _("Advanced Leadership"), _("Expert Leadership"), _("Basic Wisdom"), _("Advanced Wisdom"), _("Expert Wisdom"), _("Basic Mysticism"), _("Advanced Mysticism"), _("Expert Mysticism"), _("Basic Luck"), _("Advanced Luck"), _("Expert Luck"), _("Basic Ballistics"), _("Advanced Ballistics"), _("Expert Ballistics"), _("Basic Eagle Eye"), _("Advanced Eagle Eye"), _("Expert Eagle Eye"), _("Basic Necromancy"), _("Advanced Necromancy"), _("Expert Necromancy"), _("Basic Estates"), _("Advanced Estates"), _("Expert Estates") }; return isValid() ? name_skill[(Level() - 1) + (Skill() - 1) * 3] : "unknown"; } std::string Skill::Secondary::GetDescription(void) const { const u16 count = GetValues(); std::string str = "unknown"; switch(Skill()) { case PATHFINDING: str = ngettext("Reduces the movement penalty for rough terrain by %{count} percent.", "Reduces the movement penalty for rough terrain by %{count} percent.", count); break; case ARCHERY: str = ngettext("Increases the damage done by range attacking creatures by %{count} percent.", "Increases the damage done by range attacking creatures by %{count} percent.", count); break; case LOGISTICS: str = ngettext("Increases your hero's movement points by %{count} percent.", "Increases your hero's movement points by %{count} percent.", count); break; case SCOUTING: str = ngettext("Increases your hero's viewable area by %{count} square.", "Increases your hero's viewable area by %{count} squares.", count); break; case DIPLOMACY: str = _("Allows you to negotiate with monsters who are weaker than your group."); str.append(" "); str.append(ngettext("Approximately %{count} percent of the creatures may offer to join you.", "Approximately %{count} percent of the creatures may offer to join you.", count)); break; case NAVIGATION: str = ngettext("Increases your hero's movement points over water by %{count} percent.", "Increases your hero's movement points over water by %{count} percent.", count); break; case LEADERSHIP: str = ngettext("Increases your hero's troops' morale by %{count}.", "Increases your hero's troops' morale by %{count}.", count); break; case WISDOM: { switch(Level()) { case Level::BASIC: str = _("Allows your hero to learn third level spells."); break; case Level::ADVANCED: str = _("Allows your hero to learn fourth level spells."); break; case Level::EXPERT: str = _("Allows your hero to learn fifth level spells."); break; default: break; } break; } case MYSTICISM: str = ngettext("Regenerates %{count} of your hero's spell point per day.", "Regenerates %{count} of your hero's spell points per day.", count); break; case LUCK: str = ngettext("Increases your hero's luck by %{count}.", "Increases your hero's luck by %{count}.", count); break; case BALLISTICS: switch(Level()) { case Level::BASIC: str = _("Gives your hero's catapult shots a greater chance to hit and do damage to castle walls."); break; case Level::ADVANCED: str = _("Gives your hero's catapult an extra shot, and each shot has a greater chance to hit and do damage to castle walls."); break; case Level::EXPERT: str = _("Gives your hero's catapult an extra shot, and each shot automatically destroys any wall, except a fortified wall in a Knight town."); break; default: break; } break; case EAGLEEYE: switch(Level()) { case Level::BASIC: str = ngettext("Gives your hero a %{count} percent chance to learn any given 1st or 2nd level enemy spell used against him in a combat.", "Gives your hero a %{count} percent chance to learn any given 1st or 2nd level enemy spell used against him in a combat.", count); break; case Level::ADVANCED: str = ngettext("Gives your hero a %{count} percent chance to learn any given 3rd level spell (or below) used against him in combat.", "Gives your hero a %{count} percent chance to learn any given 3rd level spell (or below) used against him in combat.", count); break; case Level::EXPERT: str = ngettext("Gives your hero a %{count} percent chance to learn any given 4th level spell (or below) used against him in combat.", "Gives your hero a %{count} percent chance to learn any given 4th level spell (or below) used against him in combat.", count); break; default: break; } break; case NECROMANCY: str = ngettext("Allows %{count} percent of the creatures killed in combat to be brought back from the dead as Skeletons.", "Allows %{count} percent of the creatures killed in combat to be brought back from the dead as Skeletons.", count); break; case ESTATES: str = ngettext("Your hero produce %{count} gold pieces per turn as tax revenue from estates.", "Your hero produces %{count} gold pieces per turn as tax revenue from estates.", count); break; default: break; } String::Replace(str, "%{count}", count); return str; } Skill::SecSkills::SecSkills() { reserve(HEROESMAXSKILL); } Skill::SecSkills::SecSkills(u8 race) { reserve(HEROESMAXSKILL); if(race & Race::ALL) { const skillstats_t* ptr = GetSkillStats(race); if(ptr) { if(ptr->initial_secondary.archery) push_back(Secondary(Secondary::ARCHERY, ptr->initial_secondary.archery)); if(ptr->initial_secondary.ballistics) push_back(Secondary(Secondary::BALLISTICS, ptr->initial_secondary.ballistics)); if(ptr->initial_secondary.diplomacy) push_back(Secondary(Secondary::DIPLOMACY, ptr->initial_secondary.diplomacy)); if(ptr->initial_secondary.eagleeye) push_back(Secondary(Secondary::EAGLEEYE, ptr->initial_secondary.eagleeye)); if(ptr->initial_secondary.estates) push_back(Secondary(Secondary::ESTATES, ptr->initial_secondary.estates)); if(ptr->initial_secondary.leadership) push_back(Secondary(Secondary::LEADERSHIP, ptr->initial_secondary.leadership)); if(ptr->initial_secondary.logistics) push_back(Secondary(Secondary::LOGISTICS, ptr->initial_secondary.logistics)); if(ptr->initial_secondary.luck) push_back(Secondary(Secondary::LUCK, ptr->initial_secondary.luck)); if(ptr->initial_secondary.mysticism) push_back(Secondary(Secondary::MYSTICISM, ptr->initial_secondary.mysticism)); if(ptr->initial_secondary.navigation) push_back(Secondary(Secondary::NAVIGATION, ptr->initial_secondary.navigation)); if(ptr->initial_secondary.necromancy) push_back(Secondary(Secondary::NECROMANCY, ptr->initial_secondary.necromancy)); if(ptr->initial_secondary.pathfinding) push_back(Secondary(Secondary::PATHFINDING, ptr->initial_secondary.pathfinding)); if(ptr->initial_secondary.scouting) push_back(Secondary(Secondary::SCOUTING, ptr->initial_secondary.scouting)); if(ptr->initial_secondary.wisdom) push_back(Secondary(Secondary::WISDOM, ptr->initial_secondary.wisdom)); } } } void Skill::SecSkills::ReadFromMP2(const u8* ptr) { clear(); for(u8 ii = 0; ii < 8; ++ii) { Skill::Secondary skill(*(ptr + ii) + 1, *(ptr + ii + 8)); if(skill.isValid()) push_back(skill); } } u8 Skill::SecSkills::GetLevel(u8 skill) const { const_iterator it = std::find_if(begin(), end(), std::bind2nd(std::mem_fun_ref(&Secondary::isSkill), skill)); return it == end() ? Level::NONE : (*it).Level(); } u16 Skill::SecSkills::GetValues(u8 skill) const { const_iterator it = std::find_if(begin(), end(), std::bind2nd(std::mem_fun_ref(&Secondary::isSkill), skill)); return it == end() ? 0 : (*it).GetValues(); } void Skill::SecSkills::AddSkill(const Skill::Secondary & skill) { iterator it = std::find_if(begin(), end(), std::bind2nd(std::mem_fun_ref(&Secondary::isSkill), skill.Skill())); if(it != end()) (*it).SetLevel(skill.Level()); else { it = std::find_if(begin(), end(), std::not1(std::mem_fun_ref(&Secondary::isValid))); if(it != end()) (*it).Set(skill); else push_back(skill); } } std::string Skill::SecSkills::String(void) const { std::ostringstream os; for(const_iterator it = begin(); it != end(); ++it) os << (*it).GetName() << ", "; return os.str(); } u8 Skill::SecondaryGetWeightSkillFromRace(u8 race, u8 skill) { const skillstats_t* ptr = GetSkillStats(race); if(ptr) { if(skill == Secondary::PATHFINDING) return ptr->mature_secondary.pathfinding; else if(skill == Secondary::ARCHERY) return ptr->mature_secondary.archery; else if(skill == Secondary::LOGISTICS) return ptr->mature_secondary.logistics; else if(skill == Secondary::SCOUTING) return ptr->mature_secondary.scouting; else if(skill == Secondary::DIPLOMACY) return ptr->mature_secondary.diplomacy; else if(skill == Secondary::NAVIGATION) return ptr->mature_secondary.navigation; else if(skill == Secondary::LEADERSHIP) return ptr->mature_secondary.leadership; else if(skill == Secondary::WISDOM) return ptr->mature_secondary.wisdom; else if(skill == Secondary::MYSTICISM) return ptr->mature_secondary.mysticism; else if(skill == Secondary::LUCK) return ptr->mature_secondary.luck; else if(skill == Secondary::BALLISTICS) return ptr->mature_secondary.ballistics; else if(skill == Secondary::EAGLEEYE) return ptr->mature_secondary.eagleeye; else if(skill == Secondary::NECROMANCY) return ptr->mature_secondary.necromancy; else if(skill == Secondary::ESTATES) return ptr->mature_secondary.estates; } return 0; } std::vector<u8> Skill::SecondarySkills(void) { const u8 vals[] = { Secondary::PATHFINDING, Secondary::ARCHERY, Secondary::LOGISTICS, Secondary::SCOUTING, Secondary::DIPLOMACY, Secondary::NAVIGATION, Secondary::LEADERSHIP, Secondary::WISDOM, Secondary::MYSTICISM, Secondary::LUCK, Secondary::BALLISTICS, Secondary::EAGLEEYE, Secondary::NECROMANCY, Secondary::ESTATES }; return std::vector<u8>(vals, ARRAY_COUNT_END(vals)); } u8 Skill::SecondaryPriorityFromRace(u8 race, const std::vector<u8> & exclude) { Rand::Queue parts(MAXSECONDARYSKILL); std::vector<u8> skills = SecondarySkills(); for(std::vector<u8>::const_iterator it = skills.begin(); it != skills.end(); ++it) if(exclude.empty() || exclude.end() == std::find(exclude.begin(), exclude.end(), *it)) parts.Push(*it, SecondaryGetWeightSkillFromRace(race, *it)); return parts.Size() ? parts.Get() : Secondary::UNKNOWN; } /* select secondary skills for level up */ void Skill::SecSkills::FindSkillsForLevelUp(u8 race, Secondary & sec1, Secondary & sec2) const { std::vector<u8> exclude_skills; exclude_skills.reserve(MAXSECONDARYSKILL + HEROESMAXSKILL); // exclude for expert { for(const_iterator it = begin(); it != end(); ++it) if((*it).Level() == Level::EXPERT) exclude_skills.push_back((*it).Skill()); } // exclude is full, add other. if(HEROESMAXSKILL <= size()) { std::vector<u8> skills = SecondarySkills(); for(std::vector<u8>::const_iterator it = skills.begin(); it != skills.end(); ++it) if(Level::NONE == GetLevel(*it)) exclude_skills.push_back(*it); } sec1.SetSkill(SecondaryPriorityFromRace(race, exclude_skills)); if(Secondary::UNKNOWN != sec1.Skill()) { exclude_skills.push_back(sec1.Skill()); sec2.SetSkill(SecondaryPriorityFromRace(race, exclude_skills)); sec1.SetLevel(GetLevel(sec1.Skill())); sec2.SetLevel(GetLevel(sec2.Skill())); sec1.NextLevel(); sec2.NextLevel(); } else if(Settings::Get().ExtHeroAllowBannedSecSkillsUpgrade()) { const_iterator it = std::find_if(begin(), end(), std::not1(std::bind2nd(std::mem_fun_ref(&Secondary::isLevel), Level::EXPERT))); if(it != end()) { sec1.SetSkill((*it).Skill()); sec1.SetLevel(GetLevel(sec1.Skill())); sec1.NextLevel(); } } } SecondarySkillBar::SecondarySkillBar() : skills(NULL), use_mini_sprite(false), can_change(false) { } const Rect & SecondarySkillBar::GetArea(void) const { return pos; } void SecondarySkillBar::SetSkills(Skill::SecSkills & v) { skills = &v; CalcSize(); } void SecondarySkillBar::SetUseMiniSprite(void) { use_mini_sprite = true; } void SecondarySkillBar::SetInterval(u8 i) { interval = i; CalcSize(); } void SecondarySkillBar::SetPos(s16 sx, s16 sy) { pos.x = sx; pos.y = sy; CalcSize(); } void SecondarySkillBar::SetChangeMode(void) { can_change = true; } void SecondarySkillBar::CalcSize(void) { pos.w = 0; pos.h = 0; if(skills) { const Sprite & sprite = AGG::GetICN((use_mini_sprite ? ICN::MINISS : ICN::SECSKILL), 0); pos.h = sprite.h(); pos.w = HEROESMAXSKILL * (sprite.w() + interval); } } void SecondarySkillBar::Redraw(void) { Point dst_pt(pos); Text text; text.Set(Font::SMALL); for(u8 ii = 0; ii < HEROESMAXSKILL; ++ii) { const Skill::Secondary & skill = ii < skills->size() ? skills->at(ii) : Skill::Secondary(); if(skill.isValid()) { const Sprite & sprite_skill = AGG::GetICN((use_mini_sprite ? ICN::MINISS : ICN::SECSKILL), (use_mini_sprite ? skill.GetIndexSprite2() : skill.GetIndexSprite1())); sprite_skill.Blit(dst_pt); if(use_mini_sprite) { text.Set(GetString(skill.Level())); text.Blit(dst_pt.x + (sprite_skill.w() - text.w()) - 3, dst_pt.y + sprite_skill.h() - 12); } else { text.Set(Skill::Secondary::String(skill.Skill())); text.Blit(dst_pt.x + (sprite_skill.w() - text.w()) / 2, dst_pt.y + 3); text.Set(Skill::Level::String(skill.Level())); text.Blit(dst_pt.x + (sprite_skill.w() - text.w()) / 2, dst_pt.y + 50); } dst_pt.x += (use_mini_sprite ? 32 : sprite_skill.w()) + interval; } else { const Sprite & sprite_skill = AGG::GetICN((use_mini_sprite ? ICN::HSICONS : ICN::SECSKILL), 0); if(use_mini_sprite) sprite_skill.Blit(Rect((sprite_skill.w() - 32) / 2, 20, 32, 32), dst_pt); else sprite_skill.Blit(dst_pt); dst_pt.x += (use_mini_sprite ? 32 : sprite_skill.w()) + interval; } } } u8 SecondarySkillBar::GetIndexFromCoord(const Point & cu) { const Sprite & sprite_skill = AGG::GetICN((use_mini_sprite ? ICN::MINISS : ICN::SECSKILL), 0); return (pos & cu) ? (cu.x - pos.x) / (sprite_skill.w() + interval) : 0; } bool SecondarySkillBar::QueueEventProcessing(void) { Display & display = Display::Get(); Cursor & cursor = Cursor::Get(); LocalEvent & le = LocalEvent::Get(); const Point & cu = le.GetMouseCursor(); bool modify = false; if(!(pos & cu) || !skills) return false; u8 ii = GetIndexFromCoord(cu); const Sprite & sprite_skill = AGG::GetICN((use_mini_sprite ? ICN::MINISS : ICN::SECSKILL), 0); const Rect tile(pos.x + (ii * (sprite_skill.w() + interval)), pos.y, sprite_skill.w(), sprite_skill.h()); if(ii < skills->size()) { Skill::Secondary & skill = skills->at(ii); if(skill.isValid()) { if(le.MouseClickLeft(tile)) { cursor.Hide(); Dialog::SecondarySkillInfo(skill, true); cursor.Show(); display.Flip(); } else if(le.MousePressRight(tile)) { if(can_change) { skill.Reset(); modify = true; } else { cursor.Hide(); Dialog::SecondarySkillInfo(skill, false); cursor.Show(); display.Flip(); } } } } else if(ii < MAXSECONDARYSKILL) { if(can_change && le.MouseClickLeft(tile)) { Skill::Secondary alt = Dialog::SelectSecondarySkill(); if(alt.isValid() && skills) { skills->AddSkill(alt); modify = true; } } } return modify; } void StringAppendModifiers(std::string & str, s8 value) { if(value < 0) str.append(" "); // '-' present else if(value > 0) str.append(" +"); str.append(GetString(value)); } s8 Skill::GetLeadershipModifiers(u8 level, std::string* strs = NULL) { Secondary skill(Secondary::LEADERSHIP, level); if(skill.GetValues() && strs) { strs->append(skill.GetName()); StringAppendModifiers(*strs, skill.GetValues()); strs->append("\n"); } return skill.GetValues(); } s8 Skill::GetLuckModifiers(u8 level, std::string* strs = NULL) { Secondary skill(Secondary::LUCK, level); if(skill.GetValues() && strs) { strs->append(skill.GetName()); StringAppendModifiers(*strs, skill.GetValues()); strs->append("\n"); } return skill.GetValues(); } StreamBase & Skill::operator<< (StreamBase & msg, const Primary & skill) { return msg << skill.attack << skill.defense << skill.knowledge << skill.power; } StreamBase & Skill::operator>> (StreamBase & msg, Primary & skill) { return msg >> skill.attack >> skill.defense >> skill.knowledge >> skill.power; }
6dc70122b93f8cc564e2f5c01226f7c43f728a8d
76cceb3e5d356a84f65a36e337babde906b46d4e
/src/AttractionClass.h
40906e9240d98a3568386931be066fa12a467a56
[]
no_license
shiyaowww/Event_driven_theme_park_scheme
edb754de71f79c33236b51706123dfd825d4f891
87789fe180c05a9a11684680d86e5ea5c48458de
refs/heads/master
2022-12-22T18:37:49.150545
2020-09-22T20:07:25
2020-09-22T20:07:25
296,473,935
0
0
null
null
null
null
UTF-8
C++
false
false
979
h
AttractionClass.h
#ifndef _ATTRACTIONCLASS_H_ #define _ATTRACTIONCLASS_H_ #include <iostream> #include <fstream> #include <string> #include "constants.h" #include "CustomerClass.h" using namespace std; //Created by: Shiyao Wang //Date: April 10, 2020 //Purpose: This attraction class will be the data type for an attraction //which gives customers ride. class AttractionClass { private: string attractionName; int numSeats; int numIdealSeats[NUM_LINES]; public: //Default ctor that initializes attributes to default AttractionClass(); //Set numIdealSeats[NUM_LINES] with infile stream void setNumIdealSeats( ifstream &inFile); //Calculate numbers of customers from each priority level boarding //the car and returns the percentage of seats filled int loadCar( int numInLine[], int numBoard[]); //Gets the attraction name string getName() const; //Gets the number of seats int getNumSeats() const; }; #endif
c137766519a9ace2dd09664c303f3274f8f0458e
1cdbd26216487be7103b346987a142f9a6571c9f
/23-05-2021/closestPalindrome.cpp
7f0145df4779e843c9ecd81e393126c68d857896
[]
no_license
Thambidurai-Mahendran/Edabit
43dc39085a6ab465cdf6f929f66034ddf1f3acee
14f6d71acb0d655170089f31f241e5e8b4db00f3
refs/heads/main
2023-05-25T03:24:45.490511
2021-06-10T15:05:54
2021-06-10T15:05:54
366,587,238
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
closestPalindrome.cpp
/* Write a function that returns the closest palindrome number to an integer. If two palindrome numbers tie in absolute distance, return the smaller number. Examples closestPalindrome(887) ? 888 closestPalindrome(100) ? 99 // 99 and 101 are equally distant, so we return the smaller palindrome. closestPalindrome(888) ? 888 closestPalindrome(27) ? 22 */ #include<string> int closestPalindrome(int n) { int m=n; while(1) { //we check the num is palindrome or not in decreasing order. if(m>0) { std::string isPalindrome=std::to_string(m); reverse(isPalindrome.begin(),isPalindrome.end()); if(isPalindrome==std::to_string(m)) return m; m--; } //we check the num is palindrome or not in increasing order std::string isPalindrome=std::to_string(n); reverse(isPalindrome.begin(),isPalindrome.end()); if(isPalindrome==std::to_string(n)) return n; n++; } }
fd20c33df278bf76383361891b23e126fd1431aa
2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac
/HDU/1498/7717168_AC_46ms_1472kB.cpp
f6338ba13b5fb0133e4889467f85d3b3405a8b24
[]
no_license
weakmale/hhabb
9e28b1f2ed34be1ecede5b34dc2d2f62588a5528
649f0d2b5796ec10580428d16921879aa380e1f2
refs/heads/master
2021-01-01T20:19:08.062232
2017-07-30T17:23:21
2017-07-30T17:23:21
98,811,298
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
cpp
7717168_AC_46ms_1472kB.cpp
#include "cstdio" #include "vector" #include "cstring" using namespace std; int Map[111][111]; bool coler[55]; bool Mp[111][111]; bool l[111]; int c[111]; int n,k; bool DFS(int u){ for(int i=1;i<=n;i++){ if(Mp[u][i]&&!l[i]){ l[i]=true; if(!c[i]||DFS(c[i])){ c[i]=u; return true; } } } return false; } int main(){ while(scanf("%d %d",&n,&k),n||k){ memset(coler,false,sizeof(coler)); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ scanf("%d",&Map[i][j]); coler[Map[i][j]]=true; } } bool m=false; for(int t=1;t<=50;t++){ if(coler[t]){ memset(Mp, false, sizeof(Mp)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(Map[i][j]==t) Mp[i][j]=true; int sum=0; memset(c, 0, sizeof(c)); for(int i=1;i<=n;i++){ memset(l, false, sizeof(l)); sum+=DFS(i); } if(sum>k){ if(!m) printf("%d",t),m=true; else printf(" %d",t); } } } if(!m) printf("-1"); puts(""); } return 0; }
69d5d64afd910b6f9b03c0f920a2a0d2e86c6d90
da90cd5855d6397969e2ed88551f0d9491b37065
/framework/Mesh.cpp
7aef6041e534337c196704cd98d9ec9a2f7e3b25
[]
no_license
gianei/GraphicsAssessmentLincoln
9cb0931d7c83048a2c62b9611689008d0b3a4817
8c0898d0e49d71ab551c1f3b06428cd52c43a615
refs/heads/master
2016-09-03T07:12:54.485999
2014-11-24T13:30:46
2014-11-24T13:30:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,348
cpp
Mesh.cpp
#pragma comment(lib, "glew32.lib") #pragma comment(lib, "opengl32.lib") #include "Mesh.h" using namespace glm; using namespace std; Mesh::Mesh(ShaderProgram *shader){ scale = 1; rotationMatrix = mat4(1.0f); this->shader = *shader; } Mesh::Mesh(ShaderProgram *shader, MeshData *data){ scale = 1; rotationMatrix = mat4(1.0f); this->shader = *shader; LoadData(); } Mesh::~Mesh(void){ shader.~ShaderProgram(); } void Mesh::AddVertex(vec3 vertex){ vertices.push_back(vertex); } void Mesh::AddNormal(vec3 normal){ normals.push_back(normal); } void Mesh::AddTexCoord(vec2 texCoord){ texUVs.push_back(texCoord); } void Mesh::AddColor(vec4 color){ colors.push_back(color); } void Mesh::AddIndex(GLuint index){ indices.push_back(index); } void Mesh::AddIndexes(int count, GLuint *index){ indices.insert(indices.end(), index, index + count - 1); } void Mesh::LoadData(void){ int unitCounter = data.data.size(); for (int i = 0; i < unitCounter; i++) { vertices.push_back(data.data[i].position); if (data.data[i].normal != vec3(0, 0, 0)) normals.push_back(data.data[i].normal); if (data.data[i].texCoord != vec2(-1, -1)) texUVs.push_back(data.data[i].texCoord); } int indexCounter = data.indices.size(); for (int i = 0; i < indexCounter; i++) indices.push_back(data.indices[i]); } void Mesh::LoadArrayBuffer(GLint buffer, vector<vec2> data){ glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(data), &data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Mesh::LoadArrayBuffer(GLint buffer, vector<vec3> data){ glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(data), &data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Mesh::LoadArrayBuffer(GLint buffer, vector<vec4> data){ glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(data), &data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Mesh::LoadIndexer(GLint buffer, vector<GLuint> indexer){ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexer), &indexer, GL_STATIC_DRAW); } void Mesh::SetUp(void){ GLint bufferCounter = 1; if (colors.size() > 0) { bufferCounter++; hasColor = true; } if (normals.size() > 0) { bufferCounter++; hasNormals = true; } if (texUVs.size() > 0) { bufferCounter++; hasUVs = true; } if (indices.size() > 0) { bufferCounter++; isIndexed = true; } glGenBuffers(bufferCounter, buffers); LoadArrayBuffer(buffers[0], vertices); vertexCounter = vertices.size(); GLint buffersUsed = 1; if (hasColor) { colorBuffer = buffersUsed; LoadArrayBuffer(buffers[colorBuffer], colors); buffersUsed++; } if (hasNormals) { normalBuffer = buffersUsed; LoadArrayBuffer(buffers[normalBuffer], normals); buffersUsed++; } if (hasUVs) { UVbuffer = buffersUsed; LoadArrayBuffer(buffers[UVbuffer], texUVs); buffersUsed++; } if (isIndexed) { indexBuffer = buffersUsed; LoadIndexer(buffers[indexBuffer], indices); indexCounter = indices.size(); } glGenVertexArrays(1, &meshID); //glBindVertexArray(meshID); } ShaderProgram Mesh::Shader(void){ return shader; } vec3 Mesh::Position(void){ return position; } void Mesh::Position(vec3 position){ this->position = position; } GLfloat Mesh::Scale(void){ return scale; } void Mesh::Scale(GLfloat scale){ this->scale = scale; } mat4 Mesh::ModelMatrix(void){ return glm::translate(position) * glm::scale(vec3(scale, scale, scale)) * rotationMatrix; } void Mesh::BindAllBuffers(void){ glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); glVertexAttribPointer(ARRAYINDEX_VERTEXPOSITION, 3, GL_FLOAT, GL_FALSE, 0, 0); if (hasColor) { glBindBuffer(GL_ARRAY_BUFFER, buffers[colorBuffer]); glVertexAttribPointer(ARRAYINDEX_VERTEXCOLOR, 4, GL_FLOAT, GL_FALSE, 0, 0); } if (hasNormals) { glBindBuffer(GL_ARRAY_BUFFER, buffers[normalBuffer]); glVertexAttribPointer(ARRAYINDEX_VERTEXNORMAL, 3, GL_FLOAT, GL_FALSE, 0, 0); } if (hasUVs) { glBindBuffer(GL_ARRAY_BUFFER, buffers[UVbuffer]); glVertexAttribPointer(ARRAYINDEX_VERTEXTEXTUREUV, 2, GL_FLOAT, GL_FALSE, 0, 0); } if (isIndexed) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[indexBuffer]); } void Mesh::Update(GLfloat deltaTime){ } void Mesh::Draw(void){ shader.SetVariable(NAMEOF_MODELMATRIX, ModelMatrix()); shader.Activate(); glBindVertexArray(meshID); BindAllBuffers(); glEnableVertexAttribArray(ARRAYINDEX_VERTEXPOSITION); if (hasColor) glEnableVertexAttribArray(ARRAYINDEX_VERTEXCOLOR); if (hasNormals) glEnableVertexAttribArray(ARRAYINDEX_VERTEXNORMAL); if (hasUVs) glEnableVertexAttribArray(ARRAYINDEX_VERTEXTEXTUREUV); if (isIndexed) glDrawElements(GL_TRIANGLES, indexCounter, GL_UNSIGNED_INT, 0); else glDrawArrays(GL_TRIANGLES, 0, vertexCounter); glDisableVertexAttribArray(ARRAYINDEX_VERTEXPOSITION); glDisableVertexAttribArray(ARRAYINDEX_VERTEXCOLOR); glDisableVertexAttribArray(ARRAYINDEX_VERTEXNORMAL); glDisableVertexAttribArray(ARRAYINDEX_VERTEXTEXTUREUV); shader.Deactivate(); } void Mesh::RotateX(GLfloat angle){ rotationMatrix = glm::rotate(angle, vec3(1, 0, 0)) * rotationMatrix; } void Mesh::RotateY(GLfloat angle){ rotationMatrix = glm::rotate(angle, vec3(0, 1, 0)) * rotationMatrix; } void Mesh::RotateZ(GLfloat angle){ rotationMatrix = glm::rotate(angle, vec3(0, 0, 1)) * rotationMatrix; } Mesh* Mesh::FromFile(ShaderProgram *shader, string filepath){ MeshData meshData; vector<vec3> positions; vector<vec3> normals; vector<vec2> texCoords; FILE *file = fopen(filepath.c_str(), "r"); if (file == NULL){ cout << "Could not open file " << filepath; return NULL; } char char_line[256]; int filestatus = fscanf(file, "%s", char_line); while (filestatus != EOF){ string line = char_line; if (line.size() == 0 || line.substr(0, 1) == "#") continue; if (line.substr(0, 2) == "v "){ vec3 v; fscanf(file, "%f %f %f\n", &v.x, &v.y, &v.z); positions.push_back(v); continue; } if (line.substr(0, 3) == "vn "){ vec3 n; fscanf(file, "%f %f %f\n", &n.x, &n.y, &n.z); normals.push_back(n); continue; } if (line.substr(0, 3) == "vt "){ vec2 t; fscanf(file, "%f %f %f\n", &t.x, &t.y); texCoords.push_back(t); continue; } if (line.substr(0, 2) == "f "){ uint vi[3], ti[3], ni[3]; if (line.size() < 17){ int matches = fscanf(file, "%d//%d %d//%d %d//%d\n", vi[0], ni[0], vi[1], ni[1], vi[2], ni[2]); if (matches != 6){ // wrong format cout << ""; fclose(file); return NULL; } for (int i = 0; i < 3; i++){ VertexUnit unit(positions[vi[i]], normals[ni[i]], vec2(-1.0f, -1.0f)); meshData.AddVertexUnit(unit); } continue; } else { int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", vi[0], ti[0], ni[0], vi[1], ti[1], ni[1], vi[2], ti[2], ni[2]); if (matches != 9){ // wrong format cout << ""; fclose(file); return NULL; } for (int i = 0; i < 3; i++){ VertexUnit unit(positions[vi[i]], normals[ni[i]], texCoords[ti[i]]); meshData.AddVertexUnit(unit); } continue; } } // if line starts with anything else (mtllib, usemtl), it is ignored (for now). filestatus = fscanf(file, "%s", char_line); } fclose(file); return new Mesh(shader, &meshData); }