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
25cb35b5638ba762a01fdb45190ec015c976b351
5d275c77d975d53c700d14a996ac9542467ac31b
/96/src/main.cpp
6043dfe10df1b4602af1e0ad020d8f12477ac173
[]
no_license
0ria/ProjectEuler
5c31c470b980912f7d5b51c293412e60f2844115
c1ee42fe4d39cefab92feb2a42e9e89317b41646
refs/heads/master
2023-01-05T08:35:40.666674
2020-11-05T23:32:22
2020-11-05T23:32:22
303,120,586
0
0
null
null
null
null
UTF-8
C++
false
false
1,468
cpp
main.cpp
#include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <vector> using namespace std; std::vector<std::vector<int> > sudokuMatrix; void showMatrix(void) { for (auto row : sudokuMatrix) { for (auto number : row) { std::cout << number; } std::cout << std::endl; } } bool checkNumberInPos(int posY, int posX, int number) { for (int i = 0; i < 9; i++) if (sudokuMatrix[posY][i] == number) return false; for (int i = 0; i < 9; i++) if (sudokuMatrix[i][posX] == number) return false; int auxPosX = std::floor(posX / 3) * 3; int auxPosY = std::floor(posY / 3) * 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (sudokuMatrix[auxPosY + i][auxPosX + j] == number) return false; return true; } void implementSolution(void) { for (int j = 0; j < 9; j++) { for (int i = 0; i < 9; i++) { if (sudokuMatrix[j][i] == 0) { for (int num = 1; num <= 9; num++) { if (checkNumberInPos(j, i, num)) { sudokuMatrix[j][i] = num; implementSolution(); sudokuMatrix[j][i] = 0; } } return; } } } showMatrix(); } int main() { for (int i = 0; i < 9; i++) { std::vector<int> numbers; std::string n; std::cin >> n; for (char const c : n) { numbers.push_back(c - '0'); } sudokuMatrix.push_back(numbers); numbers.clear(); } implementSolution(); return 0; }
fd634365aa57aec8754a8a1fc936859985b9c23b
93837771b92a3f1345eaefbd7ca1f036c2dcd5a6
/orthodox.cpp
020d0b315c08a7c39221d8c2a7b4f4107b776252
[]
no_license
gauravvsgithub/Codechef
2e30628c0a4757d80041e27b96b2417760a9f4d9
3867c49a8d4c2ccb67dfd1fa3b163483c43a5540
refs/heads/main
2023-01-29T15:00:37.490613
2020-12-13T03:24:34
2020-12-13T03:24:34
320,974,221
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
orthodox.cpp
#include<iostream> using namespace std; void sumset(int sum[],int i,int n,int N,int arr[]) { static int k=0,m=0; for(int j=0;j<n;j++) { int sum1=0; for(int k=j;k<i;k++) { sum1=sum1+arr[k]; } sum[m]=sum1; } for(int z=0;z<N;z++) { cout<<sum[z]; } return; } void orthodox() { int t; cin>>t; for(int i=0;i<t;i++) { int n; cin>>n; int N=(n*(n+1))/2; int arr[n],sum[N]; for(int j=0;j<n;j++) { cin>>arr[j]; } for(int k=0;k<N;k++) { sumset(sum,k,n,N,arr); } } } int main() { return 0; }
3de982aaf7cfc455b2f1988c567cd6fd206bfbe0
70e6553122e9c4b272ac7ab36617a84a7630c5cb
/sdk/src/SignalKDocument.cpp
d664162d88e450f897f34708073c8da33bde4c9c
[ "Apache-2.0" ]
permissive
blog-neas/fairwindplusplus
756d6e5c8b2c602c4474d62fcba20eab9104941a
0b703050b2cdcf6936c4ae4e485faa50f246c7b1
refs/heads/main
2023-05-14T13:18:48.970770
2021-06-07T05:31:38
2021-06-07T05:31:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,324
cpp
SignalKDocument.cpp
// // Created by Raffaele Montella on 18/04/21. // #include <QJsonObject> #include <QJsonArray> #include <QFile> #include <QJsonDocument> #include <iomanip> #include <sstream> #include "SignalKDocument.hpp" SignalKDocument::SignalKDocument() { insert("version","1.0.0"); } SignalKDocument::~SignalKDocument() { } void SignalKDocument::update(QJsonObject &jsonObjectUpdate) { auto context = jsonObjectUpdate["context"].toString(); auto updates = jsonObjectUpdate["updates"].toArray(); for (auto updateItem: updates) { QJsonObject source=updateItem.toObject()["source"].toObject(); QString timeStamp=updateItem.toObject()["timestamp"].toString(); auto values=updateItem.toObject()["values"].toArray(); for (auto valueItem: values) { QString fullPath = context + "."+valueItem.toObject()["path"].toString(); QJsonValue value = valueItem.toObject()["value"]; insert(fullPath+".value",value); insert(fullPath+".source",source); insert(fullPath+".timestamp",timeStamp); } } //qDebug() << m_jsonDocument.toJson(); } void SignalKDocument::modifyJsonValue(QJsonObject& obj, const QString& path, const QJsonValue& newValue) { const int indexOfDot = path.indexOf('.'); const QString propertyName = path.left(indexOfDot); const QString subPath = indexOfDot>0 ? path.mid(indexOfDot+1) : QString(); QJsonValue subValue = obj[propertyName]; if(subPath.isEmpty()) { subValue = newValue; } else { QJsonObject obj = subValue.toObject(); modifyJsonValue(obj,subPath,newValue); subValue = obj; } obj[propertyName] = subValue; } void SignalKDocument::insert(const QString& fullPath, const QJsonValue& newValue) { modifyJsonValue(m_root,fullPath,newValue); //qDebug() << "SignalKDocument::insert: " << fullPath; emit updated(fullPath); if (fullPath.indexOf(getSelf()+".navigation.position")>=0) { emit updatedNavigationPosition(); } else if (fullPath.indexOf(getSelf()+"navigation.courseOverGroundTrue")>=0) { emit updatedNavigationCourseOverGroundTrue(); } else if (fullPath.indexOf(getSelf()+"navigation.speedOverGround")>=0) { emit updatedNavigationSpeedOverGround(); } for (auto subscription:subscriptions) { subscription.match(this, fullPath); } } QString SignalKDocument::getSelf() { return m_root["self"].toString(); } QString SignalKDocument::getVersion() { return m_root["version"].toString(); } QJsonValue SignalKDocument::subtree(const QString& path) { QStringList parts=path.split("."); QJsonValue jsonValue=m_root; for (auto part:parts) { if (jsonValue.isObject()) { QJsonObject jsonObject=jsonValue.toObject(); jsonValue=jsonObject[part]; } else { break; } } return jsonValue; } void SignalKDocument::save(QString fileName) { QFile jsonFile(fileName); jsonFile.open(QFile::WriteOnly); QJsonDocument jsonDocument; jsonDocument.setObject(m_root); jsonFile.write(jsonDocument.toJson()); } void SignalKDocument::load(QString fileName) { QFile jsonFile(fileName); jsonFile.open(QFile::ReadOnly); QString jsonString = jsonFile.readAll(); QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8()); } void SignalKDocument::setSelf(QString self) { insert("self",self); } QGV::GeoPos SignalKDocument::getNavigationPosition() { return getNavigationPosition(getSelf()); } QGV::GeoPos SignalKDocument::getNavigationPosition(const QString& uuid) { QGV::GeoPos result; QString path=uuid+".navigation.position.value"; QJsonValue positionValue = subtree(path); if (positionValue.isObject()) { double latitude = positionValue.toObject()["latitude"].toDouble(); double longitude = positionValue.toObject()["longitude"].toDouble(); result.setLat(latitude); result.setLon(longitude); } return result; } double SignalKDocument::getNavigationCourseOverGroundTrue() { return getNavigationCourseOverGroundTrue(getSelf()); } double SignalKDocument::getNavigationCourseOverGroundTrue(const QString& uuid) { QString path=uuid+".navigation.courseOverGroundTrue"; double courseOverGroundTrue = subtree(path)["value"].toDouble(); return courseOverGroundTrue; } double SignalKDocument::getNavigationSpeedOverGround() { return getNavigationSpeedOverGround(getSelf()); } double SignalKDocument::getNavigationSpeedOverGround(const QString& uuid) { QString path=uuid+".navigation.speedOverGround"; double speedOverGround = subtree(path)["value"].toDouble(); return speedOverGround; } void SignalKDocument::subscribe(const QString &fullPath, QObject *receiver, const char *member) { Subscription subscription(fullPath,receiver,member); subscriptions.append(subscription); connect(receiver,&QObject::destroyed,this,&SignalKDocument::unsubscribe); } void SignalKDocument::unsubscribe(QObject *receiver) { QMutableListIterator<Subscription> i(subscriptions); while (i.hasNext()) { auto subscription = i.next(); if (subscription.checkReceiver(receiver)) { i.remove(); } } } /** * Generate a UTC ISO8601-formatted timestamp * and return as std::string */ QString SignalKDocument::currentISO8601TimeUTC() { auto now = std::chrono::system_clock::now(); auto itt = std::chrono::system_clock::to_time_t(now); std::ostringstream ss; ss << std::put_time(gmtime(&itt), "%FT%TZ"); return QString(ss.str().c_str()); } QJsonObject SignalKDocument::makeUpdate(const QString &fullPath) { QJsonObject updateObject; QStringList parts=fullPath.split("."); if (parts[0]=="vessels") { QString context=parts[0]+"."+parts[1]; updateObject["context"] = context; QJsonArray updates; QJsonObject update; QJsonObject source; source["label"]="FairWind++"; source["type"]="SignalK"; update["source"]=source; update["timestamp"]=currentISO8601TimeUTC(); QJsonArray values; QJsonObject valueObject; QString path=fullPath; QJsonValue value= subtree(fullPath); path=path.replace(context+".",""); if (path.endsWith(".value")) { path=path.left(path.length()-6); } valueObject["path"]=path; valueObject["value"]=value; values.append(valueObject); update["values"]=values; updates.append(update); updateObject["updates"] = updates; } return updateObject; } QJsonObject SignalKDocument::getRoot() { return m_root; } void SignalKDocument::setRoot(QJsonObject root) { this->m_root=root; } QString SignalKDocument::getMmsi(const QString &typeUuid) { QString result=""; QJsonValue jsonValue=subtree(typeUuid+".mmsi"); if (!jsonValue.isNull() && jsonValue.isString()) { result=jsonValue.toString(); } return result; } QString SignalKDocument::getMmsi() { return getMmsi(getSelf()); } QString SignalKDocument::getNavigationState(const QString& typeUuid) { QString result =""; QJsonValue jsonValue=subtree(typeUuid+".navigation.state"); if (!jsonValue.isNull() && jsonValue.isObject() && jsonValue.toObject().contains("value")) { result=jsonValue.toObject()["value"].toString(); } return result; } QString SignalKDocument::getNavigationState() { return getNavigationState(getSelf()); } Subscription::Subscription(const QString &fullPath, QObject *receiver, const char *member) { //qDebug() << "fullPath: " << fullPath << " receiver: " << receiver->metaObject()->className() << " member:" << member; QString re=QString(fullPath).replace(".","[.]").replace(":","[:]").replace("*",".*"); regularExpression=QRegularExpression(fullPath); this->receiver=receiver; memberName=QString(member); int pos=memberName.lastIndexOf("::"); memberName= memberName.right(memberName.length()-pos-2); //QString className=QString(receiver->metaObject()->className()); //int pos=memberName.indexOf(className)+className.length()+2; //memberName= memberName.right(memberName.length()-pos); //qDebug() << "regularExpression: " << regularExpression << " receiver: " << receiver->metaObject()->className() << " member:" << memberName; } Subscription::~Subscription() = default; bool Subscription::checkReceiver(QObject *receiver) { if (this->receiver==receiver) return true; return false; } bool Subscription::match(SignalKDocument *signalKDocument, const QString &fullPath) { if (regularExpression.match(fullPath).hasMatch()) { //qDebug() << "Subscription::match(" << fullPath << ") :" << memberName; QJsonObject updateObject=signalKDocument->makeUpdate(fullPath); QMetaObject::invokeMethod(receiver, memberName.toStdString().c_str(), Qt::AutoConnection,Q_ARG(QJsonObject, updateObject)); //qDebug() << "Done!"; return true; } return false; } Subscription::Subscription(Subscription const &other) { this->regularExpression=other.regularExpression; this->receiver=other.receiver; this->memberName=other.memberName; }
f25a587e931b7ba7b5e72f6fee1d1df3302a7c69
0379269a408988bed4bc8ef82339aaf910489316
/Untitled36.cpp
507c8068ca89453050d33d1db1f541befb1cb596
[]
no_license
Aakash-lpu-9961/C-plus-plus-Learnings
d52f8a9455ac171c3652e5c85d7027fbdd64d9ec
3de10d34314a2849accb4708a2e8c26f5291af25
refs/heads/main
2023-07-20T00:42:58.076324
2021-09-04T18:56:40
2021-09-04T18:56:40
403,133,064
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
Untitled36.cpp
#include<iostream> using namespace std; class total { private: int n; public: void getdata(void); void putdata(void); void add(total, total); }; void total::getdata(void) { cout<<"Enter Number:"; cin>>n; } void total ::putdata(void) { cout<<"Number Enterd By User:"<<n<<endl; cout<<"Proceeding Please Wait!!"<<endl; } void total::add(total x, total y) { n = x.n + y.n; } int main() { total r,s,result; r.getdata(); s.getdata(); cout<<"Value of A:"; r.putdata(); cout<<"Value of B:"; s.putdata(); result.add(r,s); cout<<"Addition Result: "<<endl; result.putdata(); return 0; }
8c8e5e14b1f2ec8d690485fd79e11fc8ec1ef427
592aa065ad0bb870f8210e1492b3764404e0c372
/src/c++/Papyrus/ConsoleUtil.h
b3569b6c62eda6307ed97631f0b50cf774e66165
[ "MIT" ]
permissive
clayne/ConsoleUtilF4
777fd00d58d9b4ca0b1a073ad8444e9e034fbc11
0939e09bbb7ff6b06f2e076d1cf12f97f24dcb44
refs/heads/main
2023-07-06T11:36:48.957086
2021-08-08T03:58:01
2021-08-08T03:58:01
366,190,499
1
1
null
null
null
null
UTF-8
C++
false
false
1,304
h
ConsoleUtil.h
#pragma once #include "Papyrus/Common.h" namespace Papyrus::ConsoleUtil { inline void ExecuteCommand(std::monostate, std::string_view a_command) { RE::Console::ExecuteCommand(a_command.data()); } inline RE::TESObjectREFR* GetSelectedReference(std::monostate) { const auto ref = RE::Console::GetPickRef(); return ref.get().get(); } inline void SetSelectedReference(std::monostate, RE::TESObjectREFR* a_reference) { const auto ui = RE::UI::GetSingleton(); const auto console = ui ? ui->GetMenu<RE::Console>() : nullptr; if (console) { RE::ObjectRefHandle handle{ a_reference }; console->SetCurrentPickREFR(&handle); } } inline std::string_view ReadMessage(std::monostate) { const auto console = RE::ConsoleLog::GetSingleton(); return console ? console->buffer : ""sv; } inline void PrintMessage(std::monostate, std::string_view a_message) { const auto console = RE::ConsoleLog::GetSingleton(); console->AddString( fmt::format( FMT_STRING("{}\n"), a_message) .data()); } inline void Bind(RE::BSScript::IVirtualMachine& a_vm) { const auto obj = "ConsoleUtil"sv; BIND(ExecuteCommand); BIND(GetSelectedReference); BIND(SetSelectedReference); BIND(ReadMessage); BIND(PrintMessage); logger::debug("bound {} script"sv, obj); } }
c29520ac017b2953b2b310a763d6681937477bce
4a8f783118bd1bba8023f5dbd499b08e1822ce93
/tests/Unit/PointwiseFunctions/MathFunctions/Test_PowX.cpp
c3f229da657b6150285e5361d8c1000e37ded11d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
denyzamelchor/spectre
8db0757005dea9bb53cd7bd68ee8d11551705da4
1c1b72fbf464827788dbbdb8782a8251a2921c48
refs/heads/develop
2020-04-26T05:57:25.244454
2019-06-22T04:11:17
2019-06-22T04:11:17
155,779,028
0
0
NOASSERTION
2018-11-01T21:38:07
2018-11-01T21:38:06
null
UTF-8
C++
false
false
3,693
cpp
Test_PowX.cpp
// Distributed under the MIT License. // See LICENSE.txt for details. #include "tests/Unit/TestingFramework.hpp" #include <array> #include <cmath> #include <cstddef> #include "DataStructures/DataVector.hpp" #include "Parallel/PupStlCpp11.hpp" #include "PointwiseFunctions/MathFunctions/MathFunction.hpp" #include "PointwiseFunctions/MathFunctions/PowX.hpp" #include "Utilities/ConstantExpressions.hpp" #include "Utilities/Gsl.hpp" #include "tests/Unit/TestCreation.hpp" #include "tests/Unit/TestHelpers.hpp" template <size_t VolumeDim> class MathFunction; SPECTRE_TEST_CASE("Unit.PointwiseFunctions.MathFunctions.PowX", "[PointwiseFunctions][Unit]") { const std::array<double, 3> test_values{{-1.4, 2.5, 0.}}; // Check i = 0, i = 1 and i = 2 cases seperately { MathFunctions::PowX power(0); for (size_t j = 0; j < 3; ++j) { const auto value = gsl::at(test_values, j); CHECK(power(value) == 1.); CHECK(power.first_deriv(value) == 0.); CHECK(power.second_deriv(value) == 0.); CHECK(power.third_deriv(value) == 0.); } } { MathFunctions::PowX power(1); for (size_t j = 0; j < 3; ++j) { const auto value = gsl::at(test_values, j); CHECK(power(value) == approx(value)); CHECK(power.first_deriv(value) == 1.); CHECK(power.second_deriv(value) == 0.); CHECK(power.third_deriv(value) == 0.); } } { MathFunctions::PowX power(2); for (size_t j = 0; j < 3; ++j) { const auto value = gsl::at(test_values, j); CHECK(power(value) == approx(square(value))); CHECK(power.first_deriv(value) == approx(2. * value)); CHECK(power.second_deriv(value) == 2.); CHECK(power.third_deriv(value) == 0.); } } // Check several more powers for (int i = 3; i < 5; ++i) { MathFunctions::PowX power(i); for (size_t j = 0; j < 3; ++j) { const auto value = gsl::at(test_values, j); CHECK(power(value) == approx(std::pow(value, i))); CHECK(power.first_deriv(value) == approx(i * std::pow(value, i - 1))); CHECK(power.second_deriv(value) == approx(i * (i - 1) * std::pow(value, i - 2))); CHECK(power.third_deriv(value) == approx(i * (i - 1) * (i - 2) * std::pow(value, i - 3))); } } // Check negative powers for (int i = -5; i < -2; ++i) { MathFunctions::PowX power(i); // Don't check x=0 with a negative power for (size_t j = 0; j < 2; ++j) { const auto value = gsl::at(test_values, j); CHECK(power(value) == approx(std::pow(value, i))); CHECK(power.first_deriv(value) == approx(i * std::pow(value, i - 1))); CHECK(power.second_deriv(value) == approx(i * (i - 1) * std::pow(value, i - 2))); CHECK(power.third_deriv(value) == approx(i * (i - 1) * (i - 2) * std::pow(value, i - 3))); } } MathFunctions::PowX power(3); const DataVector test_dv{2, 1.4}; CHECK(power(test_dv) == pow(test_dv, 3)); CHECK(power.first_deriv(test_dv) == 3 * pow(test_dv, 2)); CHECK(power.second_deriv(test_dv) == 6 * test_dv); CHECK(power.third_deriv(test_dv) == 6.); test_serialization(power); test_serialization_via_base<MathFunction<1>, MathFunctions::PowX>(3); // test operator != const MathFunctions::PowX power2{-3}; CHECK(power != power2); } SPECTRE_TEST_CASE("Unit.PointwiseFunctions.MathFunctions.PowX.Factory", "[PointwiseFunctions][Unit]") { test_factory_creation<MathFunction<1>>(" PowX:\n Power: 3"); // Catch requires us to have at least one CHECK in each test // The Unit.PointwiseFunctions.MathFunctions.PowX.Factory does not need to // check anything CHECK(true); }
45d0d4de8322153e00eb8256a40dfec3e9e6bdcb
f7555d8b0f97073818d5c59b8025b04be20b0b19
/Basics/UserInput.cpp
1bfedc8741137808ab8c2879c64b540b361e77c2
[]
no_license
Guhanganesan/cplusplus
39860dd4f95c98303809bc4d9c0e6bd983e5c12e
8a54d7b91ac6b5d96147255c538d95e1ea08a4c8
refs/heads/master
2022-02-25T23:05:15.732880
2019-10-14T09:04:00
2019-10-14T09:04:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
UserInput.cpp
#include<iostream> using namespace std; int main() { int x,y,z; cout <<"Enter Number1"; cin >>x; cout <<"Enter Number2"; cin >>y; z=x+y; cout << "Sum of two number is" <<z; return 0; }
88bf936de1790e4bb67124703197b0ed04c0a349
6d088ec295b33db11e378212d42d40d5a190c54c
/contrib/brl/bseg/bvpl/functors/bvpl_edge2d_functor.h
8045f8941f7e9dc1298f11321854cc51a7624cec
[]
no_license
vxl/vxl
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
594ebed3d5fb6d0930d5758630113e044fee00bc
refs/heads/master
2023-08-31T03:56:24.286486
2023-08-29T17:53:12
2023-08-29T17:53:12
9,819,799
224
126
null
2023-09-14T15:52:32
2013-05-02T18:32:27
C++
UTF-8
C++
false
false
1,097
h
bvpl_edge2d_functor.h
#ifndef bvpl_edge2d_functor_h_ #define bvpl_edge2d_functor_h_ //: // \file // \brief Functor to find the 2D edges // // \author Gamze Tunali (gamze_tunali@brown.edu) // \date June 02, 2009 // // \verbatim // Modifications // <none yet> // \endverbatim #include <bvpl/kernels/bvpl_kernel_iterator.h> template <class T> class bvpl_edge2d_functor { public: //: Default constructor bvpl_edge2d_functor(); //: Destructor ~bvpl_edge2d_functor() = default; //: Apply a given operation to value val, depending on the dispatch character void apply(T& val, bvpl_kernel_dispatch& d); //: Returns the final operation of this functor T result(); private: T min_P_; T P_; // probability based on kernel T P1_; // probability of all 1s T P0_; // probability of all 1s T P05_; // probability of all 0.5 //The next variables are normalization values. //the correspond to the values above (P_, P1_ ...) when the are is empty/initial value T P_norm; T P1_norm; T P0_norm; T P05_norm; unsigned n_; //: Initializes class variables void init(); }; #endif
3eaf16eb957a3cc6a9af47847b7880428a35660d
51d0519ea68a98734eb6bae3456b5df6de8445ea
/Provette/Interface/Varie.h
677d6089404031cd622a8a70bdf870bab987e1e8
[]
no_license
eleoracca/Alacre
e9c553b59ae174e132314577c31f099d52ac3bef
dd4a80fa7f268ad621a495948bac83d94defba9f
refs/heads/master
2021-08-15T19:01:07.840717
2021-07-28T09:57:38
2021-07-28T09:57:38
135,583,869
0
0
null
null
null
null
UTF-8
C++
false
false
3,387
h
Varie.h
#ifndef Varie_h #define Varie_h /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Implementazione dell'utility Varie ~ ~ Autori: Racca Eleonora - eleonora.racca288@edu.unito.it ~ ~ Sauda Cristina - cristina.sauda@edu.unito.it ~ ~ Ultima modifica: 25/08/2018 ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include "Riostream.h" #include "TFile.h" #include "TH1F.h" #include "TMath.h" #include "TRandom3.h" #include "TString.h" #include "Colori.h" using namespace std; using namespace colore; // ****************************************************************************** // ************************ Dichiarazione delle funzioni ************************ // ****************************************************************************** // Funzione che trasforma pseudorapidit� in theta double EtaTheta(bool &distribuzione, const double inferiore, const double superiore, TH1F* istogramma); // Funzione che trasforma theta in pseudorapidità double ThetaEta(const double theta); // Funzione che importa istogrammi TH1F* ImportaIstogramma(TString file, TString istogramma); // Funzione che trova la moda double Moda(TH1D *istogramma, double larghezza); // ****************************************************************************** // *********************** Implementazione delle funzioni *********************** // ****************************************************************************** double EtaTheta(bool &distribuzione, const double inferiore, const double superiore, TH1F* istogramma){ double eta = 0.0; do{ if(distribuzione){ eta = istogramma -> GetRandom(); } else{ eta = gRandom -> Uniform(inferiore, superiore); } }while(eta<inferiore || eta>superiore); return 2*TMath::ATan(TMath::Exp(-eta)); } double ThetaEta(const double theta){ return -TMath::Log(TMath::Tan(theta/2)); } TH1F* ImportaIstogramma(TString file, TString istogramma){ TFile *fileistogramma = new TFile(file); TH1F *isto = (TH1F*)fileistogramma -> Get(istogramma); isto -> SetDirectory(0); fileistogramma -> Close(); delete fileistogramma; return isto; } double Moda(TH1D *istogramma, double larghezza){ // Cerco la moda più a sinistra int binDelMassimo = istogramma -> GetMaximumBin(); double moda = istogramma -> GetXaxis() -> GetBinCenter(binDelMassimo); // Controllo che esista una moda if(istogramma->GetBinContent(binDelMassimo)==0){ // cout << Errore("Moda della coordinata z = 0") << endl; return moda = -500; } else if(istogramma->GetBinContent(binDelMassimo)==1){ // cout << Avvertimento("Moda della coordinata z = 1") << endl; return moda = -600; } // Controllo che non ci siano altri massimi a destra int binDelMassimo2 = istogramma -> FindLastBinAbove(istogramma -> GetBinContent(binDelMassimo) - 1, 1, binDelMassimo +1, istogramma -> GetNbinsX()); double moda2 = istogramma -> GetXaxis() -> GetBinCenter(binDelMassimo2); if(istogramma -> GetBinContent(binDelMassimo2) == istogramma -> GetBinContent(binDelMassimo)){ // Cerco il massimo migliore if(fabs(moda - moda2) < larghezza){ double media = (moda + moda2)/2.; return media; } else{ if(fabs(moda) <= fabs(moda2)){ return moda; } else{ return moda2; } } } else return moda; } #endif
0b3d3d985e3545a0e63aac8593b9f1be669fb34f
cf1b40dcd73f10b92d86a961141883abc6811d08
/RepairCarInfoManage/UserMngQueryDlg.h
1f745b5e1f546d3094474e286af305499c70a643
[]
no_license
qingshanyijiu/RepairCarInfoManage
0fa823beea3672a0c840a476b1d43cad80ddcab9
ce2beb0a7d4334a8ecd274501b542793ead3e4a6
refs/heads/master
2021-01-17T06:08:15.832469
2016-07-01T07:46:05
2016-07-01T07:46:05
61,848,536
0
0
null
null
null
null
GB18030
C++
false
false
1,552
h
UserMngQueryDlg.h
#pragma once #include <vector> #include <string> using namespace std; // CUserMngQueryDlg 对话框 typedef int (*pQueryfunc)(const char* lpLicNumer,int iPages,int iMaxCount,std::vector<UserTableInfo>& userInfoList,bool bOrderInc); class CUserMngQueryDlg : public CDialogEx { DECLARE_DYNAMIC(CUserMngQueryDlg) public: CUserMngQueryDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CUserMngQueryDlg(); // 对话框数据 enum { IDD = IDD_USERMNG_QUERY_DLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); // CButton m_groupbox; virtual BOOL OnInitDialog(); afx_msg void OnBnClickedBtnUserUserquery(); afx_msg void OnBnClickedButtonQuserbefore(); afx_msg void OnBnClickedButtonQusernext(); CButton m_QUserBeforeButton; CButton m_QUserNextButton; CListCtrl m_userList; // afx_msg void OnLvnItemchangedListUserlist(NMHDR *pNMHDR, LRESULT *pResult); public: int m_curPageIndex; pQueryfunc m_pQueryFunc; string m_strQueryKey; vector<UserTableInfo> m_userInfoVect; public: void UpdateDataInfo(); void QueryUserInfoByLicNumber(const char* lpLicNumber); public: afx_msg void OnRclickListUserlist(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnDblclkListUserlist(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnSmenuUserdelete(); afx_msg void OnSmenuUserdetail(); afx_msg void OnSmenuUsermodify(); afx_msg void OnSmenuUserqueryrepair(); virtual BOOL PreTranslateMessage(MSG* pMsg); };
fe180c9023fd005f4eb4c2c2ebd8b8b52477173f
e2466243f3163fa730a7cb1726677a1ba0f500c0
/day03/ex03/ClapTrap.cpp
753ad4abb96a1c7d6bc74f3ea2f940aad49c64ad
[]
no_license
Enedys/ft_CPP_piscine
3f8e8575fd0cf9c724e0e36579f4041eba00a9aa
315a586ccba369008af10cd5a9229bc0c14521fa
refs/heads/master
2023-02-21T02:28:29.022807
2021-01-24T17:51:35
2021-01-24T17:51:35
328,935,757
0
0
null
null
null
null
UTF-8
C++
false
false
3,160
cpp
ClapTrap.cpp
# include "ClapTrap.hpp" ClapTrap::~ClapTrap() { std::cout << "ClapTrap object " << _name << " was destroyed!\n"; } ClapTrap::ClapTrap() : _name("Default_name"), _type("ClapTrap") { } ClapTrap::ClapTrap(const std::string &name, const std::string &trapType) : _name(name), _type(trapType) { _lvl = 1; _hitPoints = 50; _maxHitPoints = 100; _energyPoints = 20; _maxEnergyPoints = 80; _armorDamageReduction = 3; _meleeAttackDamage = 10; _rangedAttackDamage = 20; std::srand(static_cast<unsigned int>(std::time(0))); std::cout << "ClapTrap object " << _name << " was created!\n"; } ClapTrap::ClapTrap(const ClapTrap &toCopy) { std::srand(static_cast<unsigned int>(std::time(0))); std::cout << "ClapTrap copy constructor called\n"; *this = toCopy; } void ClapTrap::_copy(const ClapTrap &toCopy) { std::cout << "ClapTrap copy function called.\n"; _name = toCopy._name; _type = toCopy._type; _lvl = toCopy._lvl; _hitPoints = toCopy._hitPoints; _maxHitPoints = toCopy._maxHitPoints; _energyPoints = toCopy._energyPoints; _maxEnergyPoints = toCopy._maxEnergyPoints; _armorDamageReduction = toCopy._armorDamageReduction; _meleeAttackDamage = toCopy._meleeAttackDamage; _rangedAttackDamage = toCopy._rangedAttackDamage; } ClapTrap &ClapTrap::operator=(const ClapTrap &toAssign) { std::cout << "ClapTrap assignation operator called.\n"; ClapTrap::_copy(toAssign); return (*this); } const std::string &ClapTrap::_getRandomName(const std::string names[], int num) const { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); return names[static_cast<int>(std::rand() * fraction * num)]; } int ClapTrap::rangedAttack(std::string const &target) const { std::cout << "ClapTrap " << " " << _name << " attacks " << target << " at range, causing " << _rangedAttackDamage << " points of damage!\n"; return (_rangedAttackDamage); } int ClapTrap::meleeAttack(std::string const &target) const { std::cout << "ClapTrap " << " " << _name << " attacks " << target << " at melee, causing " << _meleeAttackDamage << " points of damage!\n"; return (_meleeAttackDamage); } void ClapTrap::takeDamage(unsigned int damage) { if (_hitPoints == 0) std::cout << _type << " " << _name << " is already broken :(\n"; else if (damage > _armorDamageReduction) { unsigned effectiveHealth = _hitPoints + _armorDamageReduction; unsigned int newHitPoints = effectiveHealth < damage ? 0 : effectiveHealth - damage; std::cout << _type << " " << _name << " takes " << _hitPoints - newHitPoints << " damage and now has " << newHitPoints << " HP.\n"; _hitPoints = newHitPoints; } else std::cout << _type << " " << _name << " was not damaged!\n"; } void ClapTrap::beRepaired(unsigned int healthRep) { if (_hitPoints == _maxHitPoints) std::cout << _type << " " << _name << " has a max HP!\n"; else { unsigned int futureHealth = _hitPoints + healthRep; unsigned int newHitPoints = futureHealth > _maxHitPoints ? _maxHitPoints : futureHealth; std::cout << _type << " " << _name << " take " << newHitPoints - _hitPoints << " HP and currently has " << newHitPoints << " HP.\n"; _hitPoints = newHitPoints; } }
7843529d9945aa38d45ab8463f4fe4085e24bbc2
ec22513427de8131cc57131257328626dbea1e1a
/minSwapToBringKtogether.cpp
eb63a8415e35440690e432f3ed73cface77c2ffa
[]
no_license
thanwin84/Array
7c4f25883b6fc88ca8fa253b5b91dd5fbec14317
1629b1fa59d0484bb940d1da44061cbaa7495d04
refs/heads/main
2023-07-01T06:53:59.506732
2021-08-10T07:55:24
2021-08-10T07:55:24
356,995,257
1
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
minSwapToBringKtogether.cpp
//time: O(n) using sliding window techniq int minSwap(int *arr, int n, int k) { // Complet the function int count = 0; for (int i = 0; i < n; i++) { if (arr[i] <= k) { count++; } } int bad = 0; for (int i = 0; i < count; i++) { if (arr[i] > k) bad++; } int ans = bad; int j = count; for (int i = 0; i < n; i++) { if (j == n) { break; } if (arr[i] > k) bad--; if (arr[j] > k) bad++; ans = min(ans, bad); j++; } return ans; return count; } -
75359776c875436b88b301259daceb2a82c5fcd1
02e2accd33e8810cb50bd8555cdb92f2a49301e7
/cegui/include/CEGUI/RendererModules/Null/Renderer.h
bf60504d0b9bbb556cfc451fcc22a091c4615eee
[ "MIT" ]
permissive
cegui/cegui
fa6440e848d5aea309006496d2211ddcd41fefdf
35809470b0530608039ab89fc1ffd041cef39434
refs/heads/master
2023-08-25T18:03:36.587944
2023-08-12T15:50:41
2023-08-12T15:50:41
232,757,330
426
78
MIT
2023-08-12T15:40:02
2020-01-09T08:15:37
C++
UTF-8
C++
false
false
6,949
h
Renderer.h
/*********************************************************************** created: Fri Jan 15 2010 author: Eugene Marcotte *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUINullRenderer_h_ #define _CEGUINullRenderer_h_ #include "../../Renderer.h" #include "../../Sizef.h" #include <vector> #include <unordered_map> #if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined(CEGUI_STATIC) # ifdef CEGUINULLRENDERER_EXPORTS # define NULL_GUIRENDERER_API __declspec(dllexport) # else # define NULL_GUIRENDERER_API __declspec(dllimport) # endif #else # define NULL_GUIRENDERER_API #endif #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { class NullGeometryBuffer; class NullTexture; class NullShaderWrapper; //! CEGUI::Renderer implementation for no particular engine class NULL_GUIRENDERER_API NullRenderer : public Renderer { public: /*! \brief Convenience function that creates all the necessary objects then initialises the CEGUI system with them. This will create and initialise the following objects for you: - CEGUI::NullRenderer - CEGUI::DefaultResourceProvider - CEGUI::System \param abi This must be set to CEGUI_VERSION_ABI \return Reference to the CEGUI::NullRenderer object that was created. */ static NullRenderer& bootstrapSystem(const int abi = CEGUI_VERSION_ABI); /*! \brief Convenience function to cleanup the CEGUI system and related objects that were created by calling the bootstrapSystem function. This function will destroy the following objects for you: - CEGUI::System - CEGUI::DefaultResourceProvider - CEGUI::NullRenderer \note If you did not initialise CEGUI by calling the bootstrapSystem function, you should \e not call this, but rather delete any objects you created manually. */ static void destroySystem(); /*! \brief Create an NullRenderer object */ static NullRenderer& create(const int abi = CEGUI_VERSION_ABI); //! destroy an NullRenderer object. static void destroy(NullRenderer& renderer); // implement CEGUI::Renderer interface RenderTarget& getDefaultRenderTarget() override; RefCounted<RenderMaterial> createRenderMaterial(const DefaultShaderType shaderType) const override; GeometryBuffer& createGeometryBufferTextured(RefCounted<RenderMaterial> renderMaterial) override; GeometryBuffer& createGeometryBufferColoured(RefCounted<RenderMaterial> renderMaterial) override; TextureTarget* createTextureTarget(bool addStencilBuffer) override; void destroyTextureTarget(TextureTarget* target) override; void destroyAllTextureTargets() override; Texture& createTexture(const String& name) override; Texture& createTexture(const String& name, const String& filename, const String& resourceGroup) override; Texture& createTexture(const String& name, const Sizef& size) override; void destroyTexture(Texture& texture) override; void destroyTexture(const String& name) override; void destroyAllTextures() override; Texture& getTexture(const String& name) const override; bool isTextureDefined(const String& name) const override; void beginRendering() override; void endRendering() override; void setDisplaySize(const Sizef& sz) override; const Sizef& getDisplaySize() const override; unsigned int getMaxTextureSize() const override; const String& getIdentifierString() const override; bool isTexCoordSystemFlipped() const override; protected: //! default constructor. NullRenderer(); //! common construction things. void constructor_impl(); //! destructor. virtual ~NullRenderer(); //! helper to throw exception if name is already used. void throwIfNameExists(const String& name) const; //! helper to safely log the creation of a named texture static void logTextureCreation(const String& name); //! helper to safely log the destruction of a named texture static void logTextureDestruction(const String& name); //! String holding the renderer identification text. static String d_rendererID; //! What the renderer considers to be the current display size. Sizef d_displaySize; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. typedef std::vector<TextureTarget*> TextureTargetList; //! Container used to track texture targets. TextureTargetList d_textureTargets; //! container type used to hold GeometryBuffers we create. typedef std::vector<NullGeometryBuffer*> GeometryBufferList; //! Container used to track geometry buffers. GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. typedef std::unordered_map<String, NullTexture*> TextureMap; //! Container used to track textures. TextureMap d_textures; //! What the renderer thinks the max texture size is. unsigned int d_maxTextureSize; //! Shaderwrapper for textured & coloured vertices NullShaderWrapper* d_shaderWrapperTextured; //! Shaderwrapper for coloured vertices NullShaderWrapper* d_shaderWrapperSolid; }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUINullRenderer_h_
d4c1fa33411195c615d7a134cad87a093e41cb83
0f399c573b88ef5ea3fffd3c475059ec694583bb
/82_Remove Duplicates from Sorted List II.cpp
fca5dfc416ca95a00db659f1c7e0cef08b103d36
[]
no_license
EasonQiu/LeetCode
31075bc2ca28d23509e290b4935949500e1fec24
5be348261bb5f45e471de3f44dd2f57ec671ffcf
refs/heads/master
2021-01-12T22:21:30.725971
2017-09-22T02:42:53
2017-09-22T02:42:53
68,566,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
82_Remove Duplicates from Sorted List II.cpp
// Given a sorted linked list, delete all nodes that have duplicate numbers, // leaving only distinct numbers from the original list. // For example, // Given 1->2->3->3->4->4->5, return 1->2->5. // Given 1->1->1->2->3, return 2->3. // 感想:每次试图获取node->next的时候一定要先确保node非NULL #include <iostream> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) return head; ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *prev_tail = dummy, *curr = head, *next; int val; while (curr && curr->next) { val = curr->val; next = curr->next; if (next->val == val) { // have duplicates while (curr && curr->val == val) { delete(curr); curr = next; if (curr) next = curr->next; } prev_tail->next = curr; } else { // no duplicates prev_tail = curr; curr = curr->next; } } return dummy->next; } }; int main() { ListNode* a = new ListNode(1); ListNode* b = new ListNode(1); // ListNode* c = new ListNode(2); // ListNode* d = new ListNode(4); // ListNode* e = new ListNode(5); a->next = b; // b->next = c; c->next = d; d->next = e; Solution s; ListNode *head = s.deleteDuplicates(a); while (head) { cout << head->val << " "; head = head->next; } cout << endl; return 0; }
a05f79d706de0469da43725576070f222a37dbae
e44bd6e8b06ab16b86e48d55f399873bd7f2652f
/Codeforces Round 551/Ques2/main.cpp
a5143534ce6bcb56192f361bef319b5cae7abf3a
[]
no_license
dalip98/Data-Structures-and-Algorithm
a254a91e60f23be462e2d005bd13725fb0e50ad9
d4977a1fdac9606ea820dd2e69915fca77a6d133
refs/heads/master
2021-06-29T05:28:57.811883
2020-10-21T13:37:08
2020-10-21T13:37:08
179,121,547
0
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
main.cpp
#include <bits/stdc++.h> #include<algorithm> #include<vector> #define ll long long int #define mod 1000000007 using namespace std; int main() { ios::sync_with_stdio(0); ll n,m,h; cin>>n>>m>>h; vector<ll>fnt(m); for(ll i=0;i<m;i++) cin>>fnt[i]; vector<ll>side(n); for(ll i=0;i<n;i++) cin>>side[i]; ll arr[n][m]; for(ll i=0;i<n;i++) { for(ll j=0;j<m;j++) cin>>arr[i][j]; } for(ll i=0;i<n;i++) { for(ll j=0;j<m;j++) { if(arr[i][j]==0) cout<<0<<" "; else { cout<<min(fnt[j] , side[i])<<" "; } } cout<<endl; } return 0; }
5826a4eb334357332cede904a36ec456116e4cc4
5cad367b7a34f124a766cd075a183b44415bb3ee
/JUNGOL/나는 학급회장이다/main.cpp
d76f9465e4a9fe73bd59b537159f260be2891b8e
[]
no_license
Rkda8071/PS
f8078744397c58380755a5ad3cd238e484068b7a
fbf1cacf8851e100a3c6edc335db77172a24f3db
refs/heads/master
2023-01-12T17:55:30.313774
2022-12-24T12:38:39
2022-12-24T12:38:39
237,006,211
0
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
main.cpp
#include<bits/stdc++.h> using namespace std; int a[4][4]; int cmp(int x,int y){ for(int i=0;i<=3;i++){ if(a[x][i]>a[y][i]) return x; else if(a[x][i]<a[y][i]) return y; } return 0; } int main(){ int n; int x,y,z; scanf("%d",&n); for(int i=0;i<n;i++) { for(int j=1;j<=3;j++){ scanf("%d",&x); a[j][0] += x; a[j][x]++; } } for(int i=0;i<=3;i++) a[0][i] = a[2][i]; printf("%d ",cmp(1,cmp(2,3))); printf("%d",max(a[1][0],max(a[2][0],a[3][0]))); return 0; }
f903b0837fe8f01e88c4ea0053bc0dce06944839
6e2dd4cb04f2ae7b3ad189ddb0be9e22df6b5649
/B4/B4c/include/CalcAngularRes.hh
9b9207d10e9d3291f4f88082c147c9fcaaf5aba4
[]
no_license
emberger/FwEcalAirGap
ecdb0bf1d30edb230f376183fea1bc0c29b780ce
bed340163ab977bcbb4215e2209d3bf39c231376
refs/heads/master
2021-05-14T07:49:03.366597
2018-01-09T12:27:04
2018-01-09T12:27:04
116,277,781
0
0
null
null
null
null
UTF-8
C++
false
false
1,424
hh
CalcAngularRes.hh
#include "B4ROOTEvent.hh" #include "TTree.h" #include "TChain.h" #include "TCanvas.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TH1D.h" #include "TH2D.h" #include "TLine.h" #include "TBrowser.h" #include "TColor.h" #include "TH3D.h" #include "TStyle.h" #include "TColor.h" #include "TGraph2D.h" #include "TMultiGraph.h" #include "TAttMarker.h" #include "TFile.h" #include "TList.h" #include "TF1.h" #include "TMath.h" #include "TImage.h" #include "TVector3.h" #include "TLorentzVector.h" #include "TRandom3.h" #include "TLegend.h" #include "Minuit2/MnUserParameters.h" #include "Minuit2/MinimumParameters.h" #include "Minuit2/MnUserCovariance.h" #include "Minimizer.hh" #include "Minuit2/Minuit2Minimizer.h" #include <chrono> #include <stdlib.h> #include <string> #include <cstring> #include <memory> #include <utility> #include <cstddef> // #include <boost/filesystem.hpp> // // using namespace boost::filesystem; // struct recursive_directory_range // { // typedef recursive_directory_iterator iterator; // recursive_directory_range(path p) : p_(p) {} // // iterator begin() { return recursive_directory_iterator(p_); } // iterator end() { return recursive_directory_iterator(); } // // path p_; // }; class AngularResolution { public: void CalcAngularResolution(std::string pth, std::string title); void EresAndShowerprofile(std::string pth); private: Int_t nofEvents; };
d246d91173117921987881330e4f62d5e298e2b2
84543cb24f6d641f98a28e6970ab63ea2fad4442
/src/blizzard/pool.hpp
c1fa19b36db2859b093b28edc5f22bebbc00cc13
[]
no_license
bachan/blizzard
4731cbb653ac94e6aed4a534761e2ea0c86f747d
b29b51fa970a4c005a4e1c8e2d2b313b3de0a3dc
refs/heads/master
2021-12-01T01:18:23.872440
2021-11-09T18:41:58
2021-11-09T18:50:12
2,143,009
10
5
null
2013-12-02T03:49:54
2011-08-02T14:39:04
C++
UTF-8
C++
false
false
806
hpp
pool.hpp
#ifndef __BLIZZARD_POOL_HPP__ #define __BLIZZARD_POOL_HPP__ #include <sys/types.h> #include "pool_stack.hpp" namespace pool_ns { /* Memory allocator for fixed size structures */ template <typename T, int objects_per_page = 65536> class pool { protected: struct page { page* next; T* data; T* free_node; page(); ~page(); bool full() const; T* allocate(); void attach(page* p); }; stack<T*> free_nodes; page* root; uint16_t pages_num; uint32_t objects_num; public: pool(); ~pool(); uint32_t allocated_pages() const; uint32_t allocated_objects() const; uint32_t allocated_bytes() const; size_t page_size() const; T* allocate(); void free(T* elem); }; #include "pool.tcc" } #endif /* __BLIZZARD_POOL_HPP__ */
505625c143d09ba4ac39acbb79dd05b57010c7f6
5a34d529bd017e455fd113aa3ad612fbc982abd7
/src/ZGZ_IoT.cpp
9ee7aaad7946ffa8d77c45fe984afc62d791e5bc
[]
no_license
Timearchitect/ZGZ-IoT
92d6c264ae9e710d6aa1ba84111bd5eb9d919126
782507d50eb32d791a6c9849b1377426c337f30c
refs/heads/master
2020-05-29T09:52:40.105090
2015-06-10T12:55:33
2015-06-10T12:55:33
37,070,368
0
0
null
2015-06-08T14:02:18
2015-06-08T14:02:18
Arduino
UTF-8
C++
false
false
143
cpp
ZGZ_IoT.cpp
#include "ZGZ_IoT.h" String urlEncode(String s) { for (int i = 0; i < s.length(); i++) { if (s[i] == ' ') s[i] = '+'; } return s; }
9dbed55f4c316b24b9ed39fe24b60417c36b4d56
c85134084b4015c63ee2557f4f711be512ac14a1
/serverlibrary/src/main/cpp/mmap_util.h
70d61bcdc868f82e15d2878ba39c79242e4b465f
[]
no_license
foryoung2018/PerformanceVideoCached
9d4b93477250b674c5a131dba7494ecb6d6d4dc9
c3239651973708c5003dbedc96b237d238da11f8
refs/heads/master
2021-02-13T02:46:17.459048
2020-10-28T17:29:29
2020-10-28T17:29:29
244,653,656
16
3
null
null
null
null
UTF-8
C++
false
false
973
h
mmap_util.h
// // Created by foryoung on 2020/3/7. // #ifndef PERFORMANCEVIDEOCACHED_MMAP_UTIL_H #define PERFORMANCEVIDEOCACHED_MMAP_UTIL_H #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <strings.h> #include <android/log.h> #include <string> #include <stdio.h> #include <unistd.h> #include <error.h> #define LOG(...) __android_log_print(ANDROID_LOG_ERROR,"cached_server",__VA_ARGS__); //写在头文件里的变量如果不加上static 的话会造成重复引用 最好的办法就是不要写在头文件 static int8_t *_ptr=0; static size_t _size; static int32_t _fd; void mmap_write(const char *src_ptr,const int32_t len, const char *path_ptr, const char *name_ptr); void mmap_write(const std::string src_ptr, const std::string path, const std::string name); void mmap_write(const void *src_ptr, const int32_t len, const char *path_ptr, const char *name_ptr); #endif //PERFORMANCEVIDEOCACHED_MMAP_UTIL_H
37a18c951bb40d0e84d972d307c71da80a9c1e8f
d1e2d8db59d1a349562f96704ae049c777304311
/src/engine_v0_2/src/ConstantSpeedRotation.cpp
303bc2c489930f0ea06080df8d22756234f360bf
[]
no_license
minimaxwell/gameengine
d9d1780f3acdd4ef4d54bd246eb538c22ff96eba
eaec367194e9b4c5262114e4c21f8bc3f83faa37
refs/heads/master
2016-09-02T06:01:51.021281
2014-10-11T19:36:29
2014-10-11T19:36:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
569
cpp
ConstantSpeedRotation.cpp
/* * File: ConstantSpeedRotation.cpp * Author: maxwell * * Created on 19 avril 2014, 18:07 */ #include "ConstantSpeedRotation.h" using namespace ge; ConstantSpeedRotation::ConstantSpeedRotation( double angularSpeed ) : Rotation(), m_angularSpeed(angularSpeed) { } ConstantSpeedRotation::~ConstantSpeedRotation() { } double ConstantSpeedRotation::rotation(unsigned long long elapsed){ return m_angularSpeed * ( elapsed / 1000000.0 ); } Rotation * ConstantSpeedRotation::clone() const{ return new ConstantSpeedRotation( m_angularSpeed ); }
d2db57a83b4e327972e3a8752b0b79a7a3a1d87d
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/core/tfrt/mlrt/bytecode/executable.h
2f6f9c0edea8aa29addb9c5c228fcff1142612be
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
3,222
h
executable.h
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_TFRT_MLRT_BYTECODE_EXECUTABLE_H_ #define TENSORFLOW_CORE_TFRT_MLRT_BYTECODE_EXECUTABLE_H_ #include "tensorflow/core/tfrt/mlrt/bytecode/function.h" namespace mlrt { namespace bc { // Defines the bytecode format for the executable, which contains the following // section: // 1) kernel_names: an ordered list of strings for kernel names that appear in // this file. The `code` fields of kernels in `functions` will be indices to // this list. // // 2) attributes: an ordered list of strings that are raw bytes. It is kernel // implementations' resposiblity to decode the bytes properly. The `attributes` // field of kernels in `functions` will be indices to this list. // // 3) functions: an order list of functions, which contains kernels and other // metadata. Please refer to function.h for its detailed format. class Executable { public: struct StorageType { using Self = StorageType; DEFINE_BYTECODE_FIELD(Vector<String>, kernel_names); DEFINE_BYTECODE_FIELD(Vector<Function>, functions); DEFINE_BYTECODE_FIELD(Vector<String>, attributes); }; class Constructor { public: Constructor(Allocator* allocator, BcAddr_t address) : allocator_(allocator), address_(address) {} template <typename... Args> auto construct_kernel_names(Args&&... args) { return StorageType::construct_kernel_names(allocator_, address_, std::forward<Args>(args)...); } template <typename... Args> auto construct_attributes(Args&&... args) { return StorageType::construct_attributes(allocator_, address_, std::forward<Args>(args)...); } template <typename... Args> auto construct_functions(Args&&... args) { return StorageType::construct_functions(allocator_, address_, std::forward<Args>(args)...); } BcAddr_t address() const { return address_; } private: Allocator* allocator_; BcAddr_t address_; }; using NonTrivialConstructorType = Constructor; explicit Executable(const char* p) : p_(p) {} Vector<String> kernel_names() const { return StorageType::read_kernel_names(p_); } Vector<Function> functions() const { return StorageType::read_functions(p_); } Vector<String> attributes() const { return StorageType::read_attributes(p_); } private: const char* p_; }; } // namespace bc } // namespace mlrt #endif // TENSORFLOW_CORE_TFRT_MLRT_BYTECODE_EXECUTABLE_H_
9ccf2384119a972e6f116ac9f360939f4aaac444
db4ccd7115d180dee37b5e953aa065e48f8f68e6
/node.cpp
ff88feb63be7393a372a79fb121361341dce26f3
[]
no_license
scast/ci5437
53757dd9f6cc2d01875d7536a6abc49ba21e635c
2bf645f37fdfe6a74328f50f4634b49be48759f4
refs/heads/master
2016-09-03T07:22:58.085361
2012-10-24T02:05:06
2012-10-24T02:05:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,635
cpp
node.cpp
#include "node.hpp" #include "clique.hpp" #include "cstring" /* * Constructor de un nuevo nodo. */ node::node(state& _state, node *_parent, int _costo, int _action) : s(_state), parent(_parent), cost(_costo), action(_action) { #ifndef STATIC h = find_disjoint_cliques_upto(g, s, N, MAX_GRADE); #else int total = 0; for (int i=0; i <N; i++) { if ((s[i] == INCLUIDO) && (parent->s[i] != INCLUIDO)) { // Veo si incluí este nodo y sumo 1 a su total += (cliques[i]==i) ? 0 : 1; // total, si pertenece a una clique } } h = max(parent->h - total, 0); #endif } /* * Crea un nodo en el estado inicial */ node::node() { s = init(); cost = 0; parent = 0; action = -1; h = find_disjoint_cliques_upto(g, s, N, MAX_GRADE); } /* * Crea una copia de este nodo. */ node::node(const node& n) { s = n.s; cost = n.cost; parent = &n; action = n.action+1; h = n.h; } /* * Revisar si estamos en un goal */ bool node::is_goal() { #ifndef STATIC return (h == 0); #else for (int i=0; i<N; i++) { if (s[i] != INCLUIDO) { for(set<int>::iterator it=g[i].begin(); it != g[i].end(); ++it) { if (s[*it] != INCLUIDO) return false; } } } return true; #endif } /* * Generar *un* sucesor */ state generate_succ(state& s1, int nodo) { vector<char> newState(s1); newState[nodo] = INCLUIDO; return newState; } /* * Retorna el estado inicial del arbol de busqueda dado un grafo de * tamano n. */ state init() { state g(N, EXCLUIDO); return g; }
e13664c66685cc69f3e82f36ad0a10b268a08503
4b76fa0a4f2001f10f2098f598c69eccae82a7e3
/Graph Data Structure & Algorithms/Snake Ladder Problem!.cpp
77d05dc71a8d7f1849c8fa68dac8bd529e890b36
[]
no_license
KushRohra/InterviewBit_Codes
cb87b2485c3d63f41f3da22bc03e895be4cd5d05
bd4aed23788ea800a08bb4a91e34c5b631ef763e
refs/heads/master
2023-02-10T16:01:28.218120
2021-01-11T17:51:28
2021-01-11T17:51:28
328,747,526
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
Snake Ladder Problem!.cpp
int Solution::snakeLadder(vector<vector<int> > &A, vector<vector<int> > &B) { int i, j, pos, n=10; unordered_map<int, int> snake, ladder; int ans=INT_MAX; for(i=0;i<A.size();i++) ladder[A[i][0]]=A[i][1]; for(i=0;i<B.size();i++) snake[B[i][0]]=B[i][1]; queue<pair<int, int>> q; q.push({1,0}); vector<int> vis(n*n+1,0); while(!q.empty()) { int newPos, pos = q.front().first, dist = q.front().second; q.pop(); if(vis[pos]==1) continue; vis[pos]=1; //cout<<pos<<" "<<dist<<" "; if(pos==n*n) if(dist<ans) ans=dist; for(i=1;i<7;i++) { newPos = pos + i; if(newPos>n*n) continue; //cout<<newPos<<" "; if(snake.find(newPos)!=snake.end()) newPos = snake[newPos]; if(ladder.find(newPos)!=ladder.end()) newPos = ladder[newPos]; if(vis[newPos]==0) q.push({newPos, dist+1}); } } if(ans==INT_MAX) return -1; return ans; }
988975c74ec082af66a23161cdb4617bd29ba1ac
5cef19f12d46cafa243b087fe8d8aeae07386914
/codeforces/hello2019/f.cpp
9db1c0525e5d2059ebada4622c83f61da3e1e350
[]
no_license
lych4o/competitive-programming
aaa6e1d3f7ae052cba193c5377f27470ed16208f
c5f4b98225a934f3bd3f76cbdd2184f574fe3113
refs/heads/master
2020-03-28T15:48:26.134836
2019-05-29T13:44:39
2019-05-29T13:44:39
148,627,900
1
0
null
null
null
null
UTF-8
C++
false
false
1,532
cpp
f.cpp
#include<bits/stdc++.h> #define sc(x) scanf("%d",&x) #define sll(x) scanf("%I64d",&x) #define F first #define S second #define mk make_pair #define ALL(x) x.begin(),x.end() #define maxn 8 #define pb push_back using namespace std; typedef long long LL; typedef pair<int,int> pii; const LL mod = 1e9+7; const int maxm = 1e5+10; int n, mu[maxn], q; bitset<maxn> b[maxn], c[maxn], a[maxm], f[maxn]; int main(){ for(int i=maxn-1;i>0;i--){ f[i][i]=1; for(int j=2*i;j<maxn;j+=i){ f[i]^=f[j]; } cout << "f["<<i<<"]:"<<f[i]<<endl; } for(int i=1;i<maxn;i++){ mu[i] = (i==1)-mu[i]; for(int j=i*2;j<maxn;j+=i){ mu[j] += mu[i]; } //printf("mu[%d]:%d\n",i,mu[i]); } for(int i=1;i<maxn;i++){ for(int j=i;j<maxn;j+=i){ b[j][i]=1; c[i][j]=(mu[j/i])?1:0; } } sc(n); sc(q); string ans=""; while(q--){ int op,x,y,z; sc(op); if(op==1){ sc(x); sc(y); a[x] = b[y]; //cout << a[x] << endl; }else if(op==2){ sc(x); sc(y); sc(z); a[x] = a[y]^a[z]; //cout << a[x] << endl; }else if(op==3){ sc(x); sc(y); sc(z); a[x] = a[y]&a[z]; //cout << a[x] << endl; }else{ sc(x); sc(y); bitset<maxn> bs = a[x]&c[y]; if(bs.count()&1) putchar('1'); else putchar('0'); } } cout << ans << endl; return 0; }
670e1efa8eecb11e419abb968cf8b6db574acf27
3b1d92de37ac8f555279386a5722c508cb38dac7
/WeeklyProjects/wa11/avlSort.cpp
bb0f4419444fa729a9208b40ffb06823c9851a0c
[]
no_license
jrross/csc300-data-structures
e0c701356439c54565c7aff4c239de4ca7ec176c
49ba2e3492b98030d51965175babfb90ae91dba1
refs/heads/master
2020-04-19T07:44:42.248095
2019-01-29T00:11:50
2019-01-29T00:11:50
168,056,104
0
0
null
null
null
null
UTF-8
C++
false
false
3,318
cpp
avlSort.cpp
#include "avlSort.h" AVLSort::AVLSort(std::string n) : Sort(n, false) { root = nullptr; } AVLSort::AVLSort(std::string n, std::vector<int> v) : Sort(n, false, v) { root = nullptr; } // You need to implement the sort method for AVLSort. See the InsertSort // implementation for an example void AVLSort::sort() { for(int i = 0; i < (int)values.size(); i++) this->addVal(values[i]); values.clear(); recurse(this->root); recurseDelete(this->root); } void AVLSort::addVal(int data) { if (root == nullptr) { root = new Node(data); return; } Node* temp = root; Node* prev = root; Node* prev2 = root; int d = 0; // an integer which signals if it is to the right or left int l; int r; while (temp != nullptr) { if(data >= temp->data) { d = 1; prev = temp; temp = temp-> right; } else { d = 2; prev = temp; temp = temp->left; } } temp = new Node(data); if ( d == 1) prev->right = temp; if ( d == 2) prev->left = temp; temp->parent = prev; temp->ht = 0; while(temp->parent != nullptr) { prev2 = prev; prev = temp; temp = temp->parent; temp->ht = prev->ht + 1; if ( temp->right == nullptr) r = -1; else r = temp->right->ht; if ( temp->left == nullptr) l = -1; else l = temp->left->ht; if ( l - r > 1 || l - r < -1) { rotate(temp, prev, prev2); } } root = temp; } void AVLSort::recurseDelete (Node *temp) { if (temp == nullptr) return; recurseDelete(temp->left); recurseDelete(temp->right); delete temp; } void AVLSort::recurse (Node *temp) { if(temp == nullptr) return; recurse(temp->left); values.push_back(temp->data); recurse(temp->right); } void rotate(Node* top, Node* middle, Node* bottom) { if (top->left == middle && middle->right == bottom)//left right { rotateLeft(middle, bottom, true); rotateRight(top, bottom, false); return; } if (top->left == middle && middle->left == bottom)//left left { rotateRight(top, middle, false); return; } if (top->right == middle && middle->right == bottom)//right right { rotateLeft(top, middle, false); return; } if (top->right == middle && middle->left == bottom)//right left { rotateRight(middle, bottom, true); rotateLeft(top, bottom, false); } } void rotateRight(Node* upper, Node* lower, bool twoRotations) { if (upper->parent) { if (upper->parent->left == upper) upper->parent->left = lower; if (upper->parent->right == upper) upper->parent->right = lower; } if (twoRotations == true) { upper->ht = upper->ht - 1; lower->ht = lower->ht + 1; } if (twoRotations == false) { upper->ht = upper->ht -2; } upper->left = lower->right; if ( lower->right) lower->right->parent = upper; lower->parent = upper->parent; lower->right = upper; upper->parent = lower; } void rotateLeft(Node* upper, Node* lower, bool twoRotations) { if (upper->parent) { if (upper->parent->left == upper) upper->parent->left = lower; if (upper->parent->right == upper) upper->parent->right = lower; } if (twoRotations == true) { upper->ht = upper->ht - 1; lower->ht = lower->ht + 1; } if (twoRotations == false) { upper->ht = upper->ht -2; } upper->right = lower->left; if(lower->left != nullptr) lower->left->parent = upper; lower->parent = upper->parent; lower->left = upper; upper->parent = lower; }
3cac6ab0165b41f8d6d7f1a0ea2d690f9796f829
b91dbdb3d19021318cbd831f4ec46d37ac770ae8
/kmcrypto/ikmcrypto.h
ee3c57c1ca7b3ed48d5ef0b8294fb02ea8a74ad8
[ "MIT" ]
permissive
matteofumagalli1275/kmsecure
ff714b9f2c404701ddb2c3445f4abcecd4fbf735
8f86d252e23f5100e17766ea75f516c48ca8b9a5
refs/heads/master
2021-06-17T04:21:21.734031
2017-06-05T18:17:31
2017-06-05T18:17:31
45,756,135
0
0
null
null
null
null
UTF-8
C++
false
false
678
h
ikmcrypto.h
#ifndef IKMCRYPTO_H #define IKMCRYPTO_H #include <stdint.h> #include <cstddef> #include <vector> #include <string> #include <exception> #include <stdexcept> class ikmcrypto { public: virtual void set_key(const char *key, size_t byte_length); virtual void set_key_with_iv(const char *key, size_t byte_length, const char* iv, size_t iv_length); virtual uint16_t get_minimum_block_size() = 0; virtual std::vector<char> encrypt(const std::vector<char> &src) = 0; virtual std::vector<char> decrypt(const std::vector<char> &src) = 0; }; class kmcrypto_exception: public std::runtime_error { public: kmcrypto_exception(std::string what_message); }; #endif
85319e32b6cde5d5b4a8bdb0893e24a62e91678a
13cdba7eabef5c8185f20de5e1e2a108c1825876
/SWEA/1249.cpp
fa731ca5e07edc86c2d025714658c6dfc5c82df4
[]
no_license
Hsue66/Algo
7b43ec88a0fb90c01aa0bca74863daee4689f416
4c02a71edaf4ac994520f4ab017cb5f27edaffc2
refs/heads/master
2021-07-05T23:23:26.174809
2021-05-18T14:08:00
2021-05-18T14:08:00
43,046,465
0
0
null
null
null
null
UTF-8
C++
false
false
1,795
cpp
1249.cpp
#include<stdio.h> #define INF 987654321 #define MAX 90000 int Min,N; int MAP[100][100],v[100][100]; int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; struct Node{ int x, y; }; struct Queue{ int fidx; int bidx; Node node[MAX]; void init(){ fidx = bidx = 0; } int empty(){ return fidx == bidx; } void push(int a,int b){ bidx = (bidx+1)%MAX; node[bidx].x = a; node[bidx].y = b; } void pop(){ fidx++; } Node front(){ return node[fidx+1]; } }; void init(){ for(int i=0; i<N; i++){ for(int j=0; j<N; j++) v[i][j] = INF; } } int min(int a, int b){ if(a < b) return a; else return b; } int main(){ int testcase; scanf("%d",&testcase); for(int tc =0 ; tc<testcase; tc++){ scanf("%d",&N); for(int i=0; i<N; i++){ for(int j=0; j<N; j++) scanf("%1d",&MAP[i][j]); } init(); Min = INF; Queue q; q.init(); q.push(0,0); v[0][0] = 0; while(!q.empty()){ int x = q.front().x; int y = q.front().y; q.pop(); for(int i=0; i<4; i++){ int tx = x+dir[i][0]; int ty = y+dir[i][1]; if(0<=tx && tx <N && 0<=ty && ty <N ){ int tmp = v[x][y]+MAP[tx][ty]; if(tmp < v[tx][ty]){ v[tx][ty] = tmp; if(tmp < Min) q.push(tx,ty); } } } } printf("#%d %d\n",tc+1,v[N-1][N-1] ); } }
0b60db9a7f3343db6e6e8d07ce4e0fc9552b30e2
a10bdce64752b3723d2c8910d56bcfa20f63080f
/bioblocksTranslation/blocks/logicblocks.h
b8bda2e7fc8c5a04e5c79771a24d268952cdeb91
[]
no_license
ponxosio/bioblocksTranslation
e53058f5cd28c941ee62eae52e7c3367a591e606
710abe68c93f8887f95778edf83525c56e73440a
refs/heads/master
2020-12-30T17:51:01.827977
2017-09-06T10:25:55
2017-09-06T10:25:55
89,360,551
0
0
null
null
null
null
UTF-8
C++
false
false
3,386
h
logicblocks.h
#ifndef LOGICBLOCKS_H #define LOGICBLOCKS_H #define LOGIC_COMPARE_STR "logic_compare" #define LOGIC_OPERATION_STR "logic_operation" #define LOGIC_NEGATE_STR "logic_negate" #define LOGIC_BOOLEAN_STR "logic_boolean" #define LOGIC_NULL_STR "logic_null" #define MATH_NUMBER_PROPERTY_STR "math_number_property" #define BLOCKLY_EQ_STR "EQ" #define BLOCKLY_NEQ_STR "NEQ" #define BLOCKLY_LT_STR "LT" #define BLOCKLY_LTE_STR "LTE" #define BLOCKLY_GT_STR "GT" #define BLOCKLY_GTE_STR "GTE" #define BLOCKLY_AND_STR "AND" #define BLOCKLY_OR_STR "OR" #define BLOCKLY_TRUE_STR "TRUE" #define BLOCKLY_FALSE_STR "FALSE" #define BLOCKLY_EVEN_STR "EVEN" #define BLOCKLY_ODD_STR "ODD" #define BLOCKLY_PRIME_STR "PRIME" #define BLOCKLY_WHOLE_STR "WHOLE" #define BLOCKLY_POSITIVE_STR "POSITIVE" #define BLOCKLY_NEGATIVE_STR "NEGATIVE" #define BLOCKLY_DIVISIBLE_BY_STR "DIVISIBLE_BY" #include <memory> #include <stdexcept> //lib #include <json.hpp> //local #include <protocolGraph/ProtocolGraph.h> #include <protocolGraph/operables/comparison/ComparisonOperable.h> #include <protocolGraph/operables/comparison/BooleanComparison.h> #include <protocolGraph/operables/comparison/SimpleComparison.h> #include <protocolGraph/operables/comparison/characteristiccheck.h> #include <protocolGraph/operables/comparison/protocolboolf.h> #include <protocolGraph/operables/mathematics/protocolmathf.h> #include <utils/utilsjson.h> #include "bioblocksTranslation/blocks/blocksutils.h" class MathBlocks; class LogicBlocks { public: LogicBlocks(std::shared_ptr<ProtocolGraph> protocolPtr, std::shared_ptr<MathBlocks> mathTrans = NULL); virtual ~LogicBlocks(); std::shared_ptr<ComparisonOperable> translateLogicBlock(const nlohmann::json & logicJSONObj) throw(std::invalid_argument); inline void setMathTrans(std::shared_ptr<MathBlocks> mathTrans) { this->mathTrans = mathTrans; } protected: std::shared_ptr<ProtocolGraph> protocolPtr; std::shared_ptr<MathBlocks> mathTrans; std::shared_ptr<ComparisonOperable> logicCompareOperation(const nlohmann::json & logicCompareObj) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> logicOperationOperation(const nlohmann::json & logicOperationObj) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> logicNegateOperation(const nlohmann::json & logicNegateObj) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> logicBooleanOperation(const nlohmann::json & logicBooleanObj) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> logicNullOperation(const nlohmann::json & logicNullObj) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> mathNumberPropertyOperation(const nlohmann::json & mathNumberPropertyObj) throw(std::invalid_argument); SimpleComparison::ComparisonOperator getComparisonOperator(const std::string & opStr) throw(std::invalid_argument); BooleanComparison::BooleanOperator getBooleanOperator(const std::string & opStr) throw(std::invalid_argument); CharacteristicCheck::CheckOperations getCheckOperator(const std::string & opStr) throw(std::invalid_argument); std::shared_ptr<Tautology> getBoolConstant(const std::string & opStr) throw(std::invalid_argument); std::shared_ptr<ComparisonOperable> getNumberCheckOp(const std::string & opStr) throw(std::invalid_argument); }; #endif // LOGICBLOCKS_H
bc997836ab275c7a19d6403f8159cc21a40a91cc
59047c50edad6f42ba3312c5e3f92a66d57afd0d
/src/add-ons/kernel/file_systems/packagefs/package/PackageLeafNode.cpp
2c27f45e9921d7e87fd2749de329d2794d443427
[ "BSD-2-Clause" ]
permissive
stasinek/BEFS-Explorer
b3d47954d8589e69d17502fdebe0f7f1adf9f161
fa36e7745d3bbf51184122dfc25e411a933af539
refs/heads/master
2023-05-24T23:45:40.826752
2023-05-15T12:54:11
2023-05-15T12:54:11
79,050,937
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
PackageLeafNode.cpp
/* * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include <PackageLeafNode.h> PackageLeafNode::PackageLeafNode(Package* package, mode_t mode) : PackageNode(package, mode) { } PackageLeafNode::~PackageLeafNode() { } String PackageLeafNode::SymlinkPath() const { return String(); } status_t PackageLeafNode::Read(off_t offset, void* buffer, size_t* bufferSize) { return EBADF; } status_t PackageLeafNode::Read(io_request* request) { return EBADF; }
3bc56bb89e050805f60d4c04c7801b511ad2e7f9
bba23e9d20a6ba65b509b0a1196d2e06c6bc75af
/client/Controller/CerebotClient.hpp
499b95dc62a20693b62287a8c99a5a64ae0c4e95
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
gaybro8777/Pic32Telemetry
2c54e5a34ee6788f2f480bae3d3527b8962809d3
8418a12517e74007777536c97f0a0942c18bbf10
refs/heads/master
2023-07-22T02:11:52.209591
2016-02-24T18:54:30
2016-02-24T18:54:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,475
hpp
CerebotClient.hpp
#ifndef CEREBOT_CLIENT_H #define CEREBOT_CLIENT_H #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <stdio.h> #include <string.h> #include <thread> #include <string> #include <iostream> #include <vector> #include "../../my_types.h" #include "./UiServer.hpp" #include "../../encoding/encoding.h" /* Connectivity issues: CANT CONNECT ???? CHECK BAUD RATES!!! CANT USE BLUETOOTH? To create /dev/rfcomm0 use "sudo rfcomm bind 0 MAC_ADDRESS_OF_PMODBT2" -sudo rfcomm bind 0 00:06:66:43:96:73 -program must be run with sudo priviliges: sudo ./serial -to get the address of PMODBt2 use "hcitool scan" to scan for the device when it is powered on Starting bluetooth from the command line To stop : sudo /etc/init.d/bluetooth stop To start : sudo /etc/init.d/bluetooth start To restart : sudo /etc/init.d/bluetooth restart */ /* baudrate settings are defined in <asm/termbits.h>, which is included by <termios.h> */ #define BAUDRATE B115200 //#define BAUDRATE B9600 /* change this definition for the correct port */ //#define MODEMDEVICE "/dev/rfcomm0" // use for bluetooth connection under linux: // *if /dev/rfcomm0 does not exist, use "sudo rfcomm bind 0 ADDR_OF_PMODBT2" and prior use "hcitool scan" to find ADDR_OF_PMODBT2 // *bt2 addr should be 00:06:66:43:96:73 so use >>> sudo rfcomm bind 0 00:06:66:43:96:73 //#define MODEMDEVICE "/dev/ttyUSB1" //one or the other... usb1 or usb0, wherever the cable is hooked up //#define MODEMDEVICE "/dev/ttyUSB1" // <-- direct serial over USB #define BT_DEVICE "/dev/rfcomm0" // <--if using rfcomm bind etc, over bluetooth radio #define _POSIX_SOURCE 1 /* POSIX compliant source */ #define FALSE 0 #define TRUE 1 using std::cout; using std::endl; using std::string; using std::vector; // vector /* typedef struct deviceVector{ short int X; short int Y; short int Z; short int T; //temp in celsius short int P; //pressure in Pa }VEC; */ /* Controller is the main actor behind the comms and control to and from the cerebot. Controller has a ui-thread (a server) and a primary thread for sending commands and updating internal ai logic. class CerebotController{ public: CerebotController(char* sockpath, char* btAddr) : CerebotClient(btAddr), UiServer(sockpath), UiClient(sockpath); CerebotController() = delete; CerebotController(char* sockpath, char* btaddr); ~CerebotController(); void ReadState(); void SendCommand(); void Init(); // spins off ui process: a client and server pair void Run(); private: Thread uiServerThread; CerebotClient cerebotClient; //UiClient uiClient; UiServer uiServer; }; */ class CerebotClient { public: CerebotClient() = delete; CerebotClient(const char* btAddress, const char* srvPath); ~CerebotClient(); char* GetBtAddr(); void ReadCerebotData(); void SendCerebotData(); void SendUiData(); //tell thread data is ready void Test(); private: void putState(struct imuVector* vec); void putImu(struct imuVector* vec); bool initCerebotComms(); bool initCerebotComms2(); int getVec(IMU* vec, char buf[256]); UiServer uiServer; int btfd; struct termios oldtio, newtio; vector<IMU> vecRing; int imuSize; char buf[1024]; char btAddr[64]; //an address of the form XX:XX:XX:XX:XX:XX. Use 'hcitool scan' to find yours. }; #endif
09ac08fad32e328984ebb0ea08a636cdee98cc14
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-s3control/include/aws/s3control/model/SseKmsEncryptedObjects.h
de2a9af03ea965705f0efe9a72cf86e1177774f9
[ "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
3,076
h
SseKmsEncryptedObjects.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/s3control/S3Control_EXPORTS.h> #include <aws/s3control/model/SseKmsEncryptedObjectsStatus.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace S3Control { namespace Model { /** * <p>A container for filter information that you can use to select S3 objects that * are encrypted with Key Management Service (KMS).</p> <p>This is not * supported by Amazon S3 on Outposts buckets.</p> <p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/SseKmsEncryptedObjects">AWS * API Reference</a></p> */ class SseKmsEncryptedObjects { public: AWS_S3CONTROL_API SseKmsEncryptedObjects(); AWS_S3CONTROL_API SseKmsEncryptedObjects(const Aws::Utils::Xml::XmlNode& xmlNode); AWS_S3CONTROL_API SseKmsEncryptedObjects& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); AWS_S3CONTROL_API void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const; /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline const SseKmsEncryptedObjectsStatus& GetStatus() const{ return m_status; } /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; } /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline void SetStatus(const SseKmsEncryptedObjectsStatus& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline void SetStatus(SseKmsEncryptedObjectsStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); } /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline SseKmsEncryptedObjects& WithStatus(const SseKmsEncryptedObjectsStatus& value) { SetStatus(value); return *this;} /** * <p>Specifies whether Amazon S3 replicates objects that are created with * server-side encryption by using an KMS key stored in Key Management Service.</p> */ inline SseKmsEncryptedObjects& WithStatus(SseKmsEncryptedObjectsStatus&& value) { SetStatus(std::move(value)); return *this;} private: SseKmsEncryptedObjectsStatus m_status; bool m_statusHasBeenSet = false; }; } // namespace Model } // namespace S3Control } // namespace Aws
359eb68ace7caf6267409f8dd50e5235847ca48e
b819c29719ecb14440dab9d5cbc49d9901fc2d04
/Client/Header/Shot_WhiteFadeOut.h
6035b46322d77bf843bf0be4c887ccaa7a847eca
[]
no_license
Underdog-113/3D_portfolio
d338f49d518702b191e590dc22166c9f28c08b14
6b877ff5272bea2e6d2a2bd53e63b6ee4728cd9c
refs/heads/develop
2023-07-07T20:30:00.759582
2021-07-27T06:01:52
2021-07-27T06:01:52
371,051,333
0
1
null
2021-06-13T14:30:32
2021-05-26T13:52:07
C++
UTF-8
C++
false
false
475
h
Shot_WhiteFadeOut.h
#pragma once #include "Shot.h" class CShot_WhiteFadeOut : public CShot { public: struct Desc { Engine::CFadeInOutC* pWhiteFade = nullptr; }; public: CShot_WhiteFadeOut(); ~CShot_WhiteFadeOut(); public: void Ready(CTake * pTake, _float startTimeline, _float endTimeline, void* pDesc, _float enterTimeline); virtual void Enter() override; virtual void Action() override; virtual void Cut() override; virtual void Rollback() override; private: Desc m_desc; };
afa4b3389d8ecf7a22039a1200c7fc104b2fe316
b73fbe654a268f39492c5cc3545729b7efdd765e
/array/SpiralMatrixII.h
38b6c6c8ca8331e5fbc583f1be76e6ff3be4fce8
[]
no_license
Yory-Z/Algorithm
b33cf31bc1e6f42ba8dea4aa39d4995074c45ee0
b3450e499d691b30c1229ba3843331a0d0f96f53
refs/heads/master
2020-04-25T14:23:54.435127
2019-03-22T02:49:05
2019-03-22T02:49:05
172,840,352
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
SpiralMatrixII.h
// // Created by Yory on 2019/2/22. // #ifndef ALGORITHM_SPIRALMATRIXII_H #define ALGORITHM_SPIRALMATRIXII_H #include <iostream> #include <vector> using namespace std; class SpiralMatrixII { public: void test() { int n = 5; vector<vector<int>> res = generateMatrix(n); for (vector<int> vec : res) { for (int i : vec) { cout<<i<<' '; } cout<<endl; } } private: vector<vector<int>> generateMatrix(int n) { int r1 = 0, r2 = n - 1; int c1 = 0, c2 = n - 1; vector<vector<int>> matrix = vector<vector<int>>(n, vector<int>(n)); int value = 0; while (r1 <= r2 && c1 <= c2) { //insert top for (int i = c1; i <= c2; ++i) { matrix[r1][i] = ++value; } //insert right for (int i = r1 + 1; i < r2; ++i) { matrix[i][c2] = ++value; } //insert bottom for (int i = c2; i > c1; --i) { matrix[r2][i] = ++value; } //insert left for (int i = r2; i > r1; --i) { matrix[i][c1] = ++value; } ++r1; --r2; ++c1; --c2; } return matrix; } }; #endif //ALGORITHM_SPIRALMATRIXII_H
84929573978d3f86f559d216e24d615e550f4b5d
76bb2f1b416d78c2b4c951f071657b93e8f915c1
/xlib/hall.cpp
9223a405b4e648ae7d03136a7bdbda1f3ec7f530
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
pcxod/olex2
2f48c06da586fb47d308defe9915bf63be5c8f4d
17d2718d09ad61ad961b98e966d981bb50663e3e
refs/heads/master
2023-08-11T20:01:31.660209
2023-07-21T10:55:35
2023-07-21T10:55:35
219,048,584
9
0
null
null
null
null
UTF-8
C++
false
false
15,362
cpp
hall.cpp
/****************************************************************************** * Copyright (c) 2004-2011 O. Dolomanov, OlexSys * * * * This file is part of the OlexSys Development Framework. * * * * This source file is distributed under the terms of the licence located in * * the root folder. * ******************************************************************************/ #include "hall.h" #include "symmlib.h" #include "symmparser.h" //............................................................................. void HallSymbol::init() { if (trans.IsEmpty()) { trans.AddNew(vec3d(0.5, 0, 0), "a"); trans.AddNew(vec3d(0, 0.5, 0), "b"); trans.AddNew(vec3d(0, 0, 0.5), "c"); trans.AddNew(vec3d(0.5, 0.5, 0.5), "n"); trans.AddNew(vec3d(0.25, 0, 0), "u"); trans.AddNew(vec3d(0, 0.25, 0), "v"); trans.AddNew(vec3d(0, 0, 0.25), "w"); trans.AddNew(vec3d(0.25, 0.25, 0.25), "d"); rotx.AddNew(rotation_id::get(mat3d( 1, 0, 0, 0,-1, 0, 0, 0,-1)), "2x"); rotx.AddNew(rotation_id::get(mat3d( 1, 0, 0, 0, 0,-1, 0, 1,-1)), "3x"); rotx.AddNew(rotation_id::get(mat3d( 1, 0, 0, 0, 0,-1, 0, 1, 0)), "4x"); rotx.AddNew(rotation_id::get(mat3d( 1, 0, 0, 0, 1,-1, 0, 1, 0)), "6x"); roty.AddNew(rotation_id::get(mat3d( 0, 0, 1, 0, 1, 0, -1, 0, 1)), "6y"); roty.AddNew(rotation_id::get(mat3d( 0, 0, 1, 0, 1, 0, -1, 0, 0)), "4y"); roty.AddNew(rotation_id::get(mat3d(-1, 0, 1, 0, 1, 0, -1, 0, 0)), "3y"); roty.AddNew(rotation_id::get(mat3d(-1, 0, 0, 0, 1, 0, 0, 0,-1)), "2y"); rotz.AddNew(rotation_id::get(mat3d( 1,-1, 0, 1, 0, 0, 0, 0, 1)), "6z"); rotz.AddNew(rotation_id::get(mat3d( 0,-1, 0, 1, 0, 0, 0, 0, 1)), "4z"); rotz.AddNew(rotation_id::get(mat3d( 0,-1, 0, 1,-1, 0, 0, 0, 1)), "3z"); rotz.AddNew(rotation_id::get(mat3d(-1, 0, 0, 0,-1, 0, 0, 0, 1)), "2z"); // x rotx1.AddNew(rotation_id::get(mat3d(-1, 0, 0, 0, 0,-1, 0,-1, 0)), "2"); rotx1.AddNew(rotation_id::get(mat3d(-1, 0, 0, 0, 0, 1, 0, 1, 0)), "2\""); // y roty1.AddNew(rotation_id::get(mat3d( 0, 0,-1, 0,-1, 0, -1, 0, 0)), "2"); roty1.AddNew(rotation_id::get(mat3d( 0, 0, 1, 0,-1, 0, 1, 0, 0)), "2\""); // z rotz1.AddNew(rotation_id::get(mat3d( 0,-1, 0, -1, 0, 0, 0, 0,-1)), "2"); rotz1.AddNew(rotation_id::get(mat3d( 0, 1, 0, 1, 0, 0, 0, 0,-1)), "2\""); rot3.AddNew(rotation_id::get(mat3d( 0, 0, 1, 1, 0, 0, 0, 1, 0)), "3*"); TPtrList<TTypeList<olx_pair_t<int,olxstr> > > rots; rots << rotx << roty << rotz << rot3; for (size_t i=0; i < rots.Count(); i++) { for (size_t j=0; j < rots[i]->Count(); j++) r_dict.Add((*rots[i])[j].GetB(), (*rots[i])[j].GetA()); } r_dict.Add("1", rotation_id::get(mat3d().I())); // a-b r_dict.Add("2'", rotz1[0].GetA()); for (size_t i=0; i < trans.Count(); i++) t_dict.Add(trans[i].GetB(), &trans[i].a); } } //............................................................................. olxstr HallSymbol::FindT(const vec3d& t, int order) const { for( size_t j=0; j < trans.Count(); j++ ) { if( trans[j].GetA().QDistanceTo(t) < 1e-6 ) return trans[j].GetB(); } for( size_t j=0; j < trans.Count(); j++ ) { for( size_t k=j+1; k < trans.Count(); k++ ) { if( (trans[j].GetA()+trans[k].GetA()).QDistanceTo(t) < 1e-6 ) return olxstr(trans[j].GetB()) << trans[k].GetB(); } } for( size_t j=0; j < trans.Count(); j++ ) { for( size_t k=j+1; k < trans.Count(); k++ ) { for( size_t l=k+1; l < trans.Count(); l++ ) { if( (trans[j].GetA()+trans[k].GetA()+trans[l].GetA()).QDistanceTo(t) < 1e-6 ) return olxstr(trans[j].GetB()) << trans[k].GetB() << trans[l].GetB(); } } } const double m = 12./order; return olxstr(" (") << t[0]*m << ' ' << t[1]*m << ' ' << t[2]*m << ')'; } //............................................................................. olxstr HallSymbol::FindTR(const vec3d& t, int order) const { const double v = t[0] != 0 ? t[0] : (t[1] != 0 ? t[1] : t[2]); if( v == 0 ) return EmptyString(); if( order <= 2 || t.Length() != v ) return FindT(t, order); else if( order == 3 ) { if( fabs(v - 1./3) < 0.05 ) return '1'; if( fabs(v - 2./3) < 0.05 ) return '2'; } else if( order == 4 ) { if( fabs(v - 1./4) < 0.05 ) return '1'; if( fabs(v - 3./4) < 0.05 ) return '3'; } else if( order == 6 ) { if( fabs(v - 1./6) < 0.05 ) return '1'; if( fabs(v - 2./6) < 0.05 ) return '2'; if( fabs(v - 4./6) < 0.05 ) return '4'; if( fabs(v - 5./6) < 0.05 ) return '5'; } return FindT(t, order); } //............................................................................. int HallSymbol::FindR(olxstr& hs, TTypeList<symop>& matrs, const TTypeList<olx_pair_t<int,olxstr> >& rot, bool full) const { int previous = 0; for( size_t i=0; i < rot.Count(); i++ ) { for( size_t j=0; j < matrs.Count(); j++ ) { if( matrs.IsNull(j) ) continue; const symop& so = matrs[j]; bool matched = false; if( rot[i].GetA() == so.rot_id ) { hs << ' '; matched = true; } else if( rot[i].GetA() == rotation_id::negate(so.rot_id) ) { hs << " -"; matched = true; } if( matched ) { if( full ) hs << rot[i].GetB(); else hs << rot[i].GetB().CharAt(0); previous = rot[i].GetB().CharAt(0)-'0'; hs << FindTR(so.t, previous); matrs.NullItem(j); break; } } if( previous != 0 ) break; } if( previous != 0 ) matrs.Pack(); return previous; } //............................................................................. olxstr HallSymbol::EvaluateEx_(int latt_, const smatd_list& matrices_) const { smatd_list all_matrices; TSymmLib::GetInstance().ExpandLatt(all_matrices, matrices_, latt_); return Evaluate(SymmSpace::GetInfo(all_matrices)); } //............................................................................. olxstr HallSymbol::Evaluate_(int latt, const smatd_list& matrices) const { olxstr hs; if( latt > 0 ) hs << '-'; hs << TCLattice::SymbolForLatt(olx_abs(latt)); if( matrices.IsEmpty() || (matrices.Count() == 1 && matrices[0].IsI())) hs << ' ' << '1'; else { TTypeList<HallSymbol::symop> matrs; for( size_t i=0; i < matrices.Count(); i++ ) { symop& so = matrs.AddNew(); so.rot_id = rotation_id::get(matrices[i].r); so.t = matrices[i].t; } int rz = FindR(hs, matrs, rotz, false); // c direction if( rz != 0 ) { int rx = FindR(hs, matrs, rotx, false); if( rx != 0 ) { if( FindR(hs, matrs, rot3, false) == 0 ) FindR(hs, matrs, rotx1, true); } else FindR(hs, matrs, rotz1, true); } else { // no c direction FindR(hs, matrs, rotx, true); FindR(hs, matrs, roty, true); if( FindR(hs, matrs, rot3, true) != 0 ) FindR(hs, matrs, rotz1, true); } } return hs; } //.......................................................................................... olxstr HallSymbol::Evaluate_(const SymmSpace::Info& si) const { olxstr hs = Evaluate(si.centrosymmetric ? si.latt : -si.latt, si.matrices); // explicit inversion if (!si.inv_trans.IsNull(1e-3)) { if (si.centrosymmetric) // must be! hs = hs.SubStringFrom(1); hs << " -1" << FindT(si.inv_trans, 12); } return hs; } //............................................................................. vec3d HallSymbol::get_screw_axis_t(int dir, int order) const { vec3d rv; rv[dir-1] = (double)order/12; return rv; } //............................................................................. int HallSymbol::find_diagonal(int axis, olxch which) const { int index = which == '\'' ? 0 : 1; if (axis == 1) return rotx1[index].GetA(); if (axis == 2) return roty1[index].GetA(); if (axis == 3) return rotz1[index].GetA(); throw TInvalidArgumentException(__OlxSourceInfo, olxstr("axis direction: ") << axis << ", which: " << which); } //............................................................................. SymmSpace::Info HallSymbol::Expand_(const olxstr &_hs) const { smatdd change_of_basis; change_of_basis.r.I(); SymmSpace::Info info; olxstr hs = _hs; // deal with the change of basis { size_t obi = _hs.IndexOf('('); if (obi != InvalidIndex) { size_t cbi = _hs.FirstIndexOf(')', obi); if (cbi == InvalidIndex) { throw TInvalidArgumentException(__OlxSourceInfo, "change of basis notation"); } hs = _hs.SubStringTo(obi); olxstr cbs = _hs.SubString(obi+1, cbi-obi-1); if (cbs.IndexOf(',') != InvalidIndex) { try { change_of_basis = TSymmParser::SymmToMatrix(cbs); } catch (const TExceptionBase &e) { throw TFunctionFailedException(__OlxSourceInfo, e); } } else { TStrList toks(cbs, ' '); if (toks.Count() != 3) { throw TInvalidArgumentException(__OlxSourceInfo, "change of basis notation"); } change_of_basis.t[0] = toks[0].ToDouble()/12; change_of_basis.t[1] = toks[1].ToDouble()/12; change_of_basis.t[2] = toks[2].ToDouble()/12; } } } TStrList toks(hs, ' '); if (toks.Count() < 1) { throw TInvalidArgumentException(__OlxSourceInfo, olxstr("Hall symbol: ").quote() << _hs); } info.centrosymmetric = toks[0].StartsFrom('-'); if (info.centrosymmetric && toks[0].Length() == 1) { throw TInvalidArgumentException(__OlxSourceInfo, olxstr("Hall symbol: ").quote() << _hs); } const int ii_id = rotation_id::get(-mat3i().I()); const int i_id = r_dict.Get('1'); info.latt = TCLattice::LattForSymbol( toks[0].CharAt(info.centrosymmetric ? 1 : 0)); int previous = 0, dir = 0; SortedObjectList<int, TPrimitiveComparator> r_hash; for (size_t i=1; i < toks.Count(); i++) { olxstr axis; bool neg = toks[i].StartsFrom('-'); if (neg) { toks[i] = toks[i].SubStringFrom(1); } if (toks[i].Length() > 1 ) { axis = toks[i].SubStringTo(2); size_t ai = r_dict.IndexOf(axis); if (ai == InvalidIndex) { if (((axis.CharAt(1) == '\'') || (axis.CharAt(1) == '"')) && dir != 0) { previous = axis.CharAt(0)-'0'; smatd& m = info.matrices.AddNew(); m.r = rotation_id::get(find_diagonal(dir, axis.CharAt(1))); if (neg) { m.r *= -1; } toks[i] = toks[i].SubStringFrom(2); } else { axis.SetLength(0); } } else { previous = axis.CharAt(0)-'0'; smatd& m = info.matrices.AddNew(); m.r = rotation_id::get(r_dict.GetValue(ai)); if (neg) { m.r *= -1; } toks[i] = toks[i].SubStringFrom(2); } } if (axis.IsEmpty()) { axis = toks[i].SubStringTo(1); size_t ai = r_dict.IndexOf(axis); int current = axis.CharAt(0)-'0'; if (ai == InvalidIndex) { if (i == 1) { axis << 'z'; dir = 3; } else if (i == 2) { if (current == 2) { if (previous == 2 || previous == 4) { dir = 1; axis << 'x'; } else if (previous == 3 || previous == 6) { axis << '\''; } } } else if (i == 3) { if (current != 3) { throw TInvalidArgumentException(__OlxSourceInfo, olxstr("Axis symbol: ").quote() << axis << " 3/3* is expected"); } axis << '*'; } ai = r_dict.IndexOf(axis); if (ai == InvalidIndex) { throw TInvalidArgumentException(__OlxSourceInfo, olxstr("Axis symbol: ").quote() << axis); } } smatd& m = info.matrices.AddNew(); m.r = rotation_id::get(r_dict.GetValue(ai)); if (neg) { m.r *= -1; } toks[i] = toks[i].SubStringFrom(1); previous = axis.CharAt(0)-'0'; } vec3d t; for (size_t j=0; j < toks[i].Length(); j++) { olxch t_s = toks[i].CharAt(j); if (olxstr::o_isdigit(t_s)) { t += get_screw_axis_t(dir, (t_s-'0')*12/(axis.CharAt(0)-'0')); } else { size_t ti = t_dict.IndexOf(t_s); if (ti == InvalidIndex) { throw TInvalidArgumentException(__OlxSourceInfo, olxstr("Translation symbol: ").quote() << toks[i].CharAt(j)); } t += *t_dict.GetValue(ti); } } info.matrices.GetLast().t += t; int m_id = rotation_id::get(info.matrices.GetLast().r); if (m_id == ii_id) { info.inv_trans = info.matrices.GetLast().t; info.centrosymmetric = true; info.matrices.Delete(info.matrices.Count()-1); } else if(m_id == i_id) { if (info.matrices.GetLast().t.IsNull(1e-3)) { info.matrices.Delete(info.matrices.Count() - 1); } } else { r_hash.Add(m_id); } } bool add_I = true; if (!change_of_basis.IsI()) { smatd cob_i = change_of_basis.Inverse(); if (info.latt != 1) { info.matrices.Insert(0, new smatd).r.I(); smatd_list matrices = info.expand(); for (size_t i = 0; i < matrices.Count(); i++) { smatdd m = matrices[i]; m = change_of_basis * m * cob_i; matrices[i].t = m.t; for (int ii = 0; ii < 3; ii++) { for (int jj = 0; jj < 3; jj++) { matrices[i].r[ii][jj] = olx_round(m.r[ii][jj]); } } } info = SymmSpace::GetInfo(matrices); add_I = false; } else { for (size_t i = 0; i < info.matrices.Count(); i++) { smatdd m = info.matrices[i]; m = change_of_basis * m * cob_i; info.matrices[i].t = m.t; for (int ii = 0; ii < 3; ii++) { for (int jj = 0; jj < 3; jj++) { info.matrices[i].r[ii][jj] = olx_round(m.r[ii][jj]); } } } } } for (size_t i=0; i < info.matrices.Count(); i++) { for (size_t j=i; j < info.matrices.Count(); j++) { smatd m = info.matrices[i]*info.matrices[j]; int id = rotation_id::get(m.r); if (i_id == id) { continue; } if (r_hash.IndexOf(id) == InvalidIndex) { r_hash.Add(id); info.matrices.AddCopy(m); } } } if (add_I) { info.matrices.InsertNew(0).r.I(); } info.normalise( TSymmLib::GetInstance().GetLatticeByNumber(info.latt).GetVectors()); return info; }
51b2e2b31caba77d6c0710271c74e43a516ee2cc
f981471ebe62731ec6e1ea2c3e09907f49d9d99a
/Engine/Utility/ParameterFile.cpp
d997fa0ac68411beaf7953e5cfb45363a7eed27a
[]
no_license
techmatt/layer-extraction
a784be9681494ed7cc8d648859aea990b9f01200
0892665aa33d1fd072ebba01000d5825d1817387
refs/heads/master
2021-01-23T09:28:21.183874
2017-01-10T19:13:17
2017-01-10T19:13:17
32,225,935
0
0
null
null
null
null
UTF-8
C++
false
false
8,875
cpp
ParameterFile.cpp
/* ParameterFile.cpp Written by Matthew Fisher the Parameter class loads a paramater file as a simple set of "Parameter=Option" lines. */ ParameterFile::ParameterFile(const String &filename) { Vector<String> baseDirectories; AddFile(filename, baseDirectories); } void ParameterFile::AddFile(const String &filename) { Vector<String> baseDirectories; AddFile(filename, baseDirectories); } void ParameterFile::AddFile(const String &filename, const Vector<String> &baseDirectories) { String finalFilename = filename; bool fileFound = Utility::FileExists(finalFilename); for(UINT baseDirectoryIndex = 0; baseDirectoryIndex < baseDirectories.Length() && !fileFound; baseDirectoryIndex++) { const String &curDirectory = baseDirectories[baseDirectoryIndex]; finalFilename = curDirectory + filename; fileFound = Utility::FileExists(finalFilename); } PersistentAssert(fileFound, "Parameter file not found"); Vector<String> childBaseDirectories = baseDirectories; if(filename.Contains("/") || filename.Contains("\\")) { Vector<String> parts = filename.PartitionAboutIndex(filename.FindAndReplace("\\", "/").FindLastIndex('/')); childBaseDirectories.PushEnd(parts[0] + "/"); } ifstream File(finalFilename.CString()); Vector<String> Lines; Utility::GetFileLines(File, Lines); for(UINT i = 0; i < Lines.Length(); i++) { String &CurLine = Lines[i]; if(CurLine.StartsWith("#include ")) { Vector<String> Partition = CurLine.Partition("#include "); PersistentAssert(Partition.Length() == 1, String("Invalid line in parameter file: ") + CurLine); String IncludeFilename = Partition[0]; IncludeFilename.Partition("\"", Partition); PersistentAssert(Partition.Length() == 1, String("Invalid line in parameter file: ") + CurLine); AddFile(Partition[0], childBaseDirectories); } else if(CurLine.Length() > 2 && CurLine[0] != '#') { Vector<String> Partition = CurLine.Partition('='); PersistentAssert(Partition.Length() == 2, String("Invalid line in parameter file: ") + CurLine); Parameters.PushEnd(ParameterEntry(Partition[0], Partition[1])); } } } ParameterEntry* ParameterFile::FindParameter(const String &ParameterName) { for(auto ParameterIterator = Parameters.begin(); ParameterIterator != Parameters.end(); ParameterIterator++) { auto &CurEntry = *ParameterIterator; if(CurEntry.Name == ParameterName) { return &CurEntry; } } return NULL; } const ParameterEntry* ParameterFile::FindParameter(const String &ParameterName) const { for(auto ParameterIterator = Parameters.begin(); ParameterIterator != Parameters.end(); ParameterIterator++) { auto &CurEntry = *ParameterIterator; if(CurEntry.Name == ParameterName) { return &CurEntry; } } return NULL; } void ParameterFile::OutputAllParameters(ostream &os, const String &EndLine) const { for(UINT parameterIndex = 0; parameterIndex < Parameters.Length(); parameterIndex++) { const ParameterEntry &curParameter = Parameters[parameterIndex]; os << curParameter.Name << " = " << curParameter.Value << EndLine; } } String ParameterFile::GetRequiredString(const String &ParameterName) const { for(UINT i = 0; i < Parameters.Length(); i++) { if(Parameters[i].Name.MakeLowercase() == ParameterName.MakeLowercase()) { return Parameters[i].Value; } } PersistentSignalError(String("Parameter not found: ") + ParameterName); return String("Parameter not found"); } String ParameterFile::GetOptionalString(const String &ParameterName) const { for(UINT i = 0; i < Parameters.Length(); i++) { if(Parameters[i].Name.MakeLowercase() == ParameterName.MakeLowercase()) { return Parameters[i].Value; } } return String(); } bool ParameterFile::GetBoolean(const String &ParameterName) const { String Str = GetRequiredString(ParameterName); Str = Str.MakeLowercase(); if(Str == "true") { return true; } else if(Str == "false") { return false; } else { SignalError(String("Invalid boolean value: ") + Str); return false; } } int ParameterFile::GetInteger(const String &ParameterName) const { return GetRequiredString(ParameterName).ConvertToInteger(); } UINT ParameterFile::GetUnsignedInteger(const String &ParameterName) const { return GetRequiredString(ParameterName).ConvertToUnsignedInteger(); } double ParameterFile::GetDouble(const String &ParameterName) const { return GetRequiredString(ParameterName).ConvertToDouble(); } float ParameterFile::GetFloat(const String &ParameterName) const { return GetRequiredString(ParameterName).ConvertToFloat(); } Vec3f ParameterFile::GetVec3(const String &ParameterName) const { String VecString = GetRequiredString(ParameterName); Vector<String> Elements; VecString.Partition(' ', Elements); Assert(Elements.Length() == 3, "Vector with invalid element count"); Vec3f Result; for(UINT i = 0; i < 3; i++) { Result[i] = Elements[i].ConvertToFloat(); } return Result; } String ParameterFile::GetString(const String &ParameterName, const String &Default) const { String Result = GetOptionalString(ParameterName); if(Result.Length() == 0) { return Default; } else { return Result; } } bool ParameterFile::GetBoolean(const String &ParameterName, bool Default) const { String Str = GetOptionalString(ParameterName); Str = Str.MakeLowercase(); if(Str == "true") { return true; } else if(Str == "false") { return false; } else { return Default; } } int ParameterFile::GetInteger(const String &ParameterName, int Default) const { return GetString(ParameterName, String(Default)).ConvertToInteger(); } UINT ParameterFile::GetUnsignedInteger(const String &ParameterName, UINT Default) const { return GetString(ParameterName, String(Default)).ConvertToUnsignedInteger(); } double ParameterFile::GetDouble(const String &ParameterName, double Default) const { return GetString(ParameterName, String(Default)).ConvertToDouble(); } float ParameterFile::GetFloat(const String &ParameterName, float Default) const { return GetString(ParameterName, String(Default)).ConvertToFloat(); } Vec3f ParameterFile::GetVec3(const String &ParameterName, const Vec3f &Default) const { String VecString = GetOptionalString(ParameterName); if(VecString.Length() == 0) { return Default; } Vector<String> Elements; VecString.Partition(' ', Elements); Assert(Elements.Length() == 3, "Vector with invalid element count"); Vec3f Result; for(UINT i = 0; i < 3; i++) { Result[i] = Elements[i].ConvertToFloat(); } return Result; } const void* ParameterFile::GetPointer(const String &ParameterName, const String &Type, const void *Default) const { const ParameterEntry *CurEntry = FindParameter(ParameterName); if(CurEntry == NULL) { return Default; } else { return GetPointer(ParameterName, Type); } } const void* ParameterFile::GetPointer(const String &ParameterName, const String &Type) const { const String &Value = GetRequiredString(ParameterName); Vector<String> Words; Value.Partition('@', Words); Assert(Words.Length() == 2, "Invalid pointer parameter"); Assert(Words[0] == Type, "Pointer type mismatch"); return (const void *)(Words[1].ConvertToUnsignedInteger()); } void ParameterFile::SetInteger(const String &ParameterName, UINT Value) { ParameterEntry *CurEntry = FindParameter(ParameterName); if(CurEntry == NULL) { Parameters.PushEnd(ParameterEntry(ParameterName, String(Value))); } else { CurEntry->Value = String(Value); } } void ParameterFile::SetPointer(const String &ParameterName, const void *Pointer, const String &Type) { ParameterEntry *CurEntry = FindParameter(ParameterName); String EncodedPointer = Type + String('@') + String((UINT)Pointer); if(CurEntry == NULL) { Parameters.PushEnd(ParameterEntry(ParameterName, EncodedPointer)); } else { CurEntry->Value = EncodedPointer; } }
922347f35dae6cc05725edd5d36f66609ffc67ae
63c71060f36866bca4ac27304cef6d5755fdc35c
/src/SmartDoc/SdocImport.h
7de56652b9ad8eff5067ea4c42920295d0c81eb6
[]
no_license
15831944/barry_dev
bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a
d4a83421458aa28ca293caa7a5567433e9358596
refs/heads/master
2022-03-24T07:00:26.810732
2015-12-22T07:19:58
2015-12-22T07:19:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,291
h
SdocImport.h
//////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005 // Packet Engineering, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification is not permitted unless authorized in writing by a duly // appointed officer of Packet Engineering, Inc. or its derivatives // // // Modification History: // 05/27/2011 Created by Wynn //////////////////////////////////////////////////////////////////////////// #ifndef Aos_SmartDoc_SdocImport_h #define Aos_SmartDoc_SdocImport_h #include "SmartDoc/SmartDoc.h" #include "Util/RCObject.h" #include "Util/RCObjImp.h" #include "Util/String.h" #include "UtilComm/Ptrs.h" #include <vector> #include <map> using namespace std; struct AosImport { AosXmlTagPtr mXml; AosXmlTagPtr mActions; bool mModify; AosRundataPtr mRundata; AosImport(const AosXmlTagPtr &xml, const AosXmlTagPtr &actions, const bool &modify, const AosRundataPtr &rdata) : mXml(xml), mActions(actions), mModify(modify), mRundata(rdata->clone(AosMemoryCheckerArgsBegin)) {} ~AosImport(){} }; struct AosSplit { AosXmlTagPtr mActions; bool mCover; bool mHeaderCheckedFlag; OmnString mTableName; OmnString mIdentify; OmnString mContainer; OmnConnBuffPtr mBuff; AosRundataPtr mRundata; AosSplit( const AosXmlTagPtr &actions, const bool &cover, const OmnString &tname, const OmnString &identify, const OmnString &container, const OmnConnBuffPtr &buff, const AosRundataPtr &rdata) : mActions(actions), mCover(cover), mHeaderCheckedFlag(false), mTableName(tname), mIdentify(identify), mContainer(container), mBuff(buff), mRundata(rdata->clone(AosMemoryCheckerArgsBegin)) {} ~AosSplit(){} }; class AosSdocImport : public AosSmartDoc, virtual public OmnThreadedObj { public: enum { eCreateDocId = 0, eSplitXmlId = 1, eSplitXmlLevel = 4000000 // 4M }; private: typedef vector<OmnString> AosColumnVect; typedef map<OmnString, OmnString> AosHeader2AttrMap; typedef map<OmnString, OmnString> AosSysBdMap; typedef map<OmnString, OmnString>::iterator AosHeader2AttrMapItr; typedef map<OmnString, OmnString>::iterator AosSysBdMapItr; int mNumReqs; int mPageSize; AosColumnVect mColumnVect; AosHeader2AttrMap mHeader2AttrMap; AosSysBdMap mSysBdMap; queue<AosImport> mQueue; queue<AosSplit> mSplitQueue; OmnThreadPtr mCreateDocThread; OmnThreadPtr mSplitXmlThread; OmnString mCreateMethod; public: AosSdocImport(const bool flag); ~AosSdocImport(); // Smartdoc Interface virtual bool run(const AosXmlTagPtr &sdoc, const AosRundataPtr &rdata); virtual AosSmartDocObjPtr clone(){return OmnNew AosSdocImport(false);} //ThreadedObj Interface virtual bool threadFunc(OmnThrdStatus::E &state, const OmnThreadPtr &thread); virtual bool signal(const int threadLogicId); virtual bool checkThread(OmnString &err, const int thrdLogicId) const; private: bool getExcel( const bool &cover, const OmnString &identify, const OmnString &container, const OmnString &tname, const AosXmlTagPtr &actions, OmnString &filedir, OmnString &filename, const AosRundataPtr &rdata); bool createDoc(OmnThrdStatus::E &state, const OmnThreadPtr &thread); bool splitXml(OmnThrdStatus::E &state, const OmnThreadPtr &thread); bool createDoc( const AosXmlTagPtr &xml, const AosXmlTagPtr &actions, const bool &modify, const AosRundataPtr &rdata); bool createDoc(const AosImport &import); bool splitXml(const AosSplit &split); bool initHeader( const AosXmlTagPtr &sdoc, const AosRundataPtr &rdata); bool initSysBd( const AosXmlTagPtr &sdoc, const AosRundataPtr &rdata); bool isInvalidSysBd(const OmnString &sysbd); bool addRequest( const AosXmlTagPtr &xml, const AosXmlTagPtr &actions, const bool &modify, const AosRundataPtr &rdata); bool addSplitRequest( const AosXmlTagPtr &actions, const bool &cover, const OmnString &identify, const OmnString &tname, const OmnString &container, const OmnConnBuffPtr &docBuff, const AosRundataPtr &rdata); void startThread(); bool splitXml( const OmnConnBuffPtr &buff, const AosXmlTagPtr &actions, const bool &cover, const OmnString &identify, const OmnString &tname, const OmnString &container, const AosRundataPtr &rdata); bool createXml( const char *start, const int &len, const AosXmlTagPtr &actions, const bool &cover, const OmnString identify, const OmnString &container, const AosRundataPtr &rdata); bool checkHeader( const AosXmlTagPtr &row, const AosRundataPtr &rdata); bool initAttrs( const OmnString &identify, OmnString &identify_value, const AosXmlTagPtr &row, map<OmnString, OmnString> &attrs, const AosRundataPtr &rdata); AosXmlTagPtr createCoverDoc( bool &modify, const OmnString &container, const OmnString &identify, const OmnString &identify_value, map<OmnString, OmnString> &attrs, const AosRundataPtr &rdata); AosXmlTagPtr createNewDoc( const OmnString &container, map<OmnString, OmnString> &attrs); bool createSysDoc( const bool &modify, const AosXmlTagPtr &doc, const AosRundataPtr &rdata); bool createTable( AosXmlTagPtr doc, const AosXmlTagPtr &actions, const bool &cover, const OmnString identify, OmnString &identify_value, const OmnString &container, const AosRundataPtr &rdata); bool createRowNode( const char *start, const int &len, AosXmlTagPtr &doc, const OmnString identify, OmnString &identify_value, const AosRundataPtr &rdata); }; #endif
496125102b148da07f7a20135e0d1626494f12f5
8635e9e8cde70ce1f55aac7b50d8090add38a163
/Problems/bzoj/2809.cpp
37414cd9305b93e88f68fd5a9dab71346d5c56c8
[]
no_license
99hgz/Algorithms
f0b696f60331ece11e99c93e75eb8a38326ddd96
a24c22bdee5432925f615aef58949402814473cd
refs/heads/master
2023-04-14T15:21:58.434225
2023-04-03T13:01:04
2023-04-03T13:01:04
88,978,471
3
1
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
2809.cpp
#include <cstdio> #include <cstring> #include <vector> #include <cstdlib> #include <algorithm> using namespace std; typedef long long ll; vector<ll> vec[100010]; struct Node { ll val, fa, left, right; } tree[100010]; ll dist[100010]; ll n, m, sj[100010], c[100010], l[100010], cases, x, y, sum[100010], num[100010], _root, root[100010], ans; ll merge(ll A, ll B) { if (!A || !B) return A + B; if ((tree[A].val < tree[B].val) || (tree[A].val == tree[B].val && A > B)) swap(A, B); ll tmp; tree[A].right = tmp = merge(tree[A].right, B); tree[tmp].fa = A; if (dist[tree[A].right] > dist[tree[A].left]) swap(tree[A].right, tree[A].left); dist[A] = dist[tree[A].right] + 1; return A; } ll get_father(ll A) { return tree[A].fa ? get_father(tree[A].fa) : A; } ll erase(ll B) { ll A = root[B]; //printf("erase%lld\n", tree[A].val); sum[B] -= tree[A].val; num[B]--; tree[tree[A].left].fa = 0; tree[tree[A].right].fa = 0; tree[A].val = 0; return merge(tree[A].left, tree[A].right); } void addedge(ll u, ll v) { vec[u].push_back(v); } void dfs(ll x) { //printf("in%lld\n", x); for (ll i = 0; i < vec[x].size(); i++) { dfs(vec[x][i]); root[x] = merge(root[x], root[vec[x][i]]); sum[x] += sum[vec[x][i]]; num[x] += num[vec[x][i]]; while (sum[x] > m) root[x] = erase(x); } sum[x] += c[x]; num[x]++; tree[x] = (Node){c[x], x, 0, 0}; root[x] = merge(root[x], x); while (sum[x] > m) root[x] = erase(x); ans = max(ans, num[x] * l[x]); //printf("out%lld\n", x); } int main() { scanf("%lld%lld", &n, &m); for (ll i = 1; i <= n; i++) { scanf("%lld%lld%lld", &sj[i], &c[i], &l[i]); if (sj[i] == 0) _root = i; else addedge(sj[i], i); } dfs(_root); printf("%lld\n", ans); system("pause"); return 0; }
c3d4632badd736712e9f4c4d70d3185eeece7a86
343f7c1cb545ee1e24e78d023ad3c13fb7a9db39
/leetcode/238-Product-of-Array-Except-Self.cpp
debcf3dc79f2b0751da1e9cfa169925e4fdc27ea
[]
no_license
nashirj/interview-prep
393fe5d6a5bba13db5165639f084e2bdb149665c
10541a4451eb559fe238010faeab5961bd5fc096
refs/heads/master
2022-12-08T01:49:08.042341
2020-08-12T19:11:44
2020-08-12T19:11:44
142,927,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,614
cpp
238-Product-of-Array-Except-Self.cpp
/** 238. Product of Array Except Self Medium 4109 355 Add to List Share Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) */ class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int num_zeros = std::count(nums.begin(), nums.end(), 0); if (num_zeros > 1) { return vector<int>(nums.size(), 0); } vector<int> products(nums.size()); for (int i = 0; i < nums.size(); i++) { if (nums[i]) } return products; } }; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n_size = nums.size(); vector<int> left(n_size); left[0] = 1; vector<int> right(n_size); right[n_size-1] = 1; for (int i = 1; i < n_size; i++) { left[i] = left[i-1]* nums[i-1]; right[n_size-i-1] = right[n_size-i]* nums[n_size-i]; } vector<int> products(n_size); for (int i = 0; i < nums.size(); i++) { products[i] = left[i] * right[i]; } return products; } };
7471aa99eb05d35da3ae03ab2d909ba05a89aaee
86ed1578979219c7e2f8087fb81a658becba4a84
/problem solving/Game of Thrones - I.cpp
c2d63e0f3440d2fdcdb32e7132e69eb32ff82acd
[]
no_license
aditya-kumar-129/hackerrankproblems
28818996b05aea745e493559563a8bea7f8382a3
4a201dc008b1c906e8d558b78a130f080af937ae
refs/heads/main
2023-06-30T06:27:55.300542
2021-08-11T17:52:38
2021-08-11T17:52:38
354,424,613
2
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
Game of Thrones - I.cpp
#include <iostream> using namespace std; int main() { string s; cin>>s; int ar[26]={0}; for(int i=0;i<s.size();i++) ar[s[i]-97]++; int count = 0; for(int i = 0; i < 26; i++) if(ar[i]%2 != 0) count++; if(count>1) cout<<"NO"; else cout<<"YES"; }
693dc17c539fe709f2bb6ba8ded6eba2d4558204
89c44937dcb20d35fce120cfe5848df5f21f12d0
/o3s/include/types/rotation.hpp
4931d3811eb8015396b2734b16b2930b02612b65
[]
no_license
aufheben1/Open3dSLAM
4fdb8ee6a3c2ac697dba8793c96e483a41f5df64
d2a21927aa828b87da6c6a5e5db3751b6757618b
refs/heads/master
2020-05-03T09:34:25.483906
2019-04-07T07:02:52
2019-04-07T07:05:56
178,557,779
1
0
null
2019-04-07T07:05:58
2019-03-30T12:48:24
C++
UTF-8
C++
false
false
853
hpp
rotation.hpp
#ifndef _O3S_TYPES_ROTATION_HPP_ #define _O3S_TYPES_ROTATION_HPP_ #include "types/position.hpp" namespace o3s { class Rotation { public: Rotation(); Rotation(double x, double y, double z, double w); // Operators Rotation& operator=(const Rotation& rhs); Rotation& operator*=(const Rotation& rhs); const Rotation operator*(const Rotation& other) const; Position operator*(const Position& rhs) const; // Getter inline double x() const { return data[0]; } inline double y() const { return data[1]; } inline double z() const { return data[2]; } inline double w() const { return data[3]; } // Interfaces Rotation inverse() const; private: // Used only for multiplication with Position Rotation(const Position& p); void normalize(); double magnitude(); private: double data[4]; }; } // namespace o3s #endif
9ec77185b2624d738171fd0d7320fec0979e960f
bcd3b295451cc6b8f88b6e3ae3f83bd635578164
/main.cpp
47f3d0fb4556d0ce2cf81b95eb8bd2130e654a81
[]
no_license
BenGreenfield825/OOP-Example
20beae399dfd2ec59c50c6a90742fa34fa853c89
3d043e0e01e657d7ed1fc0e6cfe19673f984a1b5
refs/heads/main
2023-01-24T18:34:55.040672
2020-12-06T22:29:16
2020-12-06T22:29:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
114
cpp
main.cpp
#include "Course.h" #include "Controller.h" using namespace std; int main() { Controller(); return 0; }
0f31df31ac646e3c36d5a167df9576c4015bc0e1
d344de8e32f82bc2596a01eac6ca1b109884bd06
/Competive Programming/coding blocks/CodeChef/alogo.cpp
e457112e87962a4b50120df1c1d274a455efa68d
[]
no_license
vijaygwala/MyCodingStyle-
214e9149ccbb33b21d2132dd0a7d85272d438f16
39d75463ec8af798df7d013efc940de89a447009
refs/heads/master
2022-10-06T07:55:46.928080
2020-06-05T15:55:31
2020-06-05T15:55:31
268,440,527
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
alogo.cpp
#include<iostream> #include<vector> using namespace std; int main(){ int n; cin>>n; vector<int> grades(n); for(int i=0;i<n;i++) { cin>>grades[i]; } for(int i=0;i<n;i++) { int a=grades[i]; int b=grades[i]; if(b>=38) { while(true) { b=b+1; if(b%5==0 && b-a<3) { grades[i]=b; break; } if(b%5==0 && b-a>=3) break; } } } for(int j=0;j<n;j++) cout<<grades[j]<<endl; }
8ef38d8408a969ed8a56bd20eb73fa7aadae853d
697d8dcb9b39ef858cad57d7eced694590821ded
/WorkingOut.cpp
fd11e9f5aa6b973f08a02d6d8022978e9578e6b4
[]
no_license
KevinMathewT/Competitive-Programming
e1dcdffd087f8a1d5ca29ae6189ca7fddbdc7754
e7805fe870ad9051d53cafcba4ce109488bc212d
refs/heads/master
2022-02-14T09:37:31.637330
2020-09-26T16:15:26
2020-09-26T16:15:26
147,362,660
4
4
null
2022-02-07T11:13:38
2018-09-04T14:52:29
C++
UTF-8
C++
false
false
1,366
cpp
WorkingOut.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; // Author - Kevin Mathew // Birla Institute of Technology, Mesra ll n, m, a[1010][1010], dp1[1010][1010], dp2[1010][1010], dp3[1010][1010], dp4[1010][1010]; void te(){ cin >> n >> m; for(ll i=1;i<=n;i++) for(ll j=1;j<=m;j++) cin >> a[i][j]; for(ll i=0;i<=n+1;i++) for(ll j=0;j<=m+1;j++){ dp1[i][j] = 0; dp2[i][j] = 0; dp3[i][j] = 0; dp4[i][j] = 0; } for(ll i=1;i<=n;i++) for(ll j=1;j<=m;j++) dp1[i][j] = a[i][j] + max(dp1[i-1][j], dp1[i][j-1]); for(ll i=n;i>=1;i--) for(ll j=m;j>=1;j--) dp2[i][j] = a[i][j] + max(dp2[i+1][j], dp2[i][j+1]); for(ll i=n;i>=1;i--) for(ll j=1;j<=m;j++) dp3[i][j] = a[i][j] + max(dp3[i+1][j], dp3[i][j-1]); for(ll i=1;i<=n;i++) for(ll j=m;j>=1;j--) dp4[i][j] = a[i][j] + max(dp4[i-1][j], dp4[i][j+1]); ll mx = LLONG_MIN; ll ans = 0; for(ll i=2;i<n;i++){ for(ll j=2;j<m;j++){ ans = max(dp1[i-1][j] + dp2[i+1][j] + dp3[i][j-1] + dp4[i][j+1], dp1[i][j-1] + dp2[i][j+1] + dp3[i+1][j] + dp4[i-1][j]); mx = max(mx, ans); } // cout << "\n"; } cout << mx << "\n"; } int main() { // freopen("input.txt", "r", stdin); //Comment // freopen("output.txt", "w", stdout); //this out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. te(); return 0; }
5c2bac48730e815178c136673c471954934fef8b
26faed1887712d4815491eb521758d91c82b72ac
/ext/wxPoint.cpp
1165094d51be1ff5c305627cc42812818d988f3c
[]
no_license
rinkevichjm/rwx
eb6dcdd62caf97bc3dc2fb203d2346438d28f059
314805fa548394ea9200b4c0dd4f8fe33dd48595
refs/heads/master
2021-01-25T02:29:26.861483
2015-06-03T06:42:53
2015-06-03T06:42:53
22,302,293
0
0
null
null
null
null
UTF-8
C++
false
false
4,616
cpp
wxPoint.cpp
/* * wxRealPoint.cpp * * Created on: 21.04.2012 * Author: hanmac */ #include "wxPoint.hpp" VALUE rb_cwxPoint; ID rwxID_x,rwxID_y; #define _self unwrap<wxRealPoint*>(self) template <> VALUE wrap< wxRealPoint >(wxRealPoint *point ) { return wrapTypedPtr(point, rb_cwxPoint); } template <> VALUE wrap< wxPoint >(const wxPoint &point ) { return wrap(new wxRealPoint(point)); } template <> bool is_wrapable< wxRealPoint >(const VALUE &vpoint) { if (rb_obj_is_kind_of(vpoint, rb_cwxPoint)){ return true; }else if(rb_respond_to(vpoint,rwxID_x) && rb_respond_to(vpoint,rwxID_y)){ return true; }else return false; } template <> bool is_wrapable< wxPoint >(const VALUE &vpoint) { return is_wrapable< wxRealPoint >(vpoint); } template <> wxRealPoint unwrap< wxRealPoint >(const VALUE &vpoint) { if(rb_obj_is_kind_of(vpoint, rb_cArray)){ wxRealPoint point; point.x = NUM2DBL(RARRAY_AREF(vpoint,0)); point.y = NUM2DBL(RARRAY_AREF(vpoint,1)); return point; }else if(!rb_obj_is_kind_of(vpoint, rb_cwxPoint) && rb_respond_to(vpoint,rwxID_x) && rb_respond_to(vpoint,rwxID_y)){ wxRealPoint point; point.x = NUM2DBL(rb_funcall(vpoint,rwxID_x,0)); point.y = NUM2DBL(rb_funcall(vpoint,rwxID_y,0)); return point; }else{ return *unwrap<wxRealPoint*>(vpoint); } } template <> wxPoint unwrap< wxPoint >(const VALUE &vpoint) { if(rb_obj_is_kind_of(vpoint, rb_cArray)){ wxPoint point; point.x = NUM2INT(RARRAY_AREF(vpoint,0)); point.y = NUM2INT(RARRAY_AREF(vpoint,1)); return point; }else if(!rb_obj_is_kind_of(vpoint, rb_cwxPoint) && rb_respond_to(vpoint,rwxID_x) && rb_respond_to(vpoint,rwxID_y)){ wxPoint point; point.x = NUM2INT(rb_funcall(vpoint,rwxID_x,0)); point.y = NUM2INT(rb_funcall(vpoint,rwxID_y,0)); return point; }else{ return *unwrap<wxRealPoint*>(vpoint); } } template <> wxPointList* unwrap< wxPointList* >(const VALUE &val) { wxPointList *result = new wxPointList; VALUE dp(rb_Array(val)); std::size_t length = RARRAY_LEN(dp); for(std::size_t i = 0; i < length; ++i) result->Append(new wxPoint(unwrap<wxPoint>(RARRAY_AREF(dp,i)))); return result; } namespace RubyWX { namespace Point { macro_attr_prop(x,double) macro_attr_prop(y,double) DLL_LOCAL VALUE _alloc(VALUE self) { return wrap(new wxRealPoint()); } DLL_LOCAL VALUE _initialize(VALUE self,VALUE x,VALUE y) { _set_x(self,x); _set_y(self,y); return self; } /* */ DLL_LOCAL VALUE _initialize_copy(VALUE self, VALUE other) { VALUE result = rb_call_super(1,&other); _set_x(self,_get_x(other)); _set_y(self,_get_y(other)); return result; } /* Document-method: inspect * call-seq: * inspect -> String * * Human-readable description. * ===Return value * String */ DLL_LOCAL VALUE _inspect(VALUE self) { return rb_sprintf( "%s(%f, %f)", rb_obj_classname( self ), NUM2DBL(_get_x(self)), NUM2DBL(_get_y(self))); } /* Document-method: marshal_dump * call-seq: * marshal_dump -> Array * * Provides marshalling support for use by the Marshal library. * ===Return value * Array */ DLL_LOCAL VALUE _marshal_dump(VALUE self) { VALUE ptr[2]; ptr[0] = _get_x(self); ptr[1] = _get_y(self); return rb_ary_new4(2, ptr); } /* Document-method: marshal_load * call-seq: * marshal_load(array) -> nil * * Provides marshalling support for use by the Marshal library. * * */ DLL_LOCAL VALUE _marshal_load(VALUE self, VALUE data) { _set_x(self, RARRAY_AREF(data,0)); _set_y(self, RARRAY_AREF(data,1)); return Qnil; } } } /* Document-class: WX::Point * * This class represents an Point. */ /* Document-attr: x * returns the x value of Point. */ /* Document-attr: y * returns the y value of Point. */ /**/ DLL_LOCAL void Init_WXPoint(VALUE rb_mWX) { using namespace RubyWX::Point; rb_cwxPoint = rb_define_class_under(rb_mWX,"Point",rb_cObject); rb_define_alloc_func(rb_cwxPoint,_alloc); #if 0 rb_define_attr(rb_cwxPoint,"x",1,1); rb_define_attr(rb_cwxPoint,"y",1,1); #endif rb_define_method(rb_cwxPoint,"initialize",RUBY_METHOD_FUNC(_initialize),2); rb_define_private_method(rb_cwxPoint,"initialize_copy",RUBY_METHOD_FUNC(_initialize_copy),1); rb_define_attr_method(rb_cwxPoint,"x",_get_x,_set_x); rb_define_attr_method(rb_cwxPoint,"y",_get_y,_set_y); rb_define_method(rb_cwxPoint,"inspect",RUBY_METHOD_FUNC(_inspect),0); rb_define_method(rb_cwxPoint,"marshal_dump",RUBY_METHOD_FUNC(_marshal_dump),0); rb_define_method(rb_cwxPoint,"marshal_load",RUBY_METHOD_FUNC(_marshal_load),-2); registerType<wxRealPoint>(rb_cwxPoint, true); rwxID_x = rb_intern("x"); rwxID_y = rb_intern("y"); }
a2eb4abdaf39a8438fe224c907c83fc6a36b9a94
210c3400dd6718ad004e02df294cc9034ddb8a9d
/src/compass.cpp
9150ed9248df1850181defff2d2a1d1112d43eff
[]
no_license
tanmaysinha18/OpenGL-Flight-SImulator
b3d8e32b9322375cb321ebe32f15aa3ae4d7845c
fc8f67bc22c71cf32c2bbfc9247b47da19920a1a
refs/heads/master
2023-08-07T11:02:11.715741
2020-03-25T22:31:58
2020-03-25T22:31:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
compass.cpp
#include "compass.h" Compass::Compass(float x,float y,float z) { this->position = glm::vec3(x,y,z); GLfloat compass_buffer_data[] = { 0,0,0, -0.5,0,-3, 0.5,0,-3, }; this->compass = create3DObject(GL_TRIANGLES,1*3,compass_buffer_data,(color_t){255,0,0},GL_FILL); } void Compass::draw(glm::mat4 VP,glm::mat4 rotate) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate // rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->compass); }
24d3fb447f46022b551c3bf930c3444ec40de70d
5521a03064928d63cc199e8034e4ea76264f76da
/fboss/thrift_cow/visitors/tests/DeltaVisitorTests.cpp
430a927e94de5ca098dfb68abe6341732d5db531
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
facebook/fboss
df190fd304e0bf5bfe4b00af29f36b55fa00efad
81e02db57903b4369200eec7ef22d882da93c311
refs/heads/main
2023-09-01T18:21:22.565059
2023-09-01T15:53:39
2023-09-01T15:53:39
31,927,407
925
353
NOASSERTION
2023-09-14T05:44:49
2015-03-09T23:04:15
C++
UTF-8
C++
false
false
25,896
cpp
DeltaVisitorTests.cpp
// (c) Facebook, Inc. and its affiliates. Confidential and proprietary. #include <folly/String.h> #include <folly/dynamic.h> #include <folly/logging/xlog.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <fboss/thrift_cow/visitors/DeltaVisitor.h> #include <thrift/lib/cpp2/reflection/folly_dynamic.h> #include "fboss/thrift_cow/nodes/Types.h" #include "fboss/thrift_cow/nodes/tests/gen-cpp2/test_fatal_types.h" using folly::dynamic; namespace { using namespace facebook::fboss; using PathTagSet = std::set<std::pair<std::string, thrift_cow::DeltaElemTag>>; TestStruct createTestStruct() { dynamic testDyn = dynamic::object("inlineBool", true)("inlineInt", 54)( "inlineString", "testname")("optionalString", "bla")("inlineStruct", dynamic::object("min", 10)("max", 20))("inlineVariant", dynamic::object("inlineInt", 99))("mapOfEnumToStruct", dynamic::object("3", dynamic::object("min", 100)("max", 200))); return apache::thrift::from_dynamic<TestStruct>( testDyn, apache::thrift::dynamic_format::JSON_1); } } // namespace TEST(DeltaVisitorTests, ChangeOneField) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.inlineInt() = false; auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineInt", DeltaElemTag::MINIMAL)})); // test encoding IDs differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions( DeltaVisitMode::PARENTS, thrift_cow::DeltaVisitOrder::PARENTS_FIRST, true), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/2", DeltaElemTag::MINIMAL)})); // test MINIMAL delta mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq( PathTagSet{std::make_pair("/inlineInt", DeltaElemTag::MINIMAL)})); // test FULL delta mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineInt", DeltaElemTag::MINIMAL)})); } TEST(DeltaVisitorTests, ChangeOneFieldInContainer) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.mapOfEnumToStruct()->at(TestEnum::THIRD).min() = 11; auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/3", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/3/min", DeltaElemTag::MINIMAL)})); differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/mapOfEnumToStruct/3/min", DeltaElemTag::MINIMAL)})); } TEST(DeltaVisitorTests, SetOptional) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.optionalString() = "now I'm set"; auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/optionalString", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/optionalString", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/optionalString", DeltaElemTag::MINIMAL)})); } TEST(DeltaVisitorTests, AddToMap) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; cfg::L4PortRange newOne; newOne.min() = 40; newOne.max() = 100; structB.mapOfEnumToStruct()->emplace(TestEnum::FIRST, std::move(newOne)); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/mapOfEnumToStruct/1", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1", DeltaElemTag::MINIMAL), std::make_pair("/mapOfEnumToStruct/1/min", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1/max", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/mapOfEnumToStruct/1/invert", DeltaElemTag::NOT_MINIMAL)})); } TEST(DeltaVisitorTests, UpdateMap) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; cfg::L4PortRange oldOne; oldOne.min() = 40; oldOne.max() = 100; oldOne.invert() = false; structA.mapOfEnumToStruct()->emplace(TestEnum::FIRST, std::move(oldOne)); // update fields cfg::L4PortRange newOne; newOne.min() = 400; newOne.max() = 1000; structB.mapOfEnumToStruct()->emplace(TestEnum::FIRST, std::move(newOne)); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1/min", DeltaElemTag::MINIMAL), std::make_pair("/mapOfEnumToStruct/1/max", DeltaElemTag::MINIMAL), })); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/mapOfEnumToStruct/1/min", DeltaElemTag::MINIMAL), std::make_pair("/mapOfEnumToStruct/1/max", DeltaElemTag::MINIMAL)})); // Test encoding ids differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions( DeltaVisitMode::MINIMAL, thrift_cow::DeltaVisitOrder::PARENTS_FIRST, true), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/15/1/1", DeltaElemTag::MINIMAL), std::make_pair("/15/1/2", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/1/min", DeltaElemTag::MINIMAL), std::make_pair("/mapOfEnumToStruct/1/max", DeltaElemTag::MINIMAL), })); } TEST(DeltaVisitorTests, DeleteFromMap) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.mapOfEnumToStruct()->erase(TestEnum::THIRD); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/3", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/mapOfEnumToStruct/3", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/3", DeltaElemTag::MINIMAL), std::make_pair("/mapOfEnumToStruct/3/min", DeltaElemTag::NOT_MINIMAL), std::make_pair("/mapOfEnumToStruct/3/max", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/mapOfEnumToStruct/3/invert", DeltaElemTag::NOT_MINIMAL)})); } TEST(DeltaVisitorTests, AddToList) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; cfg::L4PortRange newOne; newOne.min() = 40; newOne.max() = 100; structB.listOfStructs()->push_back(std::move(newOne)); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL), std::make_pair("/listOfStructs/0/min", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0/max", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/listOfStructs/0/invert", DeltaElemTag::NOT_MINIMAL)})); } TEST(DeltaVisitorTests, DeleteFromList) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; cfg::L4PortRange newOne; newOne.min() = 40; newOne.max() = 100; structB.listOfStructs()->push_back(std::move(newOne)); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeB, nodeA, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeB, nodeA, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeB, nodeA, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0", DeltaElemTag::MINIMAL), std::make_pair("/listOfStructs/0/min", DeltaElemTag::NOT_MINIMAL), std::make_pair("/listOfStructs/0/max", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/listOfStructs/0/invert", DeltaElemTag::NOT_MINIMAL)})); } TEST(DeltaVisitorTests, EditVariantField) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.inlineVariant()->inlineInt_ref() = 1000; auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL)})); // Test with ids differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions( DeltaVisitMode::FULL, thrift_cow::DeltaVisitOrder::PARENTS_FIRST, true), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/21", DeltaElemTag::NOT_MINIMAL), std::make_pair("/21/2", DeltaElemTag::MINIMAL)})); } TEST(DeltaVisitorTests, SwitchVariantField) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); auto structB = structA; structB.inlineVariant()->inlineBool_ref() = true; auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair("/inlineVariant/inlineBool", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair("/inlineVariant/inlineBool", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair("/inlineVariant/inlineBool", DeltaElemTag::MINIMAL)})); } TEST(DeltaVisitorTests, SwitchVariantFieldToStruct) { using namespace facebook::fboss::thrift_cow; auto structA = createTestStruct(); cfg::L4PortRange newOne; newOne.min() = 40; newOne.max() = 100; auto structB = structA; structB.inlineVariant()->inlineStruct_ref() = std::move(newOne); auto nodeA = std::make_shared<ThriftStructNode<TestStruct>>(structA); auto nodeB = std::make_shared<ThriftStructNode<TestStruct>>(structB); PathTagSet differingPaths; auto processChange = [&](const std::vector<std::string>& path, auto&& /*oldValue*/, auto&& /*newValue*/, auto&& tag) { differingPaths.emplace(std::make_pair("/" + folly::join('/', path), tag)); }; auto result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::PARENTS), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair( "/inlineVariant/inlineStruct", DeltaElemTag::MINIMAL)})); // Test MINIMAL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::MINIMAL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair( "/inlineVariant/inlineStruct", DeltaElemTag::MINIMAL)})); // Test FULL mode differingPaths.clear(); result = RootDeltaVisitor::visit( nodeA, nodeB, DeltaVisitOptions(DeltaVisitMode::FULL), processChange); EXPECT_EQ(result, true); EXPECT_THAT( differingPaths, ::testing::ContainerEq(PathTagSet{ std::make_pair("/", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant", DeltaElemTag::NOT_MINIMAL), std::make_pair("/inlineVariant/inlineInt", DeltaElemTag::MINIMAL), std::make_pair("/inlineVariant/inlineStruct", DeltaElemTag::MINIMAL), std::make_pair( "/inlineVariant/inlineStruct/min", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/inlineVariant/inlineStruct/max", DeltaElemTag::NOT_MINIMAL), std::make_pair( "/inlineVariant/inlineStruct/invert", DeltaElemTag::NOT_MINIMAL)})); }
e5d73d1168a22852c7a34298fe42295c0989f7d4
1c33b6fd7fbf966a961ccd679ad2ba344f2fc05f
/2018/Number chain.cpp
3de45f17163ded88e9b239b5cc0cdd5d54207300
[]
no_license
zim2510/Online-Judge-Solves
f57170e5bf14f339944079ed62bed01bdc5b27e3
949ab3cfba0cc7ec4ffaa6f2b3e5b0c517d9377a
refs/heads/master
2022-01-07T10:23:12.653572
2019-05-19T11:30:58
2019-05-19T11:30:58
135,351,009
0
0
null
null
null
null
UTF-8
C++
false
false
2,227
cpp
Number chain.cpp
#include <bits/stdc++.h> #define Read() freopen("in.txt", "r", stdin) #define Write() freopen("out.txt", "w", stdout) #define min3(a, b, c) min(a, min(b, c)) #define max3(a, b, c) max(a, max(b, c)) #define TC(i, a, b) for(int i = a; i<=b; i++) #define FOR(i, a, b) for(int i = a; i<b; i++) #define ROF(i, a, b) for(int i = a; i>=b; i--) #define MEM(a, x) memset(a, x, sizeof(a)) #define SQR(x) ((x)*(x)) #define valid(x, s, e) (x>=s && x<=e) #define sz(a) int((a).size()) #define all(c) (c).begin(),(c).end() #define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++) #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) #define pb push_back #define MAX 1000000000 #define ff first #define ss second #define sf scanf #define pf printf const int dx[] = { 0, -1, 0, 1, -1, 1, 1, -1, -2, -2, 2, 2, -1, -1, 1, 1}; const int dy[] = {-1, 0, 1, 0, 1, 1, -1, -1, -1, 1, -1, 1, -2, 2, -2, 2}; using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> ii; typedef long long LL; typedef unsigned long long ULL; int s2d(string x) { if(x.size()==0) return 1; int n = 0; for(int i = 0; i<x.size(); i++){ n = n*10 + x[i]-'0'; } return n; } string num2string(int num, int base) { string x = ""; while(num){ x += '0' + (num%base); num /= base; } reverse(x.begin(), x.end()); if(!x.size()) return "0"; else return x; } int main(int argc, char const *argv[]) { //Read(); //Write(); string in; while(cin>>in){ if(in=="0") break; cout<<"Original number was "<<in<<endl; map <string, bool> m; int length = 0; while(true){ length++; string n = in; sort(n.begin(), n.end()); string r = n; reverse(r.begin(), r.end()); in = num2string(s2d(r) - s2d(n), 10); cout<<s2d(r)<<" - "<<s2d(n)<<" = "<<s2d(in)<<endl; if(m[in]) break; else m[in] = 1; } cout<<"Chain length "<<length<<endl<<endl; } }
33fac2cf9738e7d1cace1508e063443cd0d27022
b9331609646b216bfbd7df3f5b319e29d17801da
/serverAsync/server_async_one.cpp
199f2bf4b33d22e780b3bd7704abe5d52e3eb52e
[]
no_license
clzhan/boostStudy
f196012c4a309d11cdec939f722c4d715e8d2ed3
e57707833a67560d6fc9e2d7955d28ee195b718c
refs/heads/master
2020-05-14T23:13:29.343764
2019-04-24T01:32:31
2019-04-24T01:32:31
181,993,041
0
0
null
null
null
null
GB18030
C++
false
false
2,370
cpp
server_async_one.cpp
#include <stdio.h> #include "boost/asio.hpp" #include <iostream> #include <memory> using boost::asio::ip::tcp; class Connection: public std::enable_shared_from_this<Connection> { public: Connection(boost::asio::io_service & service) : socket(service) { } ~Connection() { printf("%s \n", __FUNCTION__); } void do_read() { auto self(shared_from_this()); memset(buf, 0, 512); //注意 重置buf socket.async_read_some(boost::asio::buffer(buf), [this, self](boost::system::error_code error, std::size_t length) { if (!error) { //再原封不动写回去 this->do_write(); } } ); } void do_write() { auto self(shared_from_this()); boost::asio::async_write(socket, boost::asio::buffer(buf), [this, self](boost::system::error_code error, std::size_t length) { if (!error) { this->do_read(); } }); } tcp::socket & getSocket() { return socket; } private: tcp::socket socket; char buf[512]; }; using ConnectionPtr = std::shared_ptr<Connection>; class Server { public: Server(boost::asio::io_service & service) : acceptor(service, tcp::endpoint(tcp::v4(), 8868)) { Start(); } private: void Start() { ConnectionPtr conn(new Connection(acceptor.get_io_service())); acceptor.async_accept(conn->getSocket(), [this, conn](boost::system::error_code error){ if (!error) { tcp::socket & socket = conn->getSocket(); printf("remote addr %s %d\n", socket.remote_endpoint().address().to_string().c_str(), socket.remote_endpoint().port()); conn->do_read(); this->Start(); } }); } private: tcp::acceptor acceptor; }; int main(int argc, char * argv[]) { //1.创建一个IOservice boost::asio::io_service io_service; // boost::asio::ip::address addr; // addr.from_string("10.10.6.91"); //2.构建一个endpoint //boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("10.10.6.91"), 8868);//创建目标地址对象 //boost::asio::ip::tcp::endpoint ep(addr, 8868);//创建目标地址对象 Server server(io_service); io_service.run(); //与同步I/O 不同, 异步I/O要调用run return 0; }
329f687026af89b840f3a1696614f0088ae35be8
6f6709e98b12d9cb4b2dd725c22309aabff152ba
/blackJack.cpp
9503f6400a59e7ed41c79bf53d1603ef7bc44a03
[]
no_license
jonathanrgoh/Personal-Projects
e466e48a42a3429383a49b0b99d3864619dcde03
1edc316767281cd625d90e0c6b3671ba50d72e50
refs/heads/master
2020-11-30T11:43:26.004287
2020-08-23T17:53:59
2020-08-23T17:53:59
230,389,513
0
0
null
null
null
null
UTF-8
C++
false
false
12,771
cpp
blackJack.cpp
#include <iostream> #include <ctime> #include <cstdlib> #include <string> #include <time.h> #include <windows.h> using namespace std; class Card { private: string suit; int value; string face; public: Card() { } Card(int v, string s) { value=v; suit=s; } string getSuit() { return suit; } int getValue() { return value; } string getFace() { switch(value) { case 1: face="A"; break; case 2: face="2"; break; case 3: face="3"; break; case 4: face="4"; break; case 5: face="5"; break; case 6: face="6"; break; case 7: face="7"; break; case 8: face="8"; break; case 9: face="9"; break; case 10: face="10"; break; case 11: face="J"; break; case 12: face="Q"; break; case 13: face="K"; break; } return face; } }; Card box[52]; Card shuffleTemp[52]; int money; void createDeck() { string suits; int cardCounter = 0; for(int i=0; i<4; i++) { switch (i) { case 0: suits = "Hearts"; for(int j=0; j<13; j++) { Card jonsCards = Card(j+1,suits); cardCounter++; box[cardCounter-1]=jonsCards; } break; case 1: suits = "Spades"; for(int j=0; j<13; j++) { Card jonsCards = Card(j+1,suits); cardCounter++; box[cardCounter-1]=jonsCards; } break; case 2: suits = "Diamonds"; for(int j=0; j<13; j++) { Card jonsCards = Card(j+1,suits); cardCounter++; box[cardCounter-1]=jonsCards; } break; case 3: suits = "Clubs"; for(int j=0; j<13; j++) { Card jonsCards = Card(j+1,suits); cardCounter++; box[cardCounter-1]=jonsCards; } break; } } //PRINTS ALL CARDS IN THE DECK /* for(int k=0; k<52; k++) { cout<<box[k].getFace()<< " of "<<box[k].getSuit()<<endl; } */ } void shuffleDeck() { //int currentCard=0; int randNum1, randNum2; //cout<<box[1].getSuit(); for (int k=0; k<52; k++) { shuffleTemp[k]=box[k]; } for (int i=0; i<52; i++) { randNum1 = (rand()+time(0))%52; swap(shuffleTemp[i],shuffleTemp[randNum1]); } for (int g=51; g>=0; g--) { randNum2 = (rand()+time(0))%52; swap(shuffleTemp[g],shuffleTemp[randNum2]); } //PRINTS ALL CARDS IN THE DECK /* for (int j=0; j<52; j++) { cout<<shuffleTemp[j].getFace()<< " of "<<shuffleTemp[j].getSuit()<<endl; //cout<<shuffleTemp[j]<<endl; } */ } void sleep(unsigned int mseconds) { clock_t goal = mseconds + clock(); while (goal > clock()); } void changeConsoleColor(int x) // use argument 10 for green text { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x); } int calcTotals1(int i, int j) { int cookie; if(shuffleTemp[i].getValue()==1) { cookie= 11+j; if(cookie>21) { return 1+j; } else { return cookie; } } else if(shuffleTemp[i].getValue()>=10) { return 10+j; } else if(shuffleTemp[i].getValue()<10) { cookie = shuffleTemp[i].getValue()+j; return cookie; } else return 0; } void welcomeScreen() { changeConsoleColor(14); createDeck(); shuffleDeck(); cout<< "Welcome to Jon's BlackJack Game"<< endl<<endl; cout<< "INSTRUCIONS::"<<endl<<endl<<endl; } void blackJackGame() { changeConsoleColor(15); money=100; int startingBet; string hitStand; bool play = true; char playAgain; bool bust = false; int yourTotals, dealerTotals, tempTotals; do { changeConsoleColor(15); startingBet=0; bust = false; yourTotals=0; dealerTotals=0; playAgain='y'; cout<< "You have $"<<money; while(startingBet<10) { cout<<"\nWhat is your starting BET? => $"; cin>>startingBet; if(startingBet<10) { changeConsoleColor(192); cout<<"MINIMUM BET = $10\n"; changeConsoleColor(15); } } changeConsoleColor(240); cout<< "\n\nDEALING CARDS NOW"; for (int i=4; i>0; --i) { sleep(1000); cout<<"."; } cout<< endl << endl; changeConsoleColor(15); cout<< "DEALER Has =>\n "<<shuffleTemp[1].getFace()<<" of "<<shuffleTemp[1].getSuit()<<" , (?)"<<endl; for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } cout<< "\n\nYOU Have =>\n "<< shuffleTemp[2].getFace()<<" of "<<shuffleTemp[2].getSuit()<< " , "<<shuffleTemp[4].getFace()<<" of "<<shuffleTemp[4].getSuit()<<endl<<endl; for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } cout<<endl<<endl; changeConsoleColor(240); cout<< "YOUR TURN \n====================\n hit or stand? => "; changeConsoleColor(15); cin>> hitStand; if(hitStand=="hit") { cout<<"\nYOU NOW HAVE =>\n "<< shuffleTemp[5].getFace()<<" of "<<shuffleTemp[5].getSuit()<< " , "<<shuffleTemp[2].getFace()<<" of "<<shuffleTemp[2].getSuit()<< " , "<<shuffleTemp[4].getFace()<<" of "<<shuffleTemp[4].getSuit()<<endl<<endl; cout<< " hit or stand? => "; cin>> hitStand; if(hitStand=="hit") { cout<<"\nYOU NOW HAVE =>\n "<< shuffleTemp[6].getFace()<<" of "<<shuffleTemp[6].getSuit()<< " , "<<shuffleTemp[5].getFace()<<" of "<<shuffleTemp[5].getSuit()<< " , "<<shuffleTemp[2].getFace()<<" of "<<shuffleTemp[2].getSuit()<< " , "<<shuffleTemp[4].getFace()<<" of "<<shuffleTemp[4].getSuit()<<endl<<endl; cout<< " hit or stand? => "; cin>> hitStand; if(hitStand=="hit") { cout<<"\nYOU NOW HAVE =>\n "<< shuffleTemp[7].getFace()<<" of "<<shuffleTemp[7].getSuit()<< " , "<<shuffleTemp[6].getFace()<<" of "<<shuffleTemp[6].getSuit()<< " , "<<shuffleTemp[5].getFace()<<" of "<<shuffleTemp[5].getSuit()<< " , "<<shuffleTemp[2].getFace()<<" of "<<shuffleTemp[2].getSuit()<< " , "<<shuffleTemp[4].getFace()<<" of "<<shuffleTemp[4].getSuit()<<endl<<endl; } else { tempTotals=calcTotals1(2,0); yourTotals=tempTotals; yourTotals=calcTotals1(4,tempTotals); tempTotals=yourTotals; yourTotals=calcTotals1(5,tempTotals); tempTotals=yourTotals; yourTotals=calcTotals1(6,tempTotals); cout<<"\nYOUR TOTALS WERE: " << yourTotals << endl<<endl; } } else { tempTotals=calcTotals1(2,0); yourTotals=tempTotals; yourTotals=calcTotals1(4,tempTotals); tempTotals=yourTotals; yourTotals=calcTotals1(5,tempTotals); cout<<"\nYOUR TOTALS WERE: " << yourTotals << endl<<endl; } } else { tempTotals=calcTotals1(2,0); yourTotals=tempTotals; yourTotals=calcTotals1(4,tempTotals); cout<<"\nYOUR TOTALS WERE: " << yourTotals << endl<<endl; } //calc totals and see whose hand is better for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } changeConsoleColor(240); cout<< "\n\nDEALER'S TURN\n=============\n"; changeConsoleColor(15); cout<<"DEALER HAS =>\n "<< shuffleTemp[1].getFace()<<" of "<<shuffleTemp[1].getSuit()<< " , "<<shuffleTemp[3].getFace()<<" of "<<shuffleTemp[3].getSuit()<<endl<<endl; tempTotals=calcTotals1(1,0); dealerTotals=tempTotals; dealerTotals=calcTotals1(3,tempTotals); for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } cout<<endl<<endl; if(dealerTotals<17) { cout<< " Dealer decided to hit\n"; cout<<"DEALER NOW HAS =>\n "<< shuffleTemp[7].getFace()<<" of "<<shuffleTemp[7].getSuit()<< " , "<<shuffleTemp[1].getFace()<<" of "<<shuffleTemp[1].getSuit()<< " , "<<shuffleTemp[3].getFace()<<" of "<<shuffleTemp[3].getSuit()<<endl<<endl; tempTotals=dealerTotals; dealerTotals=calcTotals1(7,tempTotals); for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } cout<<endl<<endl; if(dealerTotals<17) { cout<< " Dealer decided to hit\n"; cout<<"DEALER NOW HAS =>\n "<< shuffleTemp[8].getFace()<<" of "<<shuffleTemp[8].getSuit()<< " , "<<shuffleTemp[7].getFace()<<" of "<<shuffleTemp[7].getSuit()<< " , "<<shuffleTemp[1].getFace()<<" of "<<shuffleTemp[1].getSuit()<< " , "<<shuffleTemp[3].getFace()<<" of "<<shuffleTemp[3].getSuit()<<endl<<endl; tempTotals=dealerTotals; dealerTotals=calcTotals1(8,tempTotals); } else { cout<<endl<<endl; cout<< " Dealer decided to stand\n"; } } else { cout<< " Dealer decided to stand\n"; } cout<<"DEALER'S TOTALS WERE: " << dealerTotals << endl<<endl; cout<<"Working out the numbers right now"; for (int i=3; i>0; --i) { sleep(1000); cout<<"."; } cout<<endl<<endl; changeConsoleColor(240); if(dealerTotals==yourTotals) { cout<<"DRAW...No money lost. $0"; } else if((dealerTotals>yourTotals)&&(dealerTotals<=21)) { cout<<"DEALER WINS. You lose $"<< startingBet<<endl; money-=startingBet; cout<<"You have $"<<money<<" remaining.\n\n"; } else if((dealerTotals<yourTotals)&&(yourTotals<=21)) { cout<<"YOU WIN! You get $"<<startingBet<<endl; money+=startingBet; cout<<"You have $"<<money<<" remaining.\n\n"; } if(money<=0) { cout<<"You're out of funds... Better luck next time."; exit; } cout<< "\n\nDo you want to PLAY AGAIN (y/n)? => "; cin>>playAgain; if(playAgain=='n') { play=false; } cout<<endl<<endl<<endl; } while(play==true); } int main() { welcomeScreen(); blackJackGame(); return 0; }
4f19f8192cdc911cd6cbe12b9803cd4fbaec260e
5ad79fabc6b25bc380d6202fec094a1b69e5f5e6
/src/cool-lex.h
09a0a91b5db864b1958519e98a0b3c6a376e77d4
[]
no_license
uganh/cool
52c79f6d92686433d738d015f5b80e458dca6832
185cf3d0859417d803a3d7067074bd9a86a1152f
refs/heads/master
2023-05-28T06:48:59.593377
2023-05-16T14:19:01
2023-05-16T14:19:01
340,672,120
0
0
null
null
null
null
UTF-8
C++
false
false
615
h
cool-lex.h
#pragma once #include "cool-parse.gen.h" #include <istream> #include <iterator> #include <string> class LexState { std::string yybuf; const char *YYCURSOR, *YYLIMIT; unsigned int curr_lineno; public: explicit LexState(std::istream &stream) : yybuf(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()) , YYCURSOR(yybuf.c_str()) , YYLIMIT(YYCURSOR + yybuf.length()) , curr_lineno(1) {} LexState(const LexState &) = delete; LexState &operator=(const LexState &) = delete; int lex(yy::parser::value_type *yylval_ptr, yy::parser::location_type *yylloc_ptr); };
5a2aa0b5a909bbec3d503cd75c02bcdb4c2af9fc
7b1b9cff50f7afed4d1f15633f958884935b8e12
/02-Bubble/GUI.cpp
d6951e1a7325e64f050da3117cd8fbba0cf837fc
[]
no_license
pabloiniesta/VJ
ff9097667e762a978e8036ce101f00fe97e435eb
e97d77933feab243ff9724715c454d247d9c0cc5
refs/heads/master
2023-01-27T11:50:07.935408
2020-12-15T21:18:40
2020-12-15T21:18:40
304,389,155
0
0
null
null
null
null
UTF-8
C++
false
false
8,647
cpp
GUI.cpp
#include "GUI.h" #include "Constants.h" #include <glm/gtc/matrix_transform.hpp> #include <GL/glew.h> #include <GL/gl.h> #include <iostream> #include <GL/glut.h> #include <string> #include <ft2build.h> #include FT_FREETYPE_H #include <iostream> using namespace std; GUI::GUI() { } void GUI::init() { //Shader initShaders(); projection = glm::ortho(0.f, float(SCREEN_WIDTH - 1), float(SCREEN_HEIGHT - 1), 0.f); //Texture quads glm::vec2 texCoords[2] = { glm::vec2(0.f, 0.f), glm::vec2(1.f, 1.f) }; glm::vec2 geomGUI[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH+ 470), -14.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 560), GUI_HEIGHT-6.5) //Margen derecho, margen inferior }; mainTextureQuad = TexturedQuad::createTexturedQuad(geomGUI, texCoords, texProgram); mainTexture.loadFromFile("images/gui.png", TEXTURE_PIXEL_FORMAT_RGBA); //Money glm::vec2 geoMoney1[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 475), 18.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 495), GUI_HEIGHT - 230) //Margen derecho, margen inferior }; glm::vec2 geoMoney2[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 495), 18.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 515), GUI_HEIGHT - 230) //Margen derecho, margen inferior }; glm::vec2 geoMoney3[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 515), 18.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 535), GUI_HEIGHT - 230) //Margen derecho, margen inferior }; glm::vec2 geoMoney4[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 535), 18.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 555), GUI_HEIGHT - 230) //Margen derecho, margen inferior }; moneyTexQuad1 = TexturedQuad::createTexturedQuad(geoMoney1, texCoords, texProgram); moneyTexture1.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); moneyTexQuad2 = TexturedQuad::createTexturedQuad(geoMoney2, texCoords, texProgram); moneyTexture2.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); moneyTexQuad3 = TexturedQuad::createTexturedQuad(geoMoney3, texCoords, texProgram); moneyTexture3.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); moneyTexQuad4 = TexturedQuad::createTexturedQuad(geoMoney4, texCoords, texProgram); moneyTexture4.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); //Score glm::vec2 geoScore1[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 475), 75.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 495), GUI_HEIGHT - 175) //Margen derecho, margen inferior }; glm::vec2 geoScore2[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 495), 75.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 515), GUI_HEIGHT - 175) //Margen derecho, margen inferior }; glm::vec2 geoScore3[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 515), 75.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 535), GUI_HEIGHT - 175) //Margen derecho, margen inferior }; glm::vec2 geoScore4[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 535), 75.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 555), GUI_HEIGHT - 175) //Margen derecho, margen inferior }; scoreTexQuad1 = TexturedQuad::createTexturedQuad(geoScore1, texCoords, texProgram); scoreTexture1.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); scoreTexQuad2 = TexturedQuad::createTexturedQuad(geoScore2, texCoords, texProgram); scoreTexture2.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); scoreTexQuad3 = TexturedQuad::createTexturedQuad(geoScore3, texCoords, texProgram); scoreTexture3.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); scoreTexQuad4 = TexturedQuad::createTexturedQuad(geoScore4, texCoords, texProgram); scoreTexture4.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); //Vidas glm::vec2 geoVidas[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 505), 130.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 525), GUI_HEIGHT - 120) //Margen derecho, margen inferior }; vidasTexQuad = TexturedQuad::createTexturedQuad(geoVidas, texCoords, texProgram); vidasTexture.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); //Level glm::vec2 geoLevel[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 505), 180.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 525), GUI_HEIGHT - 70) //Margen derecho, margen inferior }; levelTexQuad = TexturedQuad::createTexturedQuad(geoLevel, texCoords, texProgram); levelTexture.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); //Stage glm::vec2 geoStage[2] = { glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 505), 230.f), //Margen izquierdo, margen superior glm::vec2(float(GUI_ABILITY_IMG_WIDTH + 525), GUI_HEIGHT - 20) //Margen derecho, margen inferior }; stageTexQuad = TexturedQuad::createTexturedQuad(geoStage, texCoords, texProgram); stageTexture.loadFromFile("images/bluebrick.png", TEXTURE_PIXEL_FORMAT_RGBA); //leer numeros del fichero cero.loadFromFile("images/cero.png", TEXTURE_PIXEL_FORMAT_RGBA); uno.loadFromFile("images/uno.png", TEXTURE_PIXEL_FORMAT_RGBA); dos.loadFromFile("images/dos.png", TEXTURE_PIXEL_FORMAT_RGBA); tres.loadFromFile("images/tres.png", TEXTURE_PIXEL_FORMAT_RGBA); cuatro.loadFromFile("images/cuatro.png", TEXTURE_PIXEL_FORMAT_RGBA); cinco.loadFromFile("images/cinco.png", TEXTURE_PIXEL_FORMAT_RGBA); seis.loadFromFile("images/seis.png", TEXTURE_PIXEL_FORMAT_RGBA); siete.loadFromFile("images/siete.png", TEXTURE_PIXEL_FORMAT_RGBA); ocho.loadFromFile("images/ocho.png", TEXTURE_PIXEL_FORMAT_RGBA); nueve.loadFromFile("images/nueve.png", TEXTURE_PIXEL_FORMAT_RGBA); } void GUI::actualizarGui(int money, int score, int vidas, int stage, int level) { //asignar money moneyTexture4 = asignarnum(money % 10); moneyTexture3 = asignarnum((money / 10) % 10); moneyTexture2 = asignarnum((money / 100) % 10); moneyTexture1 = asignarnum((money / 1000) % 10); //asignar puntuacion scoreTexture4 = asignarnum(score % 10); scoreTexture3 = asignarnum((score / 10) % 10); scoreTexture2 = asignarnum((score / 100) % 10); scoreTexture1 = asignarnum((score / 1000) % 10); //asignar vidas vidasTexture = asignarnum(vidas); //asignar stage stageTexture = asignarnum(stage); //asignar level levelTexture = asignarnum(level); } void GUI::render() { texProgram.use(); texProgram.setUniformMatrix4f("projection", projection); texProgram.setUniform4f("color", 1.0f, 1.0f, 1.0f, 1.0f); //Color uniform transform texProgram.setUniform2f("texCoordDispl", 0.f, 0.f); glm::mat4 modelview; //BACKGROUND modelview = glm::translate(glm::mat4(1.0f), glm::vec3(0.f, SCREEN_HEIGHT - GUI_HEIGHT, 0.f)); texProgram.setUniformMatrix4f("modelview", modelview); mainTextureQuad->render(mainTexture); //Money moneyTexQuad1->render(moneyTexture1);//4 moneyTexQuad2->render(moneyTexture2);//3 moneyTexQuad3->render(moneyTexture3);//2 moneyTexQuad4->render(moneyTexture4);//1 //Score scoreTexQuad1->render(scoreTexture1);//4 scoreTexQuad2->render(scoreTexture2);//3 scoreTexQuad3->render(scoreTexture3);//2 scoreTexQuad4->render(scoreTexture4);//1 //Vidas vidasTexQuad->render(vidasTexture); //Level levelTexQuad->render(levelTexture); //Stage stageTexQuad->render(stageTexture); } void GUI::initShaders() { Shader vShader, fShader; vShader.initFromFile(VERTEX_SHADER, "shaders/texture.vert"); if (!vShader.isCompiled()) { cout << "Vertex Shader Error" << endl; cout << "" << vShader.log() << endl << endl; } fShader.initFromFile(FRAGMENT_SHADER, "shaders/texture.frag"); if (!fShader.isCompiled()) { cout << "Fragment Shader Error" << endl; cout << "" << fShader.log() << endl << endl; } texProgram.init(); texProgram.addShader(vShader); texProgram.addShader(fShader); texProgram.link(); if (!texProgram.isLinked()) { cout << "Shader Linking Error" << endl; cout << "" << texProgram.log() << endl << endl; } texProgram.bindFragmentOutput("outColor"); vShader.free(); fShader.free(); } Texture GUI::asignarnum(int num) { if (num == 0) return cero; else if (num == 1) return uno; else if (num == 2) return dos; else if (num == 3) return tres; else if (num == 4) return cuatro; else if (num == 5) return cinco; else if (num == 6) return seis; else if (num == 7) return siete; else if (num == 8) return ocho; else if (num == 9) return nueve; }
ea69e99c511609cbaf61fba3e6b4edc73f789876
913f9a9ed223740923a87a57eb05ed1d5a83dfea
/IntroToArduino/3.1.3/controlContador/controlContador.ino
9f6fc0bc2a355634c0f113f5b502cc09010779b8
[]
no_license
tabris2015/Elemental
e40fdf238d6b88aaf388f70beba4f6bba4b4de81
3672cc17d0578e755d8811c33a05a1bd9057afe8
refs/heads/master
2020-04-06T03:33:57.465464
2016-11-07T16:35:38
2016-11-07T16:35:38
57,926,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
ino
controlContador.ino
#define LED_PIN 13 #define IN1 5 #define IN2 4 #define BOTON_PIN 12 int estado; int estado_ant; int modo = 0; int contador = 0; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BOTON_PIN, INPUT_PULLUP); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); Serial.begin(9600); } void loop() { estado = digitalRead(BOTON_PIN); if(estado != estado_ant) { if(estado == 1) { contador = contador + 1; Serial.println(contador); if(modo == 0) { if(contador > 2) { modo = 1; contador = 0; Serial.println("entrando modo 1"); } } else if(modo == 1) { if(contador > 2) { modo = 2; contador = 0; Serial.println("entrando modo 2"); } } else if(modo == 2) { if(contador > 1) { modo = 0; contador = 0; Serial.println("entrando modo 0"); } } } } if(modo == 0) // detener { digitalWrite(IN1, 0); digitalWrite(IN2, 0); } else if(modo == 1) // adelante { digitalWrite(IN1, 0); digitalWrite(IN2, 1); } else if(modo == 2) // atras { digitalWrite(IN1, 1); digitalWrite(IN2, 0); } else { digitalWrite(IN1, 0); digitalWrite(IN2, 0); } estado_ant = estado; delay(50); }
12bc65f47f4a7ef4aca462b3232312f864d88be4
c20d422cfc6f969b2dbefe670781aa94bd6474c3
/oomact/src/model/FrameGraphModel.cpp
2cb98ef5b43f21e060d01e35c9fb449c6f369408
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
liuwenhaha/oomact
4ea0a82aa28ba73cf16bbb6f9de97302963f29c0
b157a1a3338358afb52a8754a9e9a38b35401894
refs/heads/master
2020-04-27T17:05:04.084384
2019-03-01T15:12:58
2019-03-01T15:12:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,627
cpp
FrameGraphModel.cpp
#include <aslam/calibration/model/FrameGraphModel.h> #include <aslam/backend/KinematicChain.hpp> #include <aslam/backend/Vector2RotationQuaternionExpressionAdapter.hpp> #include <aslam/calibration/model/fragments/So3R3Trajectory.h> #include <aslam/calibration/model/Model.h> #include <glog/logging.h> #include <aslam/calibration/model/PoseTrajectory.h> #include <aslam/calibration/model/fragments/PoseCv.h> #include <aslam/calibration/tools/Tree.h> namespace aslam { namespace calibration { constexpr int getVariability(BoundedTimeExpression*){ return 1; } constexpr int getVariability(Timestamp*){ return 0; } template <typename T> constexpr int addVariablitiy(int i){ return i + getVariability(static_cast<T*>(nullptr)); } using namespace aslam::backend; template <typename A> aslam::backend::CoordinateFrame computeTrajectoryFrame(boost::shared_ptr<const CoordinateFrame> parent, A expressionFactories, bool needGlobalPosition, int maximalDerivativeOrder){ return CoordinateFrame( parent, //TODO O The adapter is a big waste of time. There are more direct ways (UnitQuaternion expressions ..) Vector2RotationQuaternionExpressionAdapter::adapt(expressionFactories.rot.getValueExpression()), needGlobalPosition ? expressionFactories.trans.getValueExpression(0) : EuclideanExpression(), maximalDerivativeOrder >= 1 ? -EuclideanExpression(expressionFactories.rot.getAngularVelocityExpression()) : EuclideanExpression(), maximalDerivativeOrder >= 1 ? EuclideanExpression(expressionFactories.trans.getValueExpression(1)) : EuclideanExpression(), maximalDerivativeOrder >= 2 ? -EuclideanExpression(expressionFactories.rot.getAngularAccelerationExpression()) : EuclideanExpression(), maximalDerivativeOrder >= 2 ? EuclideanExpression(expressionFactories.trans.getValueExpression(2)) : EuclideanExpression() ); } struct FrameLink { union Ptr { const PoseCv* sensor; PoseTrajectory* poseTraj; Ptr(const PoseCv* sensor) : sensor(sensor) {} Ptr(PoseTrajectory* poseTraj) : poseTraj(poseTraj) {} } ptr; enum class Type { PoseCv, Trajectory } type; FrameLink(const PoseCv* sensor) : ptr(sensor), type(Type::PoseCv) {} FrameLink(PoseTrajectory* traj) : ptr(traj), type(Type::Trajectory) {} }; class FrameGraph: public Tree<const Frame*, FrameLink> { }; template <typename Time> class FrameGraphModelAtTimeImpl: public ModelAtTimeImpl { public: FrameGraphModelAtTimeImpl(const FrameGraphModel & fgModel, Time timestamp, int maximalDerivativeOrder, const ModelSimplification& simplification) : maximalDerivativeOrder_(maximalDerivativeOrder), fgModel_(fgModel), simplification_(simplification), timestamp_(timestamp) { } template <int maximalDerivativeOrder> CoordinateFrame getCoordinateFrame(const Frame & to, const Frame & from, const size_t originalMaximalDerivativeOrder) const { boost::shared_ptr<CoordinateFrame> f, fInv; fgModel_.frameGraph_->walkPath(&from , &to, [&](const FrameLink & frameLink, bool inverse){ CHECK(inverse) << "to=" << to << ", from=" << from; switch(frameLink.type){ case FrameLink::Type::PoseCv: { const PoseCv & poseCv = *frameLink.ptr.sensor; f = boost::make_shared<CoordinateFrame>( f, poseCv.getRotationToParentExpression(), poseCv.getTranslationToParentExpression() ); } break; case FrameLink::Type::Trajectory: f = boost::make_shared<CoordinateFrame>( computeTrajectoryFrame( f, frameLink.ptr.poseTraj->getCurrentTrajectory().getExpressionFactoryPair<maximalDerivativeOrder>(timestamp_), simplification_.needGlobalPosition, originalMaximalDerivativeOrder ) ); break; default: CHECK(false); } }); return std::move(*f); } aslam::backend::CoordinateFrame getCoordinateFrame(const Frame & to, const Frame & from) const { if(from == to) return CoordinateFrame(); switch(addVariablitiy<Time>(maximalDerivativeOrder_)){ case 0: case 1: case 2: //TODO O support maximalDerivativeOrder_ below 2 in getCoordinateFrame properly (requires turning off accelerations in computeTrajectoryFrame for that case! return getCoordinateFrame<2>(to, from, maximalDerivativeOrder_); case 3: return getCoordinateFrame<3>(to, from, maximalDerivativeOrder_); case 4: return getCoordinateFrame<4>(to, from, maximalDerivativeOrder_); default: LOG(FATAL) << "Unsupported maximal derivative order " << maximalDerivativeOrder_; throw 0; // dummy } } aslam::backend::TransformationExpression getTransformationToFrom(const Frame & to, const Frame & from) const override { const Frame & closestCommonAncestor = *fgModel_.frameGraph_->getClosestCommonAncestor(&to, &from); auto toCFrame = getCoordinateFrame(to, closestCommonAncestor); auto fromCFrame = getCoordinateFrame(from, closestCommonAncestor); return aslam::backend::TransformationExpression(toCFrame.getR_G_L(), toCFrame.getPG()).inverse() * aslam::backend::TransformationExpression(fromCFrame.getR_G_L(), fromCFrame.getPG()); } aslam::backend::EuclideanExpression getAcceleration(const Frame & of, const Frame & frame) const override { return getCoordinateFrame(of, frame).getAG(); } aslam::backend::EuclideanExpression getVelocity(const Frame & of, const Frame & frame) const override { return getCoordinateFrame(of, frame).getVG(); } aslam::backend::EuclideanExpression getAngularVelocity(const Frame & of, const Frame & frame) const override { return getCoordinateFrame(of, frame).getOmegaG(); } aslam::backend::EuclideanExpression getAngularAcceleration(const Frame & of, const Frame & frame) const override { return getCoordinateFrame(of, frame).getAlphaG(); } private: int maximalDerivativeOrder_; const FrameGraphModel & fgModel_; const ModelSimplification simplification_; Time timestamp_; }; FrameGraphModel::FrameGraphModel(ValueStoreRef config, std::shared_ptr<ConfigPathResolver> configPathResolver, const std::vector<const Frame*> frames) : Model(config, configPathResolver, frames), frameGraph_(new FrameGraph()) { } FrameGraphModel::~FrameGraphModel(){ } ModelAtTime FrameGraphModel::getAtTime(Timestamp timestamp, int maximalDerivativeOrder, const ModelSimplification& simplification) const { return ModelAtTime(std::unique_ptr<ModelAtTimeImpl>(new FrameGraphModelAtTimeImpl<Timestamp>(*this, timestamp, maximalDerivativeOrder, simplification))); } ModelAtTime FrameGraphModel::getAtTime(const BoundedTimeExpression& boundedTimeExpresion, int maximalDerivativeOrder, const ModelSimplification& simplification) const { return ModelAtTime(std::unique_ptr<ModelAtTimeImpl>(new FrameGraphModelAtTimeImpl<BoundedTimeExpression>(*this, boundedTimeExpresion, maximalDerivativeOrder, simplification))); } void FrameGraphModel::registerModule(Module& m) { Model::registerModule(m); if(auto trajPtr = m.ptrAs<PoseTrajectory>()){ frameGraph_->add(&trajPtr->getFrame(), &trajPtr->getReferenceFrame(), FrameLink{trajPtr}); } else if (auto sensorPtr = m.ptrAs<PoseCv>()){ frameGraph_->add(&sensorPtr->getFrame(), &sensorPtr->getParentFrame(), FrameLink{sensorPtr}); } } void FrameGraphModel::init() { frameGraph_->init(); Model::init(); } } /* namespace calibration */ } /* namespace aslam */
ba9c990e427f2c82a619b4fdfe2f63acb1fa841d
425963de819e446a75441ff901adbfe5f1c5dea6
/content/renderer/media/stream/media_stream_audio_processor_unittest.cc
662e3b19cec275657d2991ae1eb105a2beb74d3a
[ "BSD-3-Clause" ]
permissive
Igalia/chromium
06590680bcc074cf191979c496d84888dbb54df6
261db3a6f6a490742786cf841afa92e02a53b33f
refs/heads/ozone-wayland-dev
2022-12-06T16:31:09.335901
2019-12-06T21:11:21
2019-12-06T21:11:21
85,595,633
123
25
NOASSERTION
2019-02-05T08:04:47
2017-03-20T15:45:36
null
UTF-8
C++
false
false
18,895
cc
media_stream_audio_processor_unittest.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/memory/aligned_memory.h" #include "base/message_loop/message_loop_current.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "content/renderer/media/stream/media_stream_audio_processor.h" #include "content/renderer/media/stream/mock_constraint_factory.h" #include "media/base/audio_bus.h" #include "media/base/audio_parameters.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/mediastream/media_stream_request.h" #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_processor_options.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_media_constraints.h" #include "third_party/webrtc/api/media_stream_interface.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::Return; using media::AudioParameters; namespace content { namespace { const int kAudioProcessingNumberOfChannel = 1; // The number of packers used for testing. const int kNumberOfPacketsForTest = 100; const int kMaxNumberOfPlayoutDataChannels = 2; void ReadDataFromSpeechFile(char* data, int length) { base::FilePath file; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &file)); file = file.Append(FILE_PATH_LITERAL("media")) .Append(FILE_PATH_LITERAL("test")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("speech_16b_stereo_48kHz.raw")); DCHECK(base::PathExists(file)); int64_t data_file_size64 = 0; DCHECK(base::GetFileSize(file, &data_file_size64)); EXPECT_EQ(length, base::ReadFile(file, data, length)); DCHECK(data_file_size64 > length); } } // namespace class MediaStreamAudioProcessorTest : public ::testing::Test { public: MediaStreamAudioProcessorTest() : params_(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO, 48000, 480) {} protected: // Helper method to save duplicated code. void ProcessDataAndVerifyFormat(MediaStreamAudioProcessor* audio_processor, int expected_output_sample_rate, int expected_output_channels, int expected_output_buffer_size) { // Read the audio data from a file. const media::AudioParameters& params = audio_processor->InputFormat(); const int packet_size = params.frames_per_buffer() * 2 * params.channels(); const size_t length = packet_size * kNumberOfPacketsForTest; std::unique_ptr<char[]> capture_data(new char[length]); ReadDataFromSpeechFile(capture_data.get(), length); const int16_t* data_ptr = reinterpret_cast<const int16_t*>(capture_data.get()); std::unique_ptr<media::AudioBus> data_bus = media::AudioBus::Create(params.channels(), params.frames_per_buffer()); // |data_bus_playout| is used if the number of capture channels is larger // that max allowed playout channels. |data_bus_playout_to_use| points to // the AudioBus to use, either |data_bus| or |data_bus_playout|. std::unique_ptr<media::AudioBus> data_bus_playout; media::AudioBus* data_bus_playout_to_use = data_bus.get(); if (params.channels() > kMaxNumberOfPlayoutDataChannels) { data_bus_playout = media::AudioBus::CreateWrapper(kMaxNumberOfPlayoutDataChannels); data_bus_playout->set_frames(params.frames_per_buffer()); data_bus_playout_to_use = data_bus_playout.get(); } const base::TimeDelta input_capture_delay = base::TimeDelta::FromMilliseconds(20); const base::TimeDelta output_buffer_duration = expected_output_buffer_size * base::TimeDelta::FromSeconds(1) / expected_output_sample_rate; for (int i = 0; i < kNumberOfPacketsForTest; ++i) { data_bus->FromInterleaved(data_ptr, data_bus->frames(), 2); audio_processor->PushCaptureData(*data_bus, input_capture_delay); // |audio_processor| does nothing when the audio processing is off in // the processor. webrtc::AudioProcessing* ap = audio_processor->audio_processing_.get(); const bool is_aec_enabled = ap && ap->GetConfig().echo_canceller.enabled; if (is_aec_enabled) { if (params.channels() > kMaxNumberOfPlayoutDataChannels) { for (int i = 0; i < kMaxNumberOfPlayoutDataChannels; ++i) { data_bus_playout->SetChannelData( i, const_cast<float*>(data_bus->channel(i))); } } audio_processor->OnPlayoutData(data_bus_playout_to_use, params.sample_rate(), 10); } media::AudioBus* processed_data = nullptr; base::TimeDelta capture_delay; int new_volume = 0; while (audio_processor->ProcessAndConsumeData( 255, false, &processed_data, &capture_delay, &new_volume)) { EXPECT_TRUE(processed_data); EXPECT_NEAR(input_capture_delay.InMillisecondsF(), capture_delay.InMillisecondsF(), output_buffer_duration.InMillisecondsF()); EXPECT_EQ(expected_output_sample_rate, audio_processor->OutputFormat().sample_rate()); EXPECT_EQ(expected_output_channels, audio_processor->OutputFormat().channels()); EXPECT_EQ(expected_output_buffer_size, audio_processor->OutputFormat().frames_per_buffer()); } data_ptr += params.frames_per_buffer() * params.channels(); } } void VerifyDefaultComponents(MediaStreamAudioProcessor* audio_processor) { webrtc::AudioProcessing* audio_processing = audio_processor->audio_processing_.get(); const webrtc::AudioProcessing::Config config = audio_processing->GetConfig(); EXPECT_TRUE(config.echo_canceller.enabled); #if defined(OS_ANDROID) EXPECT_TRUE(config.echo_canceller.mobile_mode); EXPECT_FALSE(config.voice_detection.enabled); #else EXPECT_FALSE(config.echo_canceller.mobile_mode); EXPECT_TRUE(config.voice_detection.enabled); #endif EXPECT_TRUE(config.high_pass_filter.enabled); EXPECT_TRUE(audio_processing->noise_suppression()->is_enabled()); EXPECT_TRUE(audio_processing->noise_suppression()->level() == webrtc::NoiseSuppression::kHigh); EXPECT_TRUE(audio_processing->gain_control()->is_enabled()); #if defined(OS_ANDROID) EXPECT_TRUE(audio_processing->gain_control()->mode() == webrtc::GainControl::kFixedDigital); #else EXPECT_TRUE(audio_processing->gain_control()->mode() == webrtc::GainControl::kAdaptiveAnalog); #endif } base::test::ScopedTaskEnvironment scoped_task_environment_; media::AudioParameters params_; }; // Test crashing with ASAN on Android. crbug.com/468762 #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) #define MAYBE_WithAudioProcessing DISABLED_WithAudioProcessing #else #define MAYBE_WithAudioProcessing WithAudioProcessing #endif TEST_F(MediaStreamAudioProcessorTest, MAYBE_WithAudioProcessing) { scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_TRUE(audio_processor->has_audio_processing()); audio_processor->OnCaptureFormatChanged(params_); VerifyDefaultComponents(audio_processor.get()); ProcessDataAndVerifyFormat( audio_processor.get(), blink::kAudioProcessingSampleRate, kAudioProcessingNumberOfChannel, blink::kAudioProcessingSampleRate / 100); // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } TEST_F(MediaStreamAudioProcessorTest, TurnOffDefaultConstraints) { blink::AudioProcessingProperties properties; // Turn off the default constraints and pass it to MediaStreamAudioProcessor. properties.DisableDefaultProperties(); scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_FALSE(audio_processor->has_audio_processing()); audio_processor->OnCaptureFormatChanged(params_); ProcessDataAndVerifyFormat(audio_processor.get(), params_.sample_rate(), params_.channels(), params_.sample_rate() / 100); // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } // Test crashing with ASAN on Android. crbug.com/468762 #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) #define MAYBE_TestAllSampleRates DISABLED_TestAllSampleRates #else #define MAYBE_TestAllSampleRates TestAllSampleRates #endif TEST_F(MediaStreamAudioProcessorTest, MAYBE_TestAllSampleRates) { scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_TRUE(audio_processor->has_audio_processing()); static const int kSupportedSampleRates[] = { 8000, 16000, 22050, 32000, 44100, 48000 }; for (size_t i = 0; i < base::size(kSupportedSampleRates); ++i) { int buffer_size = kSupportedSampleRates[i] / 100; media::AudioParameters params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO, kSupportedSampleRates[i], buffer_size); audio_processor->OnCaptureFormatChanged(params); VerifyDefaultComponents(audio_processor.get()); ProcessDataAndVerifyFormat(audio_processor.get(), blink::kAudioProcessingSampleRate, kAudioProcessingNumberOfChannel, blink::kAudioProcessingSampleRate / 100); } // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } // Test that if we have an AEC dump message filter created, we are getting it // correctly in MSAP. Any IPC messages will be deleted since no sender in the // filter will be created. TEST_F(MediaStreamAudioProcessorTest, GetAecDumpMessageFilter) { scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter_( new AecDumpMessageFilter( blink::scheduler::GetSingleThreadTaskRunnerForTesting(), blink::scheduler::GetSingleThreadTaskRunnerForTesting())); scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_TRUE(audio_processor->aec_dump_message_filter_.get()); // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } TEST_F(MediaStreamAudioProcessorTest, StartStopAecDump) { scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); base::FilePath temp_file_path; ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_directory.GetPath(), &temp_file_path)); { scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); // Start and stop recording. audio_processor->OnAecDumpFile(IPC::TakePlatformFileForTransit(base::File( temp_file_path, base::File::FLAG_WRITE | base::File::FLAG_OPEN))); audio_processor->OnDisableAecDump(); // Start and wait for d-tor. audio_processor->OnAecDumpFile(IPC::TakePlatformFileForTransit(base::File( temp_file_path, base::File::FLAG_WRITE | base::File::FLAG_OPEN))); } // Check that dump file is non-empty after audio processor has been // destroyed. Note that this test fails when compiling WebRTC // without protobuf support, rtc_enable_protobuf=false. std::string output; ASSERT_TRUE(base::ReadFileToString(temp_file_path, &output)); ASSERT_FALSE(output.empty()); // The tempory file is deleted when temp_directory exists scope. } TEST_F(MediaStreamAudioProcessorTest, TestStereoAudio) { scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; // Turn off the audio processing and turn on the stereo channels mirroring. properties.DisableDefaultProperties(); properties.goog_audio_mirroring = true; scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_FALSE(audio_processor->has_audio_processing()); const media::AudioParameters source_params( media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO, 48000, 480); audio_processor->OnCaptureFormatChanged(source_params); // There's no sense in continuing if this fails. ASSERT_EQ(2, audio_processor->OutputFormat().channels()); // Construct left and right channels, and assign different values to the // first data of the left channel and right channel. const int size = media::AudioBus::CalculateMemorySize(source_params); std::unique_ptr<float, base::AlignedFreeDeleter> left_channel( static_cast<float*>(base::AlignedAlloc(size, 32))); std::unique_ptr<float, base::AlignedFreeDeleter> right_channel( static_cast<float*>(base::AlignedAlloc(size, 32))); std::unique_ptr<media::AudioBus> wrapper = media::AudioBus::CreateWrapper(source_params.channels()); wrapper->set_frames(source_params.frames_per_buffer()); wrapper->SetChannelData(0, left_channel.get()); wrapper->SetChannelData(1, right_channel.get()); wrapper->Zero(); float* left_channel_ptr = left_channel.get(); left_channel_ptr[0] = 1.0f; // Run the test consecutively to make sure the stereo channels are not // flipped back and forth. static const int kNumberOfPacketsForTest = 100; const base::TimeDelta pushed_capture_delay = base::TimeDelta::FromMilliseconds(42); for (int i = 0; i < kNumberOfPacketsForTest; ++i) { audio_processor->PushCaptureData(*wrapper, pushed_capture_delay); media::AudioBus* processed_data = nullptr; base::TimeDelta capture_delay; int new_volume = 0; EXPECT_TRUE(audio_processor->ProcessAndConsumeData( 0, false, &processed_data, &capture_delay, &new_volume)); EXPECT_TRUE(processed_data); EXPECT_EQ(processed_data->channel(0)[0], 0); EXPECT_NE(processed_data->channel(1)[0], 0); EXPECT_EQ(pushed_capture_delay, capture_delay); } // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } // Disabled on android clang builds due to crbug.com/470499 #if defined(__clang__) && defined(OS_ANDROID) #define MAYBE_TestWithKeyboardMicChannel DISABLED_TestWithKeyboardMicChannel #else #define MAYBE_TestWithKeyboardMicChannel TestWithKeyboardMicChannel #endif TEST_F(MediaStreamAudioProcessorTest, MAYBE_TestWithKeyboardMicChannel) { scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device( new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()); blink::AudioProcessingProperties properties; scoped_refptr<MediaStreamAudioProcessor> audio_processor( new rtc::RefCountedObject<MediaStreamAudioProcessor>( properties, webrtc_audio_device.get())); EXPECT_TRUE(audio_processor->has_audio_processing()); media::AudioParameters params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, media::CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC, 48000, 480); audio_processor->OnCaptureFormatChanged(params); ProcessDataAndVerifyFormat( audio_processor.get(), blink::kAudioProcessingSampleRate, kAudioProcessingNumberOfChannel, blink::kAudioProcessingSampleRate / 100); // Stop |audio_processor| so that it removes itself from // |webrtc_audio_device| and clears its pointer to it. audio_processor->Stop(); } TEST_F(MediaStreamAudioProcessorTest, GetExtraGainConfigNullOpt) { base::Optional<std::string> audio_processing_platform_config_json; base::Optional<double> pre_amplifier_fixed_gain_factor, gain_control_compression_gain_db; blink::GetExtraGainConfig(audio_processing_platform_config_json, &pre_amplifier_fixed_gain_factor, &gain_control_compression_gain_db); EXPECT_FALSE(pre_amplifier_fixed_gain_factor); EXPECT_FALSE(gain_control_compression_gain_db); } TEST_F(MediaStreamAudioProcessorTest, GetExtraGainConfig) { base::Optional<std::string> audio_processing_platform_config_json = "{\"gain_control_compression_gain_db\": 10}"; base::Optional<double> pre_amplifier_fixed_gain_factor, gain_control_compression_gain_db; blink::GetExtraGainConfig(audio_processing_platform_config_json, &pre_amplifier_fixed_gain_factor, &gain_control_compression_gain_db); EXPECT_FALSE(pre_amplifier_fixed_gain_factor); EXPECT_TRUE(gain_control_compression_gain_db); EXPECT_EQ(gain_control_compression_gain_db.value(), 10); } } // namespace content
20e7c496891915be8da9ce6d1dc328bcc9dd8024
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/src/Physics/Constraint.cpp
ad8027fc6ae297f0a84cc48064f978b89160e43e
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
6,788
cpp
Constraint.cpp
#include "stdafx.h" #include "Database/Archive.h" #include "Physics/Constraint.h" #include "Physics/DynamicsWorld.h" #include "Physics/RigidBody.h" #include "Physics/ServoMotor.h" #include "Physics/VelocityMotor.h" #ifdef SLON_ENGINE_USE_BULLET # include "Physics/Bullet/BulletConstraint.h" #endif namespace slon { namespace physics { Constraint::Constraint(const DESC& desc_) : desc(desc_) { if (desc.rigidBodies[0]) { desc.rigidBodies[0]->addConstraint(this); } if (desc.rigidBodies[1]) { desc.rigidBodies[1]->addConstraint(this); } } Constraint::~Constraint() { } // Override Serializable const char* Constraint::serialize(database::OArchive& ar) const { ar.writeStringChunk("name", desc.name.data(), desc.name.length()); ar.writeSerializable(desc.rigidBodies[0].get()); ar.writeSerializable(desc.rigidBodies[1].get()); ar.writeChunk("frame0", desc.frames[0].data(), desc.frames[0].num_elements); ar.writeChunk("frame1", desc.frames[1].data(), desc.frames[1].num_elements); ar.writeChunk("linearLimits0", desc.linearLimits[0].arr, desc.linearLimits[0].num_elements); ar.writeChunk("linearLimits1", desc.linearLimits[1].arr, desc.linearLimits[1].num_elements); ar.writeChunk("angularLimits0", desc.angularLimits[0].arr, desc.angularLimits[0].num_elements); ar.writeChunk("angularLimits1", desc.angularLimits[1].arr, desc.angularLimits[1].num_elements); ar.writeChunk("ignoreCollisions", &desc.ignoreCollisions); return "Constraint"; } void Constraint::deserialize(database::IArchive& ar) { if (desc.rigidBodies[0]) { desc.rigidBodies[0]->removeConstraint(this); } if (desc.rigidBodies[1]) { desc.rigidBodies[1]->removeConstraint(this); } ar.readStringChunk("name", desc.name); desc.rigidBodies[0] = ar.readSerializable<RigidBody>(); if (desc.rigidBodies[0]) { desc.rigidBodies[0]->addConstraint(this); } desc.rigidBodies[1] = ar.readSerializable<RigidBody>(); if (desc.rigidBodies[1]) { desc.rigidBodies[1]->addConstraint(this); } ar.readChunk("frame0", desc.frames[0].data(), desc.frames[0].num_elements); ar.readChunk("frame1", desc.frames[1].data(), desc.frames[1].num_elements); ar.readChunk("linearLimits0", desc.linearLimits[0].arr, desc.linearLimits[0].num_elements); ar.readChunk("linearLimits1", desc.linearLimits[1].arr, desc.linearLimits[1].num_elements); ar.readChunk("angularLimits0", desc.angularLimits[0].arr, desc.angularLimits[0].num_elements); ar.readChunk("angularLimits1", desc.angularLimits[1].arr, desc.angularLimits[1].num_elements); ar.readChunk("ignoreCollisions", &desc.ignoreCollisions); instantiate(); } RigidBody* Constraint::getRigidBodyA() const { return desc.rigidBodies[0].get(); } const math::RigidTransformr& Constraint::getFrameInA() const { return desc.frames[0]; } RigidBody* Constraint::getRigidBodyB() const { return desc.rigidBodies[1].get(); } const math::RigidTransformr& Constraint::getFrameInB() const { return desc.frames[1]; } const Motor* Constraint::getMotor(DOF dof) const { return motors[dof].get(); } Motor* Constraint::getMotor(DOF dof) { return motors[dof].get(); } ServoMotor* Constraint::createServoMotor(DOF dof) { assert( getRestriction(dof) != AXIS_LOCKED ); motors[dof].reset( new ServoMotor(this, dof) ); if (impl) { motors[dof]->instantiate(); } return static_cast<ServoMotor*>(motors[dof].get()); } VelocityMotor* Constraint::createVelocityMotor(DOF dof) { assert( getRestriction(dof) != AXIS_LOCKED ); motors[dof].reset( new VelocityMotor(this, dof) ); if (impl) { motors[dof]->instantiate(); } return static_cast<VelocityMotor*>(motors[dof].get()); } SpringMotor* Constraint::createSpringMotor(DOF dof) { assert( getRestriction(dof) != AXIS_LOCKED ); //motors[dof].reset( new SpringMotor(this, dof) ); //return motors[dof].get(); return 0; } math::Vector3r Constraint::getAxis(unsigned int axis) const { return impl->getAxis(axis); } real Constraint::getPosition(DOF dof) const { return impl->getPosition(dof); } Constraint::AXIS_RESTRICTION Constraint::getRestriction(DOF dof) const { if (dof < 3) { if ( desc.linearLimits[0][dof] == -std::numeric_limits<real>::infinity() && desc.linearLimits[1][dof] == std::numeric_limits<real>::infinity() ) { return AXIS_FREE; } else if (desc.linearLimits[0][dof] < desc.linearLimits[1][dof]) { return AXIS_RESTRICTED; } } else { int i = dof - 3; if ( desc.angularLimits[0][i] == -std::numeric_limits<real>::infinity() && desc.angularLimits[1][i] == std::numeric_limits<real>::infinity() ) { return AXIS_FREE; } else if (desc.angularLimits[0][i] < desc.angularLimits[1][i]) { return AXIS_RESTRICTED; } } return AXIS_LOCKED; } const std::string& Constraint::getName() const { return desc.name; } const Constraint::DESC& Constraint::getDesc() const { return desc; } const DynamicsWorld* Constraint::getDynamicsWorld() const { return world.get(); } void Constraint::reset(const DESC& desc_) { if (desc.rigidBodies[0]) { desc.rigidBodies[0]->removeConstraint(this); } if (desc.rigidBodies[1]) { desc.rigidBodies[1]->removeConstraint(this); } desc = desc_; if (desc.rigidBodies[0]) { desc.rigidBodies[0]->addConstraint(this); } if (desc.rigidBodies[1]) { desc.rigidBodies[1]->addConstraint(this); } instantiate(); } void Constraint::setWorld(const dynamics_world_ptr& world_) { assert( desc.rigidBodies[0] && desc.rigidBodies[1] && "Constraint must specify affected rigid bodies."); release(); world = world_; instantiate(); } void Constraint::instantiate() { if (!desc.rigidBodies[0] || !desc.rigidBodies[1]) { return; } if ( !impl && world && desc.rigidBodies[0]->getDynamicsWorld() && desc.rigidBodies[1]->getDynamicsWorld() ) { assert( world == desc.rigidBodies[0]->getDynamicsWorld() && desc.rigidBodies[0]->getDynamicsWorld() == desc.rigidBodies[0]->getDynamicsWorld() && "Linked bodies and constraint should be in same dynamics world." ); impl.reset( new BulletConstraint(this, world->getImpl()) ); for (int i = 0; i<6; ++i) { if (motors[i]) { motors[i]->instantiate(); } } } } void Constraint::release() { for (int i = 0; i<6; ++i) { if (motors[i]) { motors[i]->release(); } } impl.reset(); } } // namespace physics } // namespace slon
91a9f8906d45a6bbf7c419d439c1dd03257ac950
2757bb1c7fd14f5286757a5c247a41e537e914b6
/USACO/rectbarn.cpp
1e7343c41b483d1b4c6cdd22295cb7b0b4accbd6
[]
no_license
ErickLin/competitive-programming
ad71814b9dd82062009df9c59f7462ee3c074837
bca3e39c33e65f6fbfc3c297dc980bbaeae30291
refs/heads/master
2021-01-17T08:44:16.787115
2018-04-17T16:13:23
2018-04-17T18:56:20
39,700,329
0
0
null
null
null
null
UTF-8
C++
false
false
4,952
cpp
rectbarn.cpp
/* ID: Jugglebrosjr2 LANG: C++ TASK: rectbarn */ #include <algorithm> #include <fstream> #include <iostream> #include <set> #include <stack> #include <vector> using namespace std; struct cmp { bool operator()(const pair<int, int> &a, const pair<int, int> &b) { if (a.second == b.second) { return a.first < b.first; } return a.second < b.second; } }; int main() { ifstream fin("rectbarn.in"); ofstream fout("rectbarn.out"); int r, c, p; fin >> r >> c >> p; set<pair<int, int>, cmp> damaged; for (int i = 0; i < p; i++) { int a, b; fin >> a >> b; damaged.insert(make_pair(--a, --b)); } int ans = 0; /* //Prioritizes height over width vector<vector<pair<int, int> > > dpVert(r, vector<pair<int, int> >(c)); //Prioritizes width over height vector<vector<pair<int, int> > > dpHor(r, vector<pair<int, int> >(c)); for (int i = 0; i < r; i++) { dpVert[i][0] = dpHor[i][0] = make_pair( damaged[i][0] ? 0 : (i > 0 ? dpVert[i - 1][0].first + 1 : 1), damaged[i][0] ? 0 : 1); if (dpVert[i][0].first * dpVert[i][0].second > ans) { ans = dpVert[i][0].first * dpVert[i][0].second; } //cout << dpVert[i][0].first << ' ' << dpVert[i][0].second << '\n'; } for (int j = 0; j < c; j++) { dpVert[0][j] = dpHor[0][j] = make_pair( damaged[0][j] ? 0 : 1, damaged[0][j] ? 0 : (j > 0 ? dpVert[0][j - 1].second + 1 : 1)); if (dpVert[0][j].first * dpVert[0][j].second > ans) { ans = dpVert[0][j].first * dpVert[0][j].second; } //cout << dpVert[0][j].first << ' ' << dpVert[0][j].second << '\n'; } for (int i = 1; i < r; i++) { for (int j = 1; j < c; j++) { if (damaged[i][j]) { dpVert[i][j].first = 0; dpVert[i][j].second = 0; dpHor[i][j].first = 0; dpHor[i][j].second = 0; } else { if (damaged[i - 1][j - 1]) { dpVert[i][j].second = 1; dpHor[i][j].first = 1; } else { dpVert[i][j].second = dpVert[i][j - 1].second + 1; dpHor[i][j].first = dpHor[i - 1][j].first + 1; } dpVert[i][j].first = dpVert[i - 1][j].first + 1; dpHor[i][j].second = dpHor[i][j - 1].second + 1; } if (dpVert[i][j].first * dpVert[i][j].second > ans) { ans = dpVert[i][j].first * dpVert[i][j].second; } if (dpHor[i][j].first * dpHor[i][j].second > ans) { ans = dpHor[i][j].first * dpHor[i][j].second; } cout << dpVert[i][j].first << ' ' << dpVert[i][j].second << ' ' << dpHor[i][j].first << ' ' << dpHor[i][j].second << '\n'; } cout << '\n'; } */ set<pair<int, int>, cmp>::iterator it = damaged.begin(); vector<int> maxLen(r); for (int j = 0; j < c; j++) { //compute "histogram" for current column for (int i = 0; i < r; i++) { if (i == it->first && j == it->second) { maxLen[i] = 0; it++; } else { maxLen[i]++; } //cout << maxLen[i] << ' '; } //cout << '\n'; //each element stores its position and the position of its starting rectangle stack<pair<int, int> > s; int rectStart = 0; for (int i = 0; i < r; i++) { int currentW = maxLen[i]; //cout << "j:" << j << " i:" << i << '\n'; if (s.empty()) { rectStart = i; s.push(make_pair(i, rectStart)); } else { int otherW = maxLen[s.top().first]; if (currentW > otherW) { rectStart = i; s.push(make_pair(i, rectStart)); } else if (currentW < otherW) { do { int start = s.top().second; int end = i; ans = max(ans, (end - start) * otherW); s.pop(); rectStart = start; if (!s.empty()) { otherW = maxLen[s.top().first]; } } while (!s.empty() && currentW < otherW); s.push(make_pair(i, rectStart)); } } } while (!s.empty()) { int start = s.top().second; int end = r; int width = maxLen[s.top().first]; //cout << start << "->" << end << ": " << width << '\n'; ans = max(ans, (end - start) * width); s.pop(); } } fout << ans << '\n'; return 0; }
800808410029763236ad64f1d6e544d8b0bebc69
9d91c336fe94fb0b78b66eda1d8704906ac40893
/DetectFaces/JsonWriter.cpp
d0fbd1d1a89bede58e0029f31b881ece3b8021c3
[]
no_license
AlexeiOgurtsov/Test
cc03e1648a4e718d6cc8c5a1e410cdb37c8e2dfc
bed47bc87581c4d2546797c854234a5e8ae95708
refs/heads/master
2020-03-26T13:52:05.210998
2018-08-16T14:11:17
2018-08-16T14:11:17
142,784,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,425
cpp
JsonWriter.cpp
#include <filesystem> #include "JsonWriter.h" #include "Face.h" using namespace std; using namespace cv; using namespace boost; using namespace boost::property_tree; using namespace std::filesystem; JsonWriter::JsonWriter() { } ptree JsonWriter::makeCoordinatesRoot(Face face) { ptree root, child; vector<Point> vectorOfPoints = face.getCoordinates(); for (auto &point : vectorOfPoints) { child.put("", point); root.push_back(std::make_pair("", child)); } return root; } ptree JsonWriter::makeANodeWithFileNameAndCoordinates(Face face) { ptree root; root.put("Name Of file", face.getName()); root.add_child("Coordinates", makeCoordinatesRoot(face)); return root; } void JsonWriter::writeFacesInJson(vector<Face> faces, std::filesystem::path fileNamePath, string fileName) { ptree root, children; for (int i = 0; i < faces.size(); i++) { ptree node = makeANodeWithFileNameAndCoordinates(faces[i]); children.push_back(make_pair("", node)); } root.add_child("Result", children); write_json(generateJsonName(fileNamePath, fileName), root); } string JsonWriter::generateJsonName(std::filesystem::path fileNamePath, string fileName) { string pathString = fileNamePath.parent_path().string(); string jsonName = (boost::format("ResultJson%1%.json") % fileName).str(); string fullPath = (boost::format("%1%/%2%") % pathString % jsonName).str(); return fullPath; } JsonWriter::~JsonWriter() { }
f5d30a6fdee2eacd3e67ab4ed28f0b42175de51a
a8b819ee884e173d92fd48e89f625ae6423f522c
/clases/clase23/entradasalida03.cpp
b45fa7295709f5023e87f5dff646aad07e3da71a
[]
no_license
lmvasquezg/Programming-Languages
4c495a18648a004dd44351e3f1e1c8d6e6b1e37c
e8624ad3dadaa8e2d4bada816dd4ace28fda7916
refs/heads/master
2022-04-15T21:16:07.660114
2020-04-09T23:53:05
2020-04-09T23:53:05
192,031,654
0
0
null
null
null
null
UTF-8
C++
false
false
423
cpp
entradasalida03.cpp
/* * fichero: entradasalida03.cpp * * proposito: Mostrar el formato de entrada y salida en C++ * * compile: $ g++ -o entradasalida03 entradasalida03.cpp * $ make entradasalida03 */ #include <iostream> #include <cstdlib> using namespace std; int main(void) { int i; float j; cin >> i >> j; i += 2; // i = i + 2; j += 2.02f; cout << i << endl; cout << j << endl; return EXIT_SUCCESS; }
d3a36e739b401d3fc43a3990b56265aa18bb138a
11e9fdc832e174c35ee9f678890b319526e506c6
/visualpower/FileV30.cpp
5b930237ce11308e15e441812dacd83826691db9
[]
no_license
wangdi190/ChengGong
96a5c9073f8b269cebbdf02e09df2687a40d5cce
ae03dc97c98f5dc7fbdd75a8ba5869f423b83a48
refs/heads/master
2020-05-29T09:16:20.922613
2016-09-28T08:13:13
2016-09-28T08:13:13
69,441,767
4
2
null
null
null
null
GB18030
C++
false
false
73,543
cpp
FileV30.cpp
// FileV30.cpp: implementation of the FileV30 class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FileV30.h" #include "DObj.h" #include "bclass.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// FileV30::FileV30() { } FileV30::~FileV30() { } //将一个多边形转化为一个四个点的矩形 void FileV30::AllPtTo4Pt(DPOINT *in,int ptsum,DPOINT *out) { CDRect drt; drt=CreateNRt(ptsum,in); if(drt.Width()<3) { drt.left-=5; drt.right+=5; }; if(drt.Height()<3) { drt.top-=5; drt.bottom+=5; } out[0].x=drt.left; out[0].y=drt.top; out[1].x=drt.right;out[1].y=drt.top; out[2].x=drt.right;out[2].y=drt.bottom; out[3].x=drt.left; out[3].y=drt.bottom; } //返回版本3保存所需字节数 int FileV30::GetV3Size(DObj &bs,int mode) { int m,n; N_DBX *dbx; N_TEXT *txt; N_PATH *path; N_SRLTEXT *stxt; N_FLOW *flw; N_CONLINE *con; if(mode==0) m=sizeof(N3_BASATTR); else m=0; switch(bs.attr.type) { case 1: //多边形 dbx=(N_DBX*)bs.buf; n=dbx->ptsum; m=m+sizeof(N3_DBX)+n*sizeof(DPOINT); break; case 2: case 3://矩形,园 m=m+sizeof(N3_RECT); break; case 4: //正弦半波形 m=m+sizeof(N3_HSIN); break; case 5: //正弦波形 m=m+sizeof(N3_SIN); break; case 6: //园弧 m=m+sizeof(N3_ARC); break; case 7: //方向箭头 m=m+sizeof(N3_ARROW); break; case 8: //玻璃层 m=m+sizeof(N3_GLASS); break; case 10://文本 txt=(N_TEXT*)bs.buf; n=strlen(txt->text); m=m+sizeof(N3_TEXT)+n; break; case 11://电气端子 m=m+sizeof(N3_ESITE); break; case 12://组合图元母板 m=m+sizeof(N3_EGPMB); break; case 13: //坐标 m=m+sizeof(N3_COORDINATE); break; case 14://表格线 m=m+sizeof(N3_TABLE); break; case 15://静态图形 m=m+sizeof(N3_IMG); break; case 16://路径 path=(N_PATH*)bs.buf; n=path->ptsum; m=m+sizeof(N3_PATH)+n*sizeof(DPOINT); break; case 17://静态小图标 m=m+sizeof(N3_SPIC); break; case 32: m=m+sizeof(N3_METER1); break; case 33: m=m+sizeof(N3_METER2); break; case 34: m=m+sizeof(N3_METER3); break; case 35: m=m+sizeof(N3_METER4); break; case 64://模拟量显示结构 m=m+sizeof(N3_ANL); break; case 66://组合图元显示结构 m=m+sizeof(N3_ELEGRPA); break; case 69://棒图 m=m+sizeof(N3_BAR); break; case 70://饼图结构数据 m=m+sizeof(N3_PIE); break; case 71:case 72://日期格式,时间格式 m=m+sizeof(N3_DATE); break; case 73://动画图形 m=m+sizeof(N3_GIFAML); break; case 74://滚动文本 stxt=(N_SRLTEXT*)bs.buf; n=strlen(stxt->text); m=m+sizeof(N3_SRLTEXT)+n; break; case 75://按钮格式 m=m+sizeof(N3_PUSH); break; case 76://自助控件 m=m+sizeof(N3_SELFCTL); break; case 77://潮流线 flw=(N_FLOW*)bs.buf; n=flw->ptsum; m=m+sizeof(N3_FLOW)+n*sizeof(DPOINT); break; case 78://连接线 con=(N_CONLINE*)bs.buf; n=con->ptsum; m=m+sizeof(N3_CONLINE)+n*sizeof(DPOINT); break; case 79://母线 m=m+sizeof(N3_BUS); break; case 80://小型活动对象 m=m+sizeof(N3_ACTOBJ); break; case 81://FLASH对象 m=m+sizeof(N3_FLASH); break; case 82://百分比饼图 m=m+sizeof(N3_PCTPIE); break; } return m; } //将V2版本的内容转换到基本类中 int FileV30::GetBsFromV2(void *lp1, N_BASATTR &btr, void *lp2) { char *lp; lp=(char*)lp1; N2_BASATTR *ar2; ar2=(N2_BASATTR*)lp1; btr.belong=ar2->belong; btr.ID=ar2->ID; btr.type=ar2->type; lp+=sizeof(N2_BASATTR); btr.size=0; //按每种类型转换 switch(ar2->type) { case 1: //多边形 btr.size=V2DbxToBs(lp,lp2); break; case 2: case 3://矩形,园 btr.size=V2RectToBs(lp,lp2); break; case 4: //正弦半波形 btr.size=V2HsinToBs(lp,lp2); break; case 5: //正弦波形 btr.size=FileV30::V2SinToBs(lp,lp2); break; case 6: //园弧 btr.size=V2ArcToBs(lp,lp2); break; case 7: //方向箭头 btr.size=V2ArrowToBs(lp,lp2); break; case 8: //玻璃层 btr.size=V2GlassToBs(lp,lp2); break; case 10://文本 btr.size=V2TextToBs(lp,lp2); break; case 11://电气端子 btr.size=V2SiteToBs(lp,lp2); break; case 12://组合图元母板 btr.size=V2MBoardToBs(lp,lp2); break; case 13: //坐标 btr.size=V2CoordToBs(lp,lp2); break; case 14://表格线 btr.size=V2TableToBs(lp,lp2); break; case 15://静态图形 btr.size=V2SpicToBs(lp,lp2); break; case 16://路径 btr.size=V2PathToBs(lp,lp2); break; case 17://静态小图标 btr.size=V2PicToBs(lp,lp2); break; case 64://模拟量显示结构 btr.size=V2AnlToBs(lp,lp2); break; case 66://组合图元显示结构 btr.size=V2ElegToBs(lp,lp2); break; case 69://棒图 btr.size=V2BarToBs(lp,lp2); break; case 70://饼图结构数据 btr.size=V2PieToBs(lp,lp2); break; case 71:case 72://日期格式,时间格式 btr.size=V2DateToBs(lp,lp2); break; case 73://动画图形 btr.size=V2GifToBs(lp,lp2); break; case 74://滚动文本 btr.size=V2ScrtxtToBs(lp,lp2); break; case 75://按钮格式 btr.size=V2PushToBs(lp,lp2); break; case 76://自助控件 btr.size=V2SelfToBs(lp,lp2); break; case 77://潮流线 btr.size=V2FlowToBs(lp,lp2); break; case 78://连接线 btr.size=V2ConlToBs(lp,lp2); break; case 79://母线 btr.size=V2BusToBs(lp,lp2); break; case 80://小型活动对象 btr.size=V2ActToBs(lp,lp2); break; case 81://FLASH对象 btr.size=V2FlashToBs(lp,lp2); break; case 82://百分比饼图 btr.size=V2PctToBs(lp,lp2); break; } return sizeof(N2_BASATTR)+ar2->size; //返回已使用字节数 } int FileV30::V2DbxToBs(void *lp, void *lp2) { int s; N2_DBX *d1; N_DBX *d2; d1=(N2_DBX*)lp; d2=(N_DBX*)lp2; d2->close=d1->close; d2->bcolor1=d1->bcolor1; d2->fill=d1->fill; d2->fillmode=d1->fillmode; d2->lcolor=d1->lcolor; d2->ltype=d1->ltype; d2->ptsum=d1->ptsum; memcpy(d2->pt,d1->pt,d1->ptsum*sizeof(DPOINT)); s=sizeof(N_DBX)+d1->ptsum*sizeof(DPOINT); AllPtTo4Pt(d1->pt,d1->ptsum,d2->pta); return s; } int FileV30::V2RectToBs(void *lp, void *lp2) { N2_RECT *r1; N_RECT *r2; r1=(N2_RECT*)lp; r2=(N_RECT*)lp2; r2->bcolor1=r1->bcolor1; r2->fill=r1->fill; r2->fillmode=r1->fillmode; r2->lcolor=r1->lcolor; r2->type=r1->type; memcpy(r2->pt,r1->pt,4*sizeof(DPOINT)); return sizeof(N_RECT); } int FileV30::V2HsinToBs(void *lp, void *lp2) { N2_HSIN *h1; N_HSIN *h2; h1=(N2_HSIN*)lp; h2=(N_HSIN*)lp2; h2->color=h1->color; h2->ltype=h1->ltype; h2->pirodic=h1->pirodic; memcpy(h2->pt,h1->pt,4*sizeof(DPOINT)); return sizeof(N_HSIN); } int FileV30::V2SinToBs(void *lp, void *lp2) { N2_SIN *s1; N_SIN *s2; s1=(N2_SIN*)lp; s2=(N_SIN*)lp2; s2->color=s1->color; s2->ltype=s1->ltype; s2->pirodic=s1->pirodic; s2->startdeg=s1->startdeg; memcpy(s2->pt,s1->pt,4*sizeof(DPOINT)); return sizeof(N_SIN); } int FileV30::V2ArcToBs(void *lp, void *lp2) { N2_ARC *a1; N_ARC *a2; a1=(N2_ARC*)lp; a2=(N_ARC*)lp2; a2->color=a1->color; a2->end=a1->end; a2->start=a1->start; memcpy(a2->pt,a1->pt,4*sizeof(DPOINT)); return sizeof(N_ARC); } int FileV30::V2ArrowToBs(void *lp, void *lp2) { N2_ARROW *a1; N_ARROW *a2; a1=(N2_ARROW*)lp; a2=(N_ARROW*)lp2; a2->color=a1->color; memcpy(a2->pt,a1->pt,2*sizeof(DPOINT)); AllPtTo4Pt(a1->pt,2,a2->pta); return sizeof(N_ARROW); } int FileV30::V2GlassToBs(void *lp, void *lp2) { N2_GLASS *g1; N_GLASS *g2; g1=(N2_GLASS*)lp; g2=(N_GLASS*)lp2; g2->color=g1->color; g2->depth=g1->depth; g2->ocolor=g1->ocolor; g2->outline=g1->outline; memcpy(g2->pt,g1->pt,4*sizeof(DPOINT)); return sizeof(N_GLASS); } int FileV30::V2TextToBs(void *lp, void *lp2) { N2_TEXT *t1; N_TEXT *t2; t1=(N2_TEXT*)lp; t2=(N_TEXT*)lp2; t2->color=t1->color; t2->font=t1->font; t2->style=t1->style; if(t1->zm!=1&&t1->zm!=0){ t2->font.lfHeight=(int)(t1->font.lfHeight/t1->zm); t2->font.lfWidth=(int)(t1->font.lfWidth/t1->zm); } t2->autofill=t1->autofill; strcpy(t2->text,t1->text); memcpy(t2->pt,t1->pt,4*sizeof(DPOINT)); return sizeof(N_TEXT); } int FileV30::V2SiteToBs(void *lp, void *lp2) { N2_ESITE *e1; N_ESITE *e2; e1=(N2_ESITE*)lp; e2=(N_ESITE*)lp2; e2->color=e1->color; e2->solder=e1->solder; memcpy(e2->pt,e1->pt,4*sizeof(DPOINT)); return sizeof(N_ESITE); } int FileV30::V2MBoardToBs(void *lp, void *lp2) { N2_EGPMB *m1; N_EGPMB *m2; m1=(N2_EGPMB*)lp; m2=(N_EGPMB*)lp2; m2->color=m1->color; m2->mode=m1->mode; memcpy(m2->pt,m1->pt,4*sizeof(DPOINT)); return sizeof(N_EGPMB); } int FileV30::V2CoordToBs(void *lp, void *lp2) { N2_COORDINATE *c1; N_COORDINATE *c2; c1=(N2_COORDINATE*)lp; c2=(N_COORDINATE*)lp2; c2->colorc=c1->colorc; c2->colort=c1->colort; c2->colorw=c1->colorw; c2->fontx=c1->fontx; c2->fonty=c1->fonty; c2->wxdraw=c1->wxdraw; c2->wydraw=c1->wydraw; c2->xdot=c1->xdot; c2->xmax=c1->xmax; c2->xmin=c1->xmin; c2->xvshow=c1->xvshow; c2->ydot=c1->ydot; c2->ymax=c1->ymax; c2->ymin=c1->ymin; c2->yvshow=c1->yvshow; if(c1->zm!=1&&c1->zm!=0){ c2->fontx.lfHeight=(int)(c1->fontx.lfHeight/c1->zm); c2->fontx.lfWidth=(int)(c1->fontx.lfWidth/c1->zm); c2->fonty.lfHeight=(int)(c1->fonty.lfHeight/c1->zm); c2->fonty.lfWidth=(int)(c1->fonty.lfWidth/c1->zm); } c2->zm=c1->zm; memcpy(c2->pt,c1->pt,4*sizeof(DPOINT)); return sizeof(N_COORDINATE); } int FileV30::V2TableToBs(void *lp, void *lp2) { N2_TABLE *t1; N_TABLE *t2; t1=(N2_TABLE*)lp; t2=(N_TABLE*)lp2; t2->color=t1->color; t2->dbline=t1->dbline; t2->line=t1->line; t2->width=t1->width; memcpy(t2->pt,t1->pt,4*sizeof(DPOINT)); return sizeof(N_TABLE); } int FileV30::V2SpicToBs(void *lp, void *lp2) { N2_IMG *m1; N_IMG *m2; m1=(N2_IMG*)lp; m2=(N_IMG*)lp2; m2->depth=m1->depth; m2->imgID=m1->imgID; m2->shadow=m1->shadow; m2->zoom=m1->zoom; memcpy(m2->pt,m1->pt,4*sizeof(DPOINT)); return sizeof(N_IMG); } int FileV30::V2PathToBs(void *lp, void *lp2) { N2_PATH *p1; N_PATH *p2; p1=(N2_PATH*)lp; p2=(N_PATH*)lp2; p2->ID=p1->ID; p2->ptsum=p1->ptsum; memcpy(p2->pt,p1->pt,p1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(p1->pt,p1->ptsum,p2->pta); return sizeof(N_PATH)+p1->ptsum*sizeof(DPOINT); } int FileV30::V2PicToBs(void *lp, void *lp2) { N2_SPIC *s1; N_SPIC *s2; s1=(N2_SPIC*)lp; s2=(N_SPIC*)lp2; s2->picID=s1->picID; s2->zoom=s1->zoom; memcpy(s2->pt,s1->pt,4*sizeof(DPOINT)); return sizeof(N_SPIC); } int FileV30::V2AnlToBs(void *lp, void *lp2) { N2_ANL *a1; N_ANL *a2; a1=(N2_ANL*)lp; a2=(N_ANL*)lp2; memset(&a2->vr,0,sizeof(READDEV)); a2->acolor=a1->acolor; a2->direction=a1->direction; strcpy(a2->dev_name,a1->dev_name); a2->vr.did=a1->did; a2->vr.dtype=a1->dtype; a2->lf=a1->lf; if(a1->zm!=1&&a1->zm!=0){ a2->lf.lfHeight=(int)(a1->lf.lfHeight/a1->zm); a2->lf.lfWidth=(int)(a1->lf.lfWidth/a1->zm); } a2->ncolor=a1->ncolor; a2->xs=a1->xs; a2->xsmode=a1->xsmode; memcpy(a2->pt,a1->pt,4*sizeof(DPOINT)); return sizeof(N_ANL); } int FileV30::V2ElegToBs(void *lp, void *lp2) { N2_ELEGRPA *e1; N_ELEGRPA *e2; e1=(N2_ELEGRPA*)lp; e2=(N_ELEGRPA*)lp2; strcpy(e2->dev_name,e1->dev_name); e2->did=e1->did; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->genrev=e1->genrev; e2->runshow=e1->runshow; e2->showno=e1->showno; e2->sitesum=e1->sitesum; e2->subtype=e1->subtype; e2->type=e1->type; memcpy(e2->pt,e1->pt,4*sizeof(DPOINT)); memcpy(e2->site,e1->site,3*sizeof(D_SITE)); return sizeof(N_ELEGRPA); } int FileV30::V2BarToBs(void *lp, void *lp2) { N2_BAR *b1; N_BAR *b2; b1=(N2_BAR*)lp; b2=(N_BAR*)lp2; b2->acolor=b1->acolor; b2->aval=b1->aval; //b2->dsrc=b1->dsrc; strcpy(b2->dsrc.name,b1->dsrc.name); //设备名字 b2->dsrc.did=b1->dsrc.did; //设备ID b2->dsrc.dtype=b1->dsrc.dtype; //设备类型 b2->dsrc.xsmode=b1->dsrc.xsmode; //值索引 b2->max=b1->max; b2->min=b1->min; b2->ncolor=b1->ncolor; b2->outline=b1->outline; b2->style=b1->style; b2->xy=b1->xy; memcpy(b2->pt,b1->pt,4*sizeof(DPOINT)); return sizeof(N_BAR); } int FileV30::V2PieToBs(void *lp, void *lp2) { N2_PIE *p1; N_PIE *p2; p1=(N2_PIE*)lp; p2=(N_PIE*)lp2; memcpy(p2->color,p1->color,32); p2->did=p1->did; p2->fcolor=p1->fcolor; strcpy(p2->name,p1->name); memcpy(p2->pt,p1->pt,4*sizeof(DPOINT)); return sizeof(N_PIE); } int FileV30::V2DateToBs(void *lp, void *lp2) { N2_DATE *d1; N_DATE *d2; d1=(N2_DATE*)lp; d2=(N_DATE*)lp2; d2->bcolor=d1->bcolor; d2->fcolor=d1->fcolor; d2->fmt=d1->fmt; d2->font=d1->font; d2->outcolor=d1->outcolor; d2->shadow=d1->shadow; d2->tran=d1->tran; if(d1->zm!=1&&d1->zm!=0){ d2->font.lfHeight=(int)(d1->font.lfHeight/d1->zm); d2->font.lfWidth=(int)(d1->font.lfWidth/d1->zm); } d2->outline=d1->outline; memcpy(d2->pt,d1->pt,4*sizeof(DPOINT)); return sizeof(N_DATE); } int FileV30::V2GifToBs(void *lp, void *lp2) { N2_GIFAML *g1; N_GIFAML *g2; g1=(N2_GIFAML*)lp; g2=(N_GIFAML*)lp2; //g2->dsrc=g1->dsrc; strcpy(g2->dsrc.name,g1->dsrc.name); //设备名字 g2->dsrc.did=g1->dsrc.did; //设备ID g2->dsrc.dtype=g1->dsrc.dtype; //设备类型 g2->dsrc.xsmode=g1->dsrc.xsmode; //值索引 strcpy(g2->fname,g1->fname); g2->rec=g1->rec; g2->type=g1->type; memcpy(g2->pt,g1->pt,4*sizeof(DPOINT)); return sizeof(N_GIFAML); } int FileV30::V2ScrtxtToBs(void *lp, void *lp2) { N2_SRLTEXT *s1; N_SRLTEXT *s2; s1=(N2_SRLTEXT*)lp; s2=(N_SRLTEXT*)lp2; s2->align=s1->align; s2->depth=s1->depth; s2->direct=s1->direct; s2->fcolor=s1->fcolor; s2->gcolor=s1->gcolor; s2->glass=s1->glass; s2->lf=s1->lf; if(s1->zm!=1&&s1->zm!=0){ s2->lf.lfHeight=(int)(s1->lf.lfHeight/s1->zm); s2->lf.lfWidth=(int)(s1->lf.lfWidth/s1->zm); } s2->outline=s1->outline; s2->tcolor=s1->tcolor; strcpy(s2->text,s1->text); memcpy(s2->pt,s1->pt,4*sizeof(DPOINT)); return sizeof(N_SRLTEXT); } int FileV30::V2PushToBs(void *lp, void *lp2) { N2_PUSH *p1; N_PUSH *p2; p1=(N2_PUSH*)lp; p2=(N_PUSH*)lp2; p2->autlin=p1->autlin; p2->cmdnum=p1->cmdnum; p2->cmdtype=p1->cmdtype; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->command,p1->command); p2->lf=p1->lf; p2->selfid=p1->selfid; p2->shadow=p1->shadow; p2->spicid=p1->spicid; p2->style=p1->style; strcpy(p2->title,p1->title); if(p1->zm!=1&&p1->zm!=0){ p2->lf.lfHeight=(int)(p1->lf.lfHeight/p1->zm); p2->lf.lfWidth=(int)(p1->lf.lfWidth/p1->zm); } memcpy(p2->pt,p1->pt,4*sizeof(DPOINT)); return sizeof(N_PUSH); } int FileV30::V2SelfToBs(void *lp, void *lp2) { N2_SELFCTL *s1; N_SELFCTL *s2; s1=(N2_SELFCTL*)lp; s2=(N_SELFCTL*)lp2; s2->abottom=s1->abottom; s2->aleft=s1->aleft; s2->aright=s1->aright; s2->atop=s1->atop; strcpy(s2->dllname,s1->dllname); s2->id=s1->id; memcpy(s2->lkbuf,s1->lkbuf,255); s2->mode=s1->mode; s2->style=s1->style; memcpy(s2->pt,s1->pt,4*sizeof(DPOINT)); return sizeof(N_SELFCTL); } int FileV30::V2FlowToBs(void *lp, void *lp2) { N2_FLOW *f1; N_FLOW *f2; f1=(N2_FLOW*)lp; f2=(N_FLOW*)lp2; f2->color1=f1->color1; f2->color2=f1->color2; strcpy(f2->dev_name,f1->dev_name); f2->did=f1->did; f2->direct=f1->direct; f2->ptsum=f1->ptsum; f2->fpt=NULL; //低频震荡数据 f2->flen=0; //低频震荡数据长度=0; memcpy(f2->site,f1->site,2*sizeof(D_SITEB)); f2->type=f1->type; f2->vl=f1->vl; f2->linewidth=0; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_FLOW)+f1->ptsum*sizeof(DPOINT); } int FileV30::V2ConlToBs(void *lp, void *lp2) { N2_CONLINE *c1; N_CONLINE *c2; c1=(N2_CONLINE*)lp; c2=(N_CONLINE*)lp2; c2->conobj=c1->conobj; memcpy(c2->lobj,c1->lobj,2*sizeof(LOGOBJ)); c2->ptsum=c1->ptsum; c2->vl=c1->vl; memcpy(c2->pt,c1->pt,c2->ptsum*sizeof(DPOINT)); AllPtTo4Pt(c1->pt,c1->ptsum,c2->pta); return sizeof(N_CONLINE)+c2->ptsum*sizeof(DPOINT); } int FileV30::V2BusToBs(void *lp, void *lp2) { N2_BUS *b1; N_BUS *b2; b1=(N2_BUS*)lp; b2=(N_BUS*)lp2; strcpy(b2->dev_name,b1->dev_name); b2->did=b1->did; b2->eid=dbm->GetEGPRecNo(b1->eid); b2->type=b1->type; b2->vl=b1->vl; memcpy(b2->pt,b1->pt,4*sizeof(DPOINT)); return sizeof(N_BUS); } int FileV30::V2ActToBs(void *lp, void *lp2) { N2_ACTOBJ *a1; N_ACTOBJ *a2; a1=(N2_ACTOBJ*)lp; a2=(N_ACTOBJ*)lp2; //a2->dsrc=a1->dsrc; strcpy(a2->dsrc.name,a1->dsrc.name); //设备名字 a2->dsrc.did=a1->dsrc.did; //设备ID a2->dsrc.dtype=a1->dsrc.dtype; //设备类型 a2->dsrc.xsmode=a1->dsrc.xsmode; //值索引 a2->gid=a1->gid; a2->pathid=a1->pathid; a2->runmode=a1->runmode; a2->skip=a1->skip; a2->speed=a1->speed; memcpy(a2->pt,a1->pt,4*sizeof(DPOINT)); return sizeof(N_ACTOBJ); } int FileV30::V2FlashToBs(void *lp, void *lp2) { N2_FLASH *f1; N_FLASH *f2; f1=(N2_FLASH*)lp; f2=(N_FLASH*)lp2; f2->align_buttom=f1->align_buttom; f2->align_left=f1->align_left; f2->align_right=f1->align_right; f2->align_top=f1->align_top; strcpy(f2->fname,f1->fname); f2->playmode=f1->playmode; memcpy(f2->pt,f1->pt,4*sizeof(DPOINT)); return sizeof(N_FLASH); } int FileV30::V2PctToBs(void *lp, void *lp2) { N2_PCTPIE *p1; N_PCTPIE *p2; p1=(N2_PCTPIE*)lp; p2=(N_PCTPIE*)lp2; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->dev_name,p1->dev_name); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->lf=p1->lf; p2->maxv=p1->maxv; p2->type=p1->type; memcpy(p2->pt,p1->pt,4*sizeof(DPOINT)); return sizeof(N_PCTPIE); } //将V3版本的内容转换到基本类中 int FileV30::GetBsFromV3(void *lp1, N_BASATTR &btr, void *lp2) { char *lp; lp=(char*)lp1; N3_BASATTR *ar2; ar2=(N3_BASATTR*)lp1; btr.belong=ar2->belong; btr.ID=ar2->ID; btr.type=ar2->type; btr.size=0; lp+=sizeof(N3_BASATTR); //按每种类型转换 switch(ar2->type) { case 1: //多边形 btr.size=V3DbxToBs(lp,lp2); break; case 2: case 3://矩形,园 btr.size=V3RectToBs(lp,lp2); break; case 4: //正弦半波形 btr.size=V3HsinToBs(lp,lp2); break; case 5: //正弦波形 btr.size=V3SinToBs(lp,lp2); break; case 6: //园弧 btr.size=V3ArcToBs(lp,lp2); break; case 7: //方向箭头 btr.size=V3ArrowToBs(lp,lp2); break; case 8: //玻璃层 btr.size=V3GlassToBs(lp,lp2); break; case 10://文本 btr.size=V3TextToBs(lp,lp2); break; case 11://电气端子 btr.size=V3SiteToBs(lp,lp2); break; case 12://组合图元母板 btr.size=V3MBoardToBs(lp,lp2); break; case 13: //坐标 btr.size=V3CoordToBs(lp,lp2); break; case 14://表格线 btr.size=V3TableToBs(lp,lp2); break; case 15://静态图形 btr.size=V3SpicToBs(lp,lp2); break; case 16://路径 btr.size=V3PathToBs(lp,lp2); break; case 17://静态小图标 btr.size=V3PicToBs(lp,lp2); break; case 32://仪表1 btr.size=V3Meter1ToBs(lp,lp2); break; case 33: btr.size=V3Meter2ToBs(lp,lp2); break; case 34: btr.size=V3Meter3ToBs(lp,lp2); break; case 35: btr.size=V3Meter4ToBs(lp,lp2); break; case 64://模拟量显示结构 btr.size=V3AnlToBs(lp,lp2); break; case 65://水库 btr.size=V3ReservoirToBs(lp, lp2); break; case 66://组合图元显示结构 btr.size=V3ElegToBs(lp,lp2); break; case 67: btr.size=V3YBToBs(lp,lp2); break; case 69://棒图 btr.size=V3BarToBs(lp,lp2); break; case 70://饼图结构数据 btr.size=V3PieToBs(lp,lp2); break; case 71:case 72://日期格式,时间格式 btr.size=V3DateToBs(lp,lp2); break; case 73://动画图形 btr.size=V3GifToBs(lp,lp2); break; case 74://滚动文本 btr.size=V3ScrtxtToBs(lp,lp2); break; case 75://按钮格式 btr.size=V3PushToBs(lp,lp2); break; case 76://自助控件 btr.size=V3SelfToBs(lp,lp2); break; case 77://潮流线 btr.size=V3FlowToBs(lp,lp2); break; case 78://连接线 btr.size=V3ConlToBs(lp,lp2); break; case 79://母线 btr.size=V3BusToBs(lp,lp2); break; case 80://小型活动对象 btr.size=V3ActToBs(lp,lp2); break; case 81://FLASH对象 btr.size=V3FlashToBs(lp,lp2); break; case 82://百分比饼图 btr.size=V3PctToBs(lp,lp2); break; case 83://区域 btr.size=V3ZoneToBs(lp,lp2); break; case 84://多行 btr.size=V3MttextToBs(lp,lp2); break; } return sizeof(N3_BASATTR)+ar2->size; //返回已使用字节数 } int ss=0; int FileV30::V3DbxToBs(void *lp, void *lp2) { int s; N3_DBX *d1; N_DBX *d2; d1=(N3_DBX*)lp; d2=(N_DBX*)lp2; d2->close=d1->close; d2->bcolor1=d1->bcolor1; d2->fill=d1->fill; d2->fillmode=d1->fillmode; d2->lcolor=d1->lcolor; d2->ltype=d1->ltype; d2->ptsum=d1->ptsum; d2->bgmode=d1->bgmode; memcpy(d2->pt,d1->pt,d1->ptsum*sizeof(DPOINT)); s=sizeof(N_DBX)+d1->ptsum*sizeof(DPOINT); AllPtTo4Pt(d1->pt,d1->ptsum,d2->pta); return s; } int FileV30::V3RectToBs(void *lp, void *lp2) { N3_RECT *r1; N_RECT *r2; r1=(N3_RECT*)lp; r2=(N_RECT*)lp2; r2->bcolor1=r1->bcolor1; r2->fill=r1->fill; r2->fillmode=r1->fillmode; r2->lcolor=r1->lcolor; r2->type=r1->type; GetptFromDRECT(r1->rt,r2->pt); return sizeof(N_RECT); } int FileV30::V3HsinToBs(void *lp, void *lp2) { N3_HSIN *h1; N_HSIN *h2; h1=(N3_HSIN*)lp; h2=(N_HSIN*)lp2; h2->color=h1->color; h2->ltype=h1->hv; h2->pirodic=h1->pirodic; GetptFromDRECT(h1->rt,h2->pt); return sizeof(N_HSIN); } int FileV30::V3SinToBs(void *lp, void *lp2) { N3_SIN *s1; N_SIN *s2; s1=(N3_SIN*)lp; s2=(N_SIN*)lp2; s2->color=s1->color; s2->ltype=s1->hv; s2->pirodic=s1->pirodic; s2->startdeg=s1->startdeg; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SIN); } int FileV30::V3ArcToBs(void *lp, void *lp2) { N3_ARC *a1; N_ARC *a2; a1=(N3_ARC*)lp; a2=(N_ARC*)lp2; a2->color=a1->color; a2->end=a1->end; a2->start=a1->start; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ARC); } int FileV30::V3ArrowToBs(void *lp, void *lp2) { N3_ARROW *a1; N_ARROW *a2; a1=(N3_ARROW*)lp; a2=(N_ARROW*)lp2; a2->color=a1->color; memcpy(a2->pt,a1->pt,2*sizeof(DPOINT)); AllPtTo4Pt(a1->pt,2,a2->pta); return sizeof(N_ARROW); } int FileV30::V3GlassToBs(void *lp, void *lp2) { N3_GLASS *g1; N_GLASS *g2; g1=(N3_GLASS*)lp; g2=(N_GLASS*)lp2; g2->color=g1->color; g2->depth=g1->depth; g2->ocolor=g1->lcolor; g2->outline=g1->outline; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GLASS); } int FileV30::V3TextToBs(void *lp, void *lp2) { N3_TEXT *t1; N_TEXT *t2; t1=(N3_TEXT*)lp; t2=(N_TEXT*)lp2; t2->color=t1->color; t2->font=t1->font; t2->style=t1->style; t2->autofill=t1->autofit; if(t1->zm!=1&&t1->zm!=0){ t2->font.lfHeight=(int)(t1->font.lfHeight); t2->font.lfWidth=(int)(t1->font.lfWidth); } t2->zm=1; strcpy(t2->text,t1->text); GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TEXT); } int FileV30::V3SiteToBs(void *lp, void *lp2) { N3_ESITE *e1; N_ESITE *e2; e1=(N3_ESITE*)lp; e2=(N_ESITE*)lp2; e2->color=e1->color; e2->solder=e1->solder; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ESITE); } int FileV30::V3MBoardToBs(void *lp, void *lp2) { N3_EGPMB *m1; N_EGPMB *m2; m1=(N3_EGPMB*)lp; m2=(N_EGPMB*)lp2; m2->color=m1->color; m2->mode=m1->mode; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_EGPMB); } int FileV30::V3CoordToBs(void *lp, void *lp2) { N3_COORDINATE *c1; N_COORDINATE *c2; c1=(N3_COORDINATE*)lp; c2=(N_COORDINATE*)lp2; c2->colorc=c1->colorc; c2->colort=c1->colort; c2->colorw=c1->colorw; c2->fontx=c1->fontx; c2->fonty=c1->fonty; c2->wxdraw=c1->wxdraw; c2->wydraw=c1->wydraw; c2->xdot=c1->xdot; c2->xmax=c1->xmax; c2->xmin=c1->xmin; c2->xvshow=c1->xvshow; c2->ydot=c1->ydot; c2->ymax=c1->ymax; c2->ymin=c1->ymin; c2->yvshow=c1->yvshow; if(c1->zm!=1&&c1->zm!=0){ c2->fontx.lfHeight=(int)(c1->fontx.lfHeight/c1->zm); c2->fontx.lfWidth=(int)(c1->fontx.lfWidth/c1->zm); c2->fonty.lfHeight=(int)(c1->fonty.lfHeight/c1->zm); c2->fonty.lfWidth=(int)(c1->fonty.lfWidth/c1->zm); } c2->zm=c1->zm; GetptFromDRECT(c1->rt,c2->pt); return sizeof(N_COORDINATE); } int FileV30::V3TableToBs(void *lp, void *lp2) { N3_TABLE *t1; N_TABLE *t2; t1=(N3_TABLE*)lp; t2=(N_TABLE*)lp2; t2->color=t1->color; t2->dbline=t1->dbline; t2->line=t1->line; t2->width=t1->width; GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TABLE); } int FileV30::V3SpicToBs(void *lp, void *lp2) { N3_IMG *m1; N_IMG *m2; m1=(N3_IMG*)lp; m2=(N_IMG*)lp2; m2->depth=m1->depth; m2->imgID=m1->imgID; m2->shadow=m1->shadow; m2->zoom=m1->zoom; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_IMG); } int FileV30::V3PathToBs(void *lp, void *lp2) { N3_PATH *p1; N_PATH *p2; p1=(N3_PATH*)lp; p2=(N_PATH*)lp2; p2->ID=p1->ID; p2->ptsum=p1->ptsum; memcpy(p2->pt,p1->pt,p1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(p1->pt,p1->ptsum,p2->pta); return sizeof(N_PATH)+p1->ptsum*sizeof(DPOINT); } int FileV30::V3PicToBs(void *lp, void *lp2) { N3_SPIC *s1; N_SPIC *s2; s1=(N3_SPIC*)lp; s2=(N_SPIC*)lp2; s2->picID=s1->picID; s2->zoom=s1->zoom; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SPIC); } int FileV30::V3AnlToBs(void *lp, void *lp2) { N3_ANL *a1; N_ANL *a2; a1=(N3_ANL*)lp; a2=(N_ANL*)lp2; memset(&a2->vr,0,sizeof(READDEV)); a2->acolor=a1->acolor; a2->direction=a1->angle==0 ? 0:1; strcpy(a2->dev_name,a1->dev_name); a2->vr.did=a1->did; a2->vr.dtype=a1->dtype; a2->lf=a1->lf; if(a1->zm!=1&&a1->zm!=0){ a2->lf.lfWidth=(int)(a2->lf.lfWidth/a1->zm); a2->lf.lfHeight=(int)(a2->lf.lfHeight/a1->zm); } a2->ncolor=a1->ncolor; a2->xs=a1->xs; a2->xsmode=a1->xsmode; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ANL); } int FileV30::V3ReservoirToBs(void *lp, void *lp2) { int i,size; N3_RESERVOIR *a1; N_RESERVOIR *a2; a1=(N3_RESERVOIR*)lp; a2=(N_RESERVOIR *)lp2; a2->color=a1->color; strcpy(a2->dev_name,a1->dev_name); a2->did=a1->did; a2->hcolor=a1->hcolor; a2->lcolor=a1->lcolor; a2->ncolor=a1->ncolor; a2->ptsum=a1->ptsum; size=sizeof(N_RESERVOIR)+a2->ptsum*sizeof(DPOINT); for(i=0;i<a2->ptsum;i++) a2->pt[i]=a1->pt[i]; AllPtTo4Pt(a1->pt,a1->ptsum,a2->pta); memset(&a2->vr,0,sizeof(READDEV)); return size; } int FileV30::V3ElegToBs(void *lp, void *lp2) { N3_ELEGRPA *e1; N_ELEGRPA *e2; e1=(N3_ELEGRPA*)lp; e2=(N_ELEGRPA*)lp2; memset(&e2->vr,0,sizeof(READDEV)); e2->vr.did=e1->did; strcpy(e2->dev_name,e1->dev_name); e2->did=e1->did; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->genrev=e1->genrev; e2->runshow=e1->runshow; e2->showno=e1->showno; e2->sitesum=e1->sitesum; e2->type=e1->type; e2->subtype=e1->subtype; GetptFromDRECT(e1->rt,e2->pt); memcpy(e2->site,e1->site,3*sizeof(D_SITE)); return sizeof(N_ELEGRPA); } int FileV30::V3YBToBs(void *lp, void *lp2) { int i,j; N3_ELEGRPYB *e1; N_ELEGRPYB *e2; e1=(N3_ELEGRPYB*)lp; e2=(N_ELEGRPYB*)lp2; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->dbsum=e1->dbsum; for(i=0;i<8;i++){ e2->curval[i]=0; e2->newval[i]=0; //e2->dbs[i]=e1->dbs[i]; //e2->umr[i]=e1->umr[i]; strcpy(e2->dbs[i].name,e1->dbs[i].name); e2->dbs[i].did=e1->dbs[i].did; e2->dbs[i].dtype=e1->dbs[i].dtype; e2->dbs[i].xsmode=e1->dbs[i].xsmode; e2->umr[i].ptype=e1->umr[i].ptype; e2->umr[i].vmin=e1->umr[i].vmin; e2->umr[i].vmax=e1->umr[i].vmax; e2->umr[i].alarm=e1->umr[i].alarm; for(j=0;j<4;j++) e2->umr[i].val[j]=e1->umr[i].val[j]; for(j=0;j<2;j++) e2->umr[i].color[j]=e1->umr[i].color[j]; } e2->show=1; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ELEGRPYB); } int FileV30::V3BarToBs(void *lp, void *lp2) { N3_BAR *b1; N_BAR *b2; b1=(N3_BAR*)lp; b2=(N_BAR*)lp2; b2->acolor=b1->acolor; b2->aval=b1->aval; //b2->dsrc=b1->dsrc; strcpy(b2->dsrc.name,b1->dsrc.name); b2->dsrc.did=b1->dsrc.did; b2->dsrc.dtype=b1->dsrc.dtype; b2->dsrc.xsmode=b1->dsrc.xsmode; b2->max=b1->max; b2->min=b1->min; b2->ncolor=b1->ncolor; b2->outline=b1->outline; b2->style=b1->style; b2->xy=b1->xy; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BAR); } int FileV30::V3PieToBs(void *lp, void *lp2) { N3_PIE *p1; N_PIE *p2; p1=(N3_PIE*)lp; p2=(N_PIE*)lp2; memcpy(p2->color,p1->color,32); p2->did=p1->did; p2->fcolor=p1->fcolor; strcpy(p2->name,p1->name); GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PIE); } int FileV30::V3DateToBs(void *lp, void *lp2) { N3_DATE *d1; N_DATE *d2; d1=(N3_DATE*)lp; d2=(N_DATE*)lp2; d2->bcolor=d1->bcolor; d2->fcolor=d1->fcolor; d2->fmt=d1->fmt; d2->font=d1->font; d2->outcolor=d1->outcolor; d2->shadow=d1->shadow; d2->tran=d1->tran; if(d1->zm!=1&&d1->zm!=0){ d2->font.lfHeight=(int)(d1->font.lfHeight/d1->zm); d2->font.lfWidth=(int)(d1->font.lfWidth/d1->zm); } d2->outline=d1->outline; GetptFromDRECT(d1->rt,d2->pt); return sizeof(N_DATE); } int FileV30::V3GifToBs(void *lp, void *lp2) { N3_GIFAML *g1; N_GIFAML *g2; g1=(N3_GIFAML*)lp; g2=(N_GIFAML*)lp2; //g2->dsrc=g1->dsrc; strcpy(g2->dsrc.name,g1->dsrc.name); g2->dsrc.did=g1->dsrc.did; g2->dsrc.dtype=g1->dsrc.dtype; g2->dsrc.xsmode=g1->dsrc.xsmode; strcpy(g2->fname,g1->fname); g2->rec=g1->rec; g2->type=g1->type; g2->zt=0; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GIFAML); } int FileV30::V3ScrtxtToBs(void *lp, void *lp2) { N3_SRLTEXT *s1; N_SRLTEXT *s2; s1=(N3_SRLTEXT*)lp; s2=(N_SRLTEXT*)lp2; s2->align=s1->align; s2->depth=s1->depth; s2->direct=s1->direct; s2->fcolor=s1->fcolor; s2->gcolor=s1->gcolor; s2->glass=s1->glass; s2->lf=s1->lf; s2->outline=s1->outline; s2->tcolor=s1->tcolor; if(s1->zm!=1&&s1->zm!=0){ s2->lf.lfHeight=(int)(s1->lf.lfHeight/s1->zm); s2->lf.lfWidth=(int)(s1->lf.lfWidth/s1->zm); } strcpy(s2->text,s1->text); GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SRLTEXT); } int FileV30::V3PushToBs(void *lp, void *lp2) { N3_PUSH *p1; N_PUSH *p2; p1=(N3_PUSH*)lp; p2=(N_PUSH*)lp2; p2->autlin=p1->autlin; p2->cmdnum=p1->cmdnum; p2->cmdtype=p1->cmdtype; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->command,p1->command); p2->lf=p1->lf; p2->selfid=p1->selfid; p2->shadow=p1->shadow; p2->spicid=p1->spicid; p2->style=p1->style; strcpy(p2->title,p1->title); if(p1->zm!=1&&p1->zm!=0){ p2->lf.lfHeight=(int)(p1->lf.lfHeight/p1->zm); p2->lf.lfWidth=(int)(p1->lf.lfWidth/p1->zm); } p2->tosta=p1->tosta; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PUSH); } int FileV30::V3SelfToBs(void *lp, void *lp2) { N3_SELFCTL *s1; N_SELFCTL *s2; s1=(N3_SELFCTL*)lp; s2=(N_SELFCTL*)lp2; s2->abottom=s1->abottom; s2->aleft=s1->aleft; s2->aright=s1->aright; s2->atop=s1->atop; strcpy(s2->dllname,s1->dllname); s2->id=s1->id; memcpy(s2->lkbuf,s1->lkbuf,255); s2->mode=s1->mode; s2->style=s1->style; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SELFCTL); } int FileV30::V3FlowToBs(void *lp, void *lp2) { N3_FLOW *f1; N_FLOW *f2; f1=(N3_FLOW*)lp; f2=(N_FLOW*)lp2; memset(&f2->vr,0,sizeof(READDEV)); f2->color1=f1->color1; f2->color2=f1->color2; f2->fpt=NULL; //低频震荡数据 f2->flen=0; //低频震荡数据长度=0; strcpy(f2->dev_name,f1->dev_name); f2->did=f1->did; f2->direct=f1->direct; f2->ptsum=f1->ptsum; memcpy(f2->site,f1->site,2*sizeof(D_SITEB)); f2->type=f1->type; f2->vl=f1->vl; f2->linewidth=f1->linewidth>4 ? 0:f1->linewidth; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_FLOW)+f1->ptsum*sizeof(DPOINT); } int FileV30::V3ConlToBs(void *lp, void *lp2) { N3_CONLINE *c1; N_CONLINE *c2; c1=(N3_CONLINE*)lp; c2=(N_CONLINE*)lp2; c2->conobj=c1->conobj; memcpy(c2->lobj,c1->lobj,2*sizeof(LOGOBJ)); c2->ptsum=c1->ptsum; c2->vl=c1->vl; memcpy(c2->pt,c1->pt,c2->ptsum*sizeof(DPOINT)); AllPtTo4Pt(c1->pt,c1->ptsum,c2->pta); return sizeof(N_CONLINE)+c2->ptsum*sizeof(DPOINT); } int FileV30::V3BusToBs(void *lp, void *lp2) { N3_BUS *b1; N_BUS *b2; b1=(N3_BUS*)lp; b2=(N_BUS*)lp2; memset(&b2->vr,0,sizeof(READDEV)); strcpy(b2->dev_name,b1->dev_name); b2->did=b1->did; b2->eid=dbm->GetEGPRecNo(b1->eid); b2->type=b1->type; b2->vl=b1->vl; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BUS); } int FileV30::V3ActToBs(void *lp, void *lp2) { N3_ACTOBJ *a1; N_ACTOBJ *a2; a1=(N3_ACTOBJ*)lp; a2=(N_ACTOBJ*)lp2; //a2->dsrc=a1->dsrc; strcpy(a2->dsrc.name,a1->dsrc.name); a2->dsrc.did=a1->dsrc.did; a2->dsrc.dtype=a1->dsrc.dtype; a2->dsrc.xsmode=a1->dsrc.xsmode; a2->gid=a1->gid; a2->pathid=a1->pathid; a2->runmode=a1->runmode; a2->skip=a1->skip; a2->speed=a1->speed; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ACTOBJ); } int FileV30::V3FlashToBs(void *lp, void *lp2) { N3_FLASH *f1; N_FLASH *f2; f1=(N3_FLASH*)lp; f2=(N_FLASH*)lp2; f2->align_buttom=f1->align_buttom; f2->align_left=f1->align_left; f2->align_right=f1->align_right; f2->align_top=f1->align_top; strcpy(f2->fname,f1->fname); f2->playmode=f1->playmode; GetptFromDRECT(f1->rt,f2->pt); return sizeof(N_FLASH); } int FileV30::V3PctToBs(void *lp, void *lp2) { N3_PCTPIE *p1; N_PCTPIE *p2; p1=(N3_PCTPIE*)lp; p2=(N_PCTPIE*)lp2; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->dev_name,p1->dev_name); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->lf=p1->lf; p2->maxv=p1->maxv; p2->type=p1->type; if(p1->zm!=1&&p1->zm!=0){ p2->lf.lfHeight=(int)(p1->lf.lfHeight/p1->zm); p2->lf.lfWidth=(int)(p1->lf.lfWidth/p1->zm); } GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PCTPIE); } int FileV30::V3Meter1ToBs(void *lp, void *lp2) { int i; N3_METER1 *m1; N_METER1 *m2; m1=(N3_METER1*)lp; m2=(N_METER1*)lp2; for(i=0;i<2;i++) m2->pt[i]=m1->pt[i]; m2->font=m1->font; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showarc=m1->showarc; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->slen=m1->slen; m2->angle=m1->angle; m2->pstyle=m1->pstyle; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; m2->axw=m1->axw; m2->pw=m1->pw; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; m2->curval=0; m2->zm=1; m2->stype=m1->stype; m2->lstype=m1->lstype; return sizeof(N_METER1); } int FileV30::V3Meter2ToBs(void *lp, void *lp2) { int i; N3_METER2 *m1; N_METER2 *m2; m1=(N3_METER2*)lp; m2=(N_METER2*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); m2->curval=0; return sizeof(N_METER2); } int FileV30::V3Meter3ToBs(void *lp, void *lp2) { int i; N3_METER3 *m1; N_METER3 *m2; m1=(N3_METER3*)lp; m2=(N_METER3*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); m2->curval=0; return sizeof(N_METER3); } int FileV30::V3Meter4ToBs(void *lp, void *lp2) { int i; N3_METER4 *m1; N_METER4 *m2; m1=(N3_METER4*)lp; m2=(N_METER4*)lp2; m2->num=m1->num; m2->numdot=m1->numdot; m2->bcr=m1->bcr; for(i=0;i<2;i++) m2->ncr[i]=m1->ncr[i]; GetptFromDRECT(m1->rt,m2->pt); m2->curval=(float)0; return sizeof(N_METER3); } int FileV30::V3ZoneToBs(void *lp, void *lp2) { N3_ZONE *f1; N_ZONE *f2; f1=(N3_ZONE*)lp; f2=(N_ZONE*)lp2; f2->lcolor=f1->lcolor; f2->dyval=0; strcpy(f2->zone_name,f1->zone_name); f2->lf=f1->lf; f2->fcolor=f1->fcolor; f2->did=f1->did; f2->ptsum=f1->ptsum; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_ZONE)+f1->ptsum*sizeof(DPOINT); } int FileV30::V3MttextToBs(void *lp, void *lp2) { N3_MTTEXT *f1; N_MTTEXT *f2; f1=(N3_MTTEXT*)lp; f2=(N_MTTEXT*)lp2; f2->fcolor=f1->fcolor; strcpy(f2->name,f1->name); f2->lf=f1->lf; f2->did=f1->did; f2->type=f1->type; strcpy(f2->text,f1->text); GetptFromDRECT(f1->rt,f2->pt); return sizeof(N_MTTEXT); } ////////////////////////////////////////////////////////////////////// void FileV30::GetptFromDRECT(DRECT&rt,DPOINT *pt) { pt[0].x=rt.left; pt[0].y=rt.top; pt[1].x=rt.right;pt[1].y=rt.top; pt[2].x=rt.right;pt[2].y=rt.bottom; pt[3].x=rt.left;pt[3].y=rt.bottom; } //将V4版本的内容转换到基本类中 int FileV30::GetBsFromV4(void *lp1, N_BASATTR &btr, void *lp2) { char *lp; lp=(char*)lp1; N4_BASATTR *ar2; ar2=(N4_BASATTR*)lp1; btr.belong=ar2->belong; btr.ID=ar2->ID; btr.type=ar2->type; btr.size=0; lp+=sizeof(N4_BASATTR); //按每种类型转换 switch(ar2->type) { case 1: //多边形 btr.size=V4DbxToBs(lp,lp2); break; case 2: case 3://矩形,园 btr.size=V4RectToBs(lp,lp2); break; case 4: //正弦半波形 btr.size=V4HsinToBs(lp,lp2); break; case 5: //正弦波形 btr.size=V4SinToBs(lp,lp2); break; case 6: //园弧 btr.size=V4ArcToBs(lp,lp2); break; case 7: //方向箭头 btr.size=V4ArrowToBs(lp,lp2); break; case 8: //玻璃层 btr.size=V4GlassToBs(lp,lp2); break; case 10://文本 btr.size=V4TextToBs(lp,lp2); break; case 11://电气端子 btr.size=V4SiteToBs(lp,lp2); break; case 12://组合图元母板 btr.size=V4MBoardToBs(lp,lp2); break; case 13: //坐标 btr.size=V4CoordToBs(lp,lp2); break; case 14://表格线 btr.size=V4TableToBs(lp,lp2); break; case 15://静态图形 btr.size=V4SpicToBs(lp,lp2); break; case 16://路径 btr.size=V4PathToBs(lp,lp2); break; case 17://静态小图标 btr.size=V4PicToBs(lp,lp2); break; case 32://仪表1 btr.size=V4Meter1ToBs(lp,lp2); break; case 33://仪表2 btr.size=V4Meter2ToBs(lp,lp2); break; case 34://仪表3 btr.size=V4Meter3ToBs(lp,lp2); break; case 35://仪表4 btr.size=V4Meter4ToBs(lp,lp2); break; case 64://模拟量显示结构 btr.size=V4AnlToBs(lp,lp2); break; case 65://水库 btr.size=V4ReservoirToBs(lp, lp2); break; case 66://组合图元显示结构 btr.size=V4ElegToBs(lp,lp2); break; case 67: btr.size=V4YBToBs(lp,lp2); break; case 68: btr.size=V4SysPieToBs(lp,lp2); break; case 69://棒图 btr.size=V4BarToBs(lp,lp2); break; case 70://饼图结构数据 btr.size=V4PieToBs(lp,lp2); break; case 71:case 72://日期格式,时间格式 btr.size=V4DateToBs(lp,lp2); break; case 73://动画图形 btr.size=V4GifToBs(lp,lp2); break; case 74://滚动文本 btr.size=V4ScrtxtToBs(lp,lp2); break; case 75://按钮格式 btr.size=V4PushToBs(lp,lp2); break; case 76://自助控件 btr.size=V4SelfToBs(lp,lp2); break; case 77://潮流线 btr.size=V4FlowToBs(lp,lp2); break; case 78://连接线 btr.size=V4ConlToBs(lp,lp2); break; case 79://母线 btr.size=V4BusToBs(lp,lp2); break; case 80://小型活动对象 btr.size=V4ActToBs(lp,lp2); break; case 81://FLASH对象 btr.size=V4FlashToBs(lp,lp2); break; case 83://区域 btr.size=V4ZoneToBs(lp,lp2); break; case 84: btr.size=V4WtrToBs(lp,lp2); btr.type=85; //天气 break; } return sizeof(N4_BASATTR)+ar2->size; //返回已使用字节数 } int FileV30::V4DbxToBs(void *lp, void *lp2) { int s; N4_DBX *d1; N_DBX *d2; d1=(N4_DBX*)lp; d2=(N_DBX*)lp2; d2->bcolor1=d1->bcolor1; d2->fill=d1->fill; d2->fillmode=d1->fillmode; d2->lcolor=d1->lcolor; d2->ltype=d1->ltype; d2->ptsum=d1->ptsum; d2->bgmode=d1->bgmode; if(d1->fill==1) d2->close=1; else d2->close=0; memcpy(d2->pt,d1->pt,d1->ptsum*sizeof(DPOINT)); s=sizeof(N_DBX)+d1->ptsum*sizeof(DPOINT); AllPtTo4Pt(d1->pt,d1->ptsum,d2->pta); return s; } int FileV30::V4RectToBs(void *lp, void *lp2) { N4_RECT *r1; N_RECT *r2; r1=(N4_RECT*)lp; r2=(N_RECT*)lp2; r2->bcolor1=r1->bcolor1; r2->fill=r1->fill; r2->fillmode=r1->fillmode; r2->lcolor=r1->lcolor; r2->type=r1->type; GetptFromDRECT(r1->rt,r2->pt); return sizeof(N_RECT); } int FileV30::V4HsinToBs(void *lp, void *lp2) { N4_HSIN *h1; N_HSIN *h2; h1=(N4_HSIN*)lp; h2=(N_HSIN*)lp2; h2->color=h1->color; h2->ltype=h1->hv; h2->pirodic=h1->pirodic; GetptFromDRECT(h1->rt,h2->pt); return sizeof(N_HSIN); } int FileV30::V4SinToBs(void *lp, void *lp2) { N4_SIN *s1; N_SIN *s2; s1=(N4_SIN*)lp; s2=(N_SIN*)lp2; s2->color=s1->color; s2->ltype=s1->hv; s2->pirodic=s1->pirodic; s2->startdeg=s1->startdeg; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SIN); } int FileV30::V4ArcToBs(void *lp, void *lp2) { N4_ARC *a1; N_ARC *a2; a1=(N4_ARC*)lp; a2=(N_ARC*)lp2; a2->color=a1->color; a2->end=a1->end; a2->start=a1->start; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ARC); } int FileV30::V4ArrowToBs(void *lp, void *lp2) { N4_ARROW *a1; N_ARROW *a2; a1=(N4_ARROW*)lp; a2=(N_ARROW*)lp2; a2->color=a1->color; memcpy(a2->pt,a1->pt,2*sizeof(DPOINT)); AllPtTo4Pt(a1->pt,2,a2->pta); return sizeof(N_ARROW); } int FileV30::V4GlassToBs(void *lp, void *lp2) { N4_GLASS *g1; N_GLASS *g2; g1=(N4_GLASS*)lp; g2=(N_GLASS*)lp2; g2->color=g1->color; g2->depth=g1->depth; g2->ocolor=g1->lcolor; g2->outline=g1->outline; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GLASS); } int FileV30::V4TextToBs(void *lp, void *lp2) { N4_TEXT *t1; N_TEXT *t2; t1=(N4_TEXT*)lp; t2=(N_TEXT*)lp2; t2->color=t1->color; t2->font=t1->font; t2->style=t1->style; t2->autofill=t1->autofit; if(t1->zm!=1&&t1->zm!=0){ t2->font.lfHeight=(int)(t1->font.lfHeight/t1->zm); t2->font.lfWidth=(int)(t1->font.lfWidth/t1->zm); } t2->zm=1; strcpy(t2->text,t1->text); GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TEXT); } int FileV30::V4SiteToBs(void *lp, void *lp2) { N4_ESITE *e1; N_ESITE *e2; e1=(N4_ESITE*)lp; e2=(N_ESITE*)lp2; e2->color=e1->color; e2->solder=e1->solder; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ESITE); } int FileV30::V4MBoardToBs(void *lp, void *lp2) { N4_EGPMB *m1; N_EGPMB *m2; m1=(N4_EGPMB*)lp; m2=(N_EGPMB*)lp2; m2->color=m1->color; m2->mode=m1->mode; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_EGPMB); } int FileV30::V4CoordToBs(void *lp, void *lp2) { N4_COORDINATE *c1; N_COORDINATE *c2; c1=(N4_COORDINATE*)lp; c2=(N_COORDINATE*)lp2; c2->colorc=c1->colorc; c2->colort=c1->colort; c2->colorw=c1->colorw; c2->fontx=c1->fontx; c2->fonty=c1->fonty; c2->wxdraw=c1->wxdraw; c2->wydraw=c1->wydraw; c2->xdot=c1->xdot; c2->xmax=c1->xmax; c2->xmin=c1->xmin; c2->xvshow=c1->xvshow; c2->ydot=c1->ydot; c2->ymax=c1->ymax; c2->ymin=c1->ymin; c2->yvshow=c1->yvshow; if(c1->zm!=1&&c1->zm!=0){ c2->fontx.lfHeight=(int)(c1->fontx.lfHeight/c1->zm); c2->fontx.lfWidth=(int)(c1->fontx.lfWidth/c1->zm); c2->fonty.lfHeight=(int)(c1->fonty.lfHeight/c1->zm); c2->fonty.lfWidth=(int)(c1->fonty.lfWidth/c1->zm); } c2->zm=1; GetptFromDRECT(c1->rt,c2->pt); return sizeof(N_COORDINATE); } int FileV30::V4TableToBs(void *lp, void *lp2) { N4_TABLE *t1; N_TABLE *t2; t1=(N4_TABLE*)lp; t2=(N_TABLE*)lp2; t2->color=t1->color; t2->dbline=t1->dbline; t2->line=t1->line; t2->width=t1->width; GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TABLE); } int FileV30::V4SpicToBs(void *lp, void *lp2) { N4_IMG *m1; N_IMG *m2; m1=(N4_IMG*)lp; m2=(N_IMG*)lp2; m2->depth=m1->depth; m2->imgID=m1->imgID; m2->shadow=m1->shadow; m2->zoom=m1->zoom; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_IMG); } int FileV30::V4PathToBs(void *lp, void *lp2) { N4_PATH *p1; N_PATH *p2; p1=(N4_PATH*)lp; p2=(N_PATH*)lp2; p2->ID=p1->ID; p2->ptsum=p1->ptsum; memcpy(p2->pt,p1->pt,p1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(p1->pt,p1->ptsum,p2->pta); return sizeof(N_PATH)+p1->ptsum*sizeof(DPOINT); } int FileV30::V4PicToBs(void *lp, void *lp2) { N4_SPIC *s1; N_SPIC *s2; s1=(N4_SPIC*)lp; s2=(N_SPIC*)lp2; s2->picID=s1->picID; s2->zoom=s1->zoom; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SPIC); } int FileV30::V4Meter1ToBs(void *lp, void *lp2) { int i; N4_METER1 *m1; N_METER1 *m2; m1=(N4_METER1*)lp; m2=(N_METER1*)lp2; for(i=0;i<2;i++) m2->pt[i]=m1->pt[i]; m2->font=m1->font; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showarc=m1->showarc; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->slen=m1->slen; m2->angle=m1->angle; m2->pstyle=m1->pstyle; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; m2->axw=m1->axw; m2->pw=m1->pw; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; m2->zm=1; return sizeof(N_METER1); } int FileV30::V4Meter2ToBs(void *lp, void *lp2) { int i; N4_METER2 *m1; N_METER2 *m2; m1=(N4_METER2*)lp; m2=(N_METER2*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER2); } int FileV30::V4Meter3ToBs(void *lp, void *lp2) { int i; N4_METER3 *m1; N_METER3 *m2; m1=(N4_METER3*)lp; m2=(N_METER3*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER3); } int FileV30::V4Meter4ToBs(void *lp, void *lp2) { int i; N4_METER4 *m1; N_METER4 *m2; m1=(N4_METER4*)lp; m2=(N_METER4*)lp2; m2->num=m1->num; m2->numdot=m1->numdot; m2->bcr=m1->bcr; for(i=0;i<2;i++) m2->ncr[i]=m1->ncr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER3); } int FileV30::V4SelfToBs(void *lp, void *lp2) { N4_SELFCTL *s1; N_SELFCTL *s2; s1=(N4_SELFCTL*)lp; s2=(N_SELFCTL*)lp2; s2->abottom=s1->abottom; s2->aleft=s1->aleft; s2->aright=s1->aright; s2->atop=s1->atop; strcpy(s2->dllname,s1->dllname); s2->id=s1->id; memcpy(s2->lkbuf,s1->lkbuf,255); s2->mode=s1->mode; s2->style=s1->style; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SELFCTL); } int FileV30::V4PieToBs(void *lp, void *lp2) { /*N4_PIE *p1; N_PIE *p2; p1=(N4_PIE*)lp; p2=(N_PIE*)lp2; p2->angle=p1->angle; memcpy(p2->color,p1->color,32); p2->did=p1->did; p2->fcolor=p1->fcolor; strcpy(p2->name,p1->name); p2->outline=p1->outline; memcpy(p2->pd,p1->pd,8*sizeof(NPIEDAT)); p2->shad=p1->shad; p2->style=p1->style; p2->sum=p1->sum; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PIE);*/ N4_PIE *p1; N_PIE *p2; p1=(N4_PIE*)lp; p2=(N_PIE*)lp2; p2->lf=p1->lf; // p2->angle=p1->angle; memcpy(p2->color,p1->color,12); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->type=p1->type; strcpy(p2->name,p1->name); GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PIE); } int FileV30::V4SysPieToBs(void *lp, void *lp2) { N4_SYSPIE *p1; N_SYSPIE *p2; p1=(N4_SYSPIE*)lp; p2=(N_SYSPIE*)lp2; p2->lf=p1->lf; p2->ID=p1->ID; memcpy(p2->color,p1->color,24); p2->fcolor=p1->fcolor; p2->type=p1->type; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_SYSPIE); } int FileV30::V4DateToBs(void *lp, void *lp2) { N4_DATE *d1; N_DATE *d2; d1=(N4_DATE*)lp; d2=(N_DATE*)lp2; d2->bcolor=d1->bcolor; d2->fcolor=d1->fcolor; d2->fmt=d1->fmt; d2->font=d1->font; d2->outcolor=d1->outcolor; d2->shadow=d1->shadow; d2->tran=d1->tran; if(d1->zm!=1&&d1->zm!=0){ d2->font.lfHeight=(int)(d1->font.lfHeight/d1->zm); d2->font.lfWidth=(int)(d1->font.lfWidth/d1->zm); } d2->outline=d1->outline; GetptFromDRECT(d1->rt,d2->pt); return sizeof(N_DATE); } int FileV30::V4ScrtxtToBs(void *lp, void *lp2) { N4_SRLTEXT *s1; N_SRLTEXT *s2; s1=(N4_SRLTEXT*)lp; s2=(N_SRLTEXT*)lp2; s2->align=s1->align; s2->depth=s1->depth; s2->direct=s1->direct; s2->fcolor=s1->fcolor; s2->gcolor=s1->gcolor; s2->glass=s1->glass; s2->lf=s1->lf; s2->outline=s1->outline; s2->tcolor=s1->tcolor; if(s1->zm!=1&&s1->zm!=0){ s2->lf.lfHeight=(int)(s1->lf.lfHeight/s1->zm); s2->lf.lfWidth=(int)(s1->lf.lfWidth/s1->zm); } strcpy(s2->text,s1->text); GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SRLTEXT); } int FileV30::V4BarToBs(void *lp, void *lp2) { N4_BAR *b1; N_BAR *b2; b1=(N4_BAR*)lp; b2=(N_BAR*)lp2; b2->acolor=b1->acolor; b2->aval=b1->aval; b2->dsrc.did=b1->dsrc.did; b2->dsrc.dtype=b1->dsrc.dtype; b2->dsrc.xsmode=b1->dsrc.xsmode; strcpy(b2->dsrc.name,b1->dsrc.name); b2->max=b1->max; b2->min=b1->min; b2->ncolor=b1->ncolor; b2->outline=b1->outline; b2->style=b1->style; b2->xy=b1->xy; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BAR); } int FileV30::V4WtrToBs(void *lp, void *lp2) { N4_WEATHER *p1; N_WEATHER *p2; p1=(N4_WEATHER*)lp; p2=(N_WEATHER*)lp2; strcpy(p2->name,p1->name); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->lf=p1->lf; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_WEATHER); } int FileV30::V4ZoneToBs(void *lp, void *lp2) { N4_ZONE *f1; N_ZONE *f2; f1=(N4_ZONE*)lp; f2=(N_ZONE*)lp2; f2->lcolor=f1->lcolor; f2->dyval=0; strcpy(f2->zone_name,f1->zone_name); f2->lf=f1->lf; f2->fcolor=f1->fcolor; f2->did=f1->did; f2->ptsum=f1->ptsum; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_ZONE)+f1->ptsum*sizeof(DPOINT); } int FileV30::V4ActToBs(void *lp, void *lp2) { N4_ACTOBJ *a1; N_ACTOBJ *a2; a1=(N4_ACTOBJ*)lp; a2=(N_ACTOBJ*)lp2; a2->dsrc.did=a1->dsrc.did; a2->dsrc.dtype=a1->dsrc.dtype; a2->dsrc.xsmode=a1->dsrc.xsmode; strcpy(a2->dsrc.name,a1->dsrc.name); a2->gid=a1->gid; a2->pathid=a1->pathid; a2->runmode=a1->runmode; a2->skip=a1->skip; a2->speed=a1->speed; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ACTOBJ); } int FileV30::V4BusToBs(void *lp, void *lp2) { N4_BUS *b1; N_BUS *b2; b1=(N4_BUS*)lp; b2=(N_BUS*)lp2; memset(&b2->vr,0,sizeof(READDEV)); strcpy(b2->dev_name,b1->dev_name); b2->did=b1->did; b2->eid=dbm->GetEGPRecNo(b1->eid); b2->type=b1->type; b2->vl=b1->vl; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BUS); } int FileV30::V4FlowToBs(void *lp, void *lp2) { N4_FLOW *f1; N_FLOW *f2; f1=(N4_FLOW*)lp; f2=(N_FLOW*)lp2; memset(&f2->vr,0,sizeof(READDEV)); f2->color1=f1->color1; f2->color2=f1->color2; f2->fpt=NULL; //低频震荡数据 f2->flen=0; //低频震荡数据长度=0; strcpy(f2->dev_name,f1->dev_name); f2->did=f1->did; f2->direct=f1->direct; f2->ptsum=f1->ptsum; memcpy(f2->site,f1->site,2*sizeof(D_SITEB)); f2->type=f1->type; f2->vl=f1->vl; f2->linewidth=0;//f1->linewidth>4 ? 0:f1->linewidth; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_FLOW)+f1->ptsum*sizeof(DPOINT); } int FileV30::V4PushToBs(void *lp, void *lp2) { N4_PUSH *p1; N_PUSH *p2; p1=(N4_PUSH*)lp; p2=(N_PUSH*)lp2; p2->autlin=p1->autlin; p2->cmdnum=p1->cmdnum; p2->cmdtype=p1->cmdtype; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->command,p1->command); p2->lf=p1->lf; p2->selfid=p1->selfid; p2->shadow=p1->shadow; p2->spicid=p1->spicid; p2->style=p1->style; p2->tosta=p1->tosta; strcpy(p2->title,p1->title); if(p1->zm!=1&&p1->zm!=0){ p2->lf.lfHeight=(int)(p1->lf.lfHeight/p1->zm); p2->lf.lfWidth=(int)(p1->lf.lfWidth/p1->zm); } GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PUSH); } int FileV30::V4GifToBs(void *lp, void *lp2) { N4_GIFAML *g1; N_GIFAML *g2; g1=(N4_GIFAML*)lp; g2=(N_GIFAML*)lp2; strcpy(g2->dsrc.name,g1->dsrc.name); g2->dsrc.did=g1->dsrc.did; g2->dsrc.dtype=g1->dsrc.dtype; g2->dsrc.xsmode=g1->dsrc.xsmode; strcpy(g2->fname,g1->fname); g2->rec=g1->rec; g2->type=g1->type; g2->zt=0; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GIFAML); } int FileV30::V4YBToBs(void *lp, void *lp2) { int i,j; N4_ELEGRPYB *e1; N_ELEGRPYB *e2; e1=(N4_ELEGRPYB*)lp; e2=(N_ELEGRPYB*)lp2; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->dbsum=e1->dbsum; for(i=0;i<8;i++){ e2->curval[i]=0; e2->newval[i]=0; strcpy(e2->dbs[i].name,e1->dbs[i].name); e2->dbs[i].did=e1->dbs[i].did; e2->dbs[i].dtype=e1->dbs[i].dtype; e2->dbs[i].xsmode=e1->dbs[i].xsmode; e2->umr[i].ptype=e1->umr[i].ptype; e2->umr[i].vmin=e1->umr[i].vmin; e2->umr[i].vmax=e1->umr[i].vmax; e2->umr[i].alarm=e1->umr[i].alarm; for(j=0;j<4;j++) e2->umr[i].val[j]=e1->umr[i].val[j]; for(j=0;j<2;j++) e2->umr[i].color[j]=e1->umr[i].color[j]; } e2->show=1; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ELEGRPYB); } int FileV30::V4AnlToBs(void *lp, void *lp2) { N4_ANL *a1; N_ANL *a2; a1=(N4_ANL*)lp; a2=(N_ANL*)lp2; memset(&a2->vr,0,sizeof(READDEV)); a2->acolor=a1->acolor; a2->direction=a1->angle==0 ? 0:1; strcpy(a2->dev_name,a1->dev_name); a2->vr.did=a1->did; a2->vr.dtype=a1->dtype; a2->vr.xsmode=(unsigned)a1->xsmode; a2->lf=a1->lf; if(a1->zm!=1&&a1->zm!=0){ a2->lf.lfWidth=(int)(a2->lf.lfWidth/a1->zm); a2->lf.lfHeight=(int)(a2->lf.lfHeight/a1->zm); } a2->ncolor=a1->ncolor; a2->xs=a1->xs; a2->xsmode=a1->xsmode; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ANL); } int FileV30::V4ReservoirToBs(void *lp, void *lp2) { int i,size; N4_RESERVOIR *a1; N_RESERVOIR *a2; a1=(N4_RESERVOIR*)lp; a2=(N_RESERVOIR *)lp2; a2->color=a1->color; strcpy(a2->dev_name,a1->dev_name); a2->did=a1->did; a2->hcolor=a1->hcolor; a2->lcolor=a1->lcolor; a2->ncolor=a1->ncolor; a2->ptsum=a1->ptsum; size=sizeof(N_RESERVOIR)+a2->ptsum*sizeof(DPOINT); for(i=0;i<a2->ptsum;i++) a2->pt[i]=a1->pt[i]; AllPtTo4Pt(a1->pt,a1->ptsum,a2->pta); memset(&a2->vr,0,sizeof(READDEV)); return size; } int FileV30::V4ElegToBs(void *lp, void *lp2) { N4_ELEGRPA *e1; N_ELEGRPA *e2; e1=(N4_ELEGRPA*)lp; e2=(N_ELEGRPA*)lp2; memset(&e2->vr,0,sizeof(READDEV)); e2->vr.did=e1->did; strcpy(e2->dev_name,e1->dev_name); e2->did=e1->did; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->genrev=e1->genrev; e2->runshow=e1->runshow; e2->showno=e1->showno; e2->sitesum=e1->sitesum; e2->type=e1->type; e2->subtype=e1->subtype; GetptFromDRECT(e1->rt,e2->pt); memcpy(e2->site,e1->site,3*sizeof(D_SITE)); return sizeof(N_ELEGRPA); } int FileV30::V4ConlToBs(void *lp, void *lp2) { N4_CONLINE *c1; N_CONLINE *c2; c1=(N4_CONLINE*)lp; c2=(N_CONLINE*)lp2; c2->conobj=c1->conobj; memcpy(c2->lobj,c1->lobj,2*sizeof(LOGOBJ)); c2->ptsum=c1->ptsum; c2->vl=c1->vl; memcpy(c2->pt,c1->pt,c2->ptsum*sizeof(DPOINT)); AllPtTo4Pt(c1->pt,c1->ptsum,c2->pta); return sizeof(N_CONLINE)+c2->ptsum*sizeof(DPOINT); } int FileV30::V4FlashToBs(void *lp, void *lp2) { N4_FLASH *f1; N_FLASH *f2; f1=(N4_FLASH*)lp; f2=(N_FLASH*)lp2; f2->align_buttom=f1->align_buttom; f2->align_left=f1->align_left; f2->align_right=f1->align_right; f2->align_top=f1->align_top; strcpy(f2->fname,f1->fname); f2->playmode=f1->playmode; GetptFromDRECT(f1->rt,f2->pt); return sizeof(N_FLASH); } //将V5版本的内容转换到基本类中 int FileV30::GetBsFromV5(void *lp1, N_BASATTR &btr, void *lp2) { char *lp; lp=(char*)lp1; N5_BASATTR *ar2; ar2=(N5_BASATTR*)lp1; btr.belong=ar2->belong; btr.ID=ar2->ID; btr.type=ar2->type; btr.size=0; lp+=sizeof(N5_BASATTR); //按每种类型转换 switch(ar2->type) { case 1: //多边形 btr.size=V5DbxToBs(lp,lp2); break; case 2: case 3://矩形,园 btr.size=V5RectToBs(lp,lp2); break; case 4: //正弦半波形 btr.size=V5HsinToBs(lp,lp2); break; case 5: //正弦波形 btr.size=V5SinToBs(lp,lp2); break; case 6: //园弧 btr.size=V5ArcToBs(lp,lp2); break; case 7: //方向箭头 btr.size=V5ArrowToBs(lp,lp2); break; case 8: //玻璃层 btr.size=V5GlassToBs(lp,lp2); break; case 10://文本 btr.size=V5TextToBs(lp,lp2); break; case 11://电气端子 btr.size=V5SiteToBs(lp,lp2); break; case 12://组合图元母板 btr.size=V5MBoardToBs(lp,lp2); break; case 13: //坐标 btr.size=V5CoordToBs(lp,lp2); break; case 14://表格线 btr.size=V5TableToBs(lp,lp2); break; case 15://静态图形 btr.size=V5SpicToBs(lp,lp2); break; case 16://路径 btr.size=V5PathToBs(lp,lp2); break; case 17://静态小图标 btr.size=V5PicToBs(lp,lp2); break; case 32://仪表1 btr.size=V5Meter1ToBs(lp,lp2); break; case 33://仪表2 btr.size=V5Meter2ToBs(lp,lp2); break; case 34://仪表3 btr.size=V5Meter3ToBs(lp,lp2); break; case 35://仪表4 btr.size=V5Meter4ToBs(lp,lp2); break; case 64://模拟量显示结构 btr.size=V5AnlToBs(lp,lp2); break; case 65://水库 btr.size=V5ReservoirToBs(lp, lp2); break; case 66://组合图元显示结构 btr.size=V5ElegToBs(lp,lp2); break; case 67: btr.size=V5YBToBs(lp,lp2); break; case 68: btr.size=V5SysPieToBs(lp,lp2); break; case 69://棒图 btr.size=V5BarToBs(lp,lp2); break; case 70://饼图结构数据 btr.size=V5PieToBs(lp,lp2); break; case 71:case 72://日期格式,时间格式 btr.size=V5DateToBs(lp,lp2); break; case 73://动画图形 btr.size=V5GifToBs(lp,lp2); break; case 74://滚动文本 btr.size=V5ScrtxtToBs(lp,lp2); break; case 75://按钮格式 btr.size=V5PushToBs(lp,lp2); break; case 76://自助控件 btr.size=V5SelfToBs(lp,lp2); break; case 77://潮流线 btr.size=V5FlowToBs(lp,lp2); break; case 78://连接线 btr.size=V5ConlToBs(lp,lp2); break; case 79://母线 btr.size=V5BusToBs(lp,lp2); break; case 80://小型活动对象 btr.size=V5ActToBs(lp,lp2); break; case 81://FLASH对象 btr.size=V5FlashToBs(lp,lp2); break; case 82://百分比饼图 btr.size=V5PctToBs(lp,lp2); break; case 83://区域 btr.size=V5ZoneToBs(lp,lp2); break; case 84://多行 btr.size=V5MttextToBs(lp,lp2); break; } return sizeof(N5_BASATTR)+ar2->size; //返回已使用字节数 } int FileV30::V5DbxToBs(void *lp, void *lp2) { int s; N5_DBX *d1; N_DBX *d2; d1=(N5_DBX*)lp; d2=(N_DBX*)lp2; d2->close=d1->close; d2->bcolor1=d1->bcolor1; d2->fill=d1->fill; d2->fillmode=d1->fillmode; d2->lcolor=d1->lcolor; d2->ltype=d1->ltype; d2->ptsum=d1->ptsum; d2->bgmode=d1->bgmode; memcpy(d2->pt,d1->pt,d1->ptsum*sizeof(DPOINT)); s=sizeof(N_DBX)+d1->ptsum*sizeof(DPOINT); AllPtTo4Pt(d1->pt,d1->ptsum,d2->pta); return s; } int FileV30::V5RectToBs(void *lp, void *lp2) { N5_RECT *r1; N_RECT *r2; r1=(N5_RECT*)lp; r2=(N_RECT*)lp2; r2->bcolor1=r1->bcolor1; r2->fill=r1->fill; r2->fillmode=r1->fillmode; r2->lcolor=r1->lcolor; r2->type=r1->type; GetptFromDRECT(r1->rt,r2->pt); return sizeof(N_RECT); } int FileV30::V5HsinToBs(void *lp, void *lp2) { N5_HSIN *h1; N_HSIN *h2; h1=(N5_HSIN*)lp; h2=(N_HSIN*)lp2; h2->color=h1->color; h2->ltype=h1->hv; h2->pirodic=h1->pirodic; GetptFromDRECT(h1->rt,h2->pt); return sizeof(N_HSIN); } int FileV30::V5SinToBs(void *lp, void *lp2) { N5_SIN *s1; N_SIN *s2; s1=(N5_SIN*)lp; s2=(N_SIN*)lp2; s2->color=s1->color; s2->ltype=s1->hv; s2->pirodic=s1->pirodic; s2->startdeg=s1->startdeg; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SIN); } int FileV30::V5ArcToBs(void *lp, void *lp2) { N5_ARC *a1; N_ARC *a2; a1=(N5_ARC*)lp; a2=(N_ARC*)lp2; a2->color=a1->color; a2->end=a1->end; a2->start=a1->start; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ARC); } int FileV30::V5ArrowToBs(void *lp, void *lp2) { N5_ARROW *a1; N_ARROW *a2; a1=(N5_ARROW*)lp; a2=(N_ARROW*)lp2; a2->color=a1->color; memcpy(a2->pt,a1->pt,2*sizeof(DPOINT)); AllPtTo4Pt(a1->pt,2,a2->pta); return sizeof(N_ARROW); } int FileV30::V5GlassToBs(void *lp, void *lp2) { N5_GLASS *g1; N_GLASS *g2; g1=(N5_GLASS*)lp; g2=(N_GLASS*)lp2; g2->color=g1->color; g2->depth=g1->depth; g2->ocolor=g1->lcolor; g2->outline=g1->outline; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GLASS); } int FileV30::V5TextToBs(void *lp, void *lp2) { N5_TEXT *t1; N_TEXT *t2; t1=(N5_TEXT*)lp; t2=(N_TEXT*)lp2; t2->color=t1->color; t2->font=t1->font; t2->style=t1->style; t2->autofill=t1->autofit; if(t1->zm!=1&&t1->zm!=0) { t2->font.lfHeight=(int)(t1->font.lfHeight/t1->zm); t2->font.lfWidth=(int)(t1->font.lfWidth/t1->zm); } t2->zm=1; strcpy(t2->text,t1->text); GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TEXT); } int FileV30::V5SiteToBs(void *lp, void *lp2) { N5_ESITE *e1; N_ESITE *e2; e1=(N5_ESITE*)lp; e2=(N_ESITE*)lp2; e2->color=e1->color; e2->solder=e1->solder; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ESITE); } int FileV30::V5MBoardToBs(void *lp, void *lp2) { N5_EGPMB *m1; N_EGPMB *m2; m1=(N5_EGPMB*)lp; m2=(N_EGPMB*)lp2; m2->color=m1->color; m2->mode=m1->mode; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_EGPMB); } int FileV30::V5CoordToBs(void *lp, void *lp2) { N5_COORDINATE *c1; N_COORDINATE *c2; c1=(N5_COORDINATE*)lp; c2=(N_COORDINATE*)lp2; c2->colorc=c1->colorc; c2->colort=c1->colort; c2->colorw=c1->colorw; c2->fontx=c1->fontx; c2->fonty=c1->fonty; c2->wxdraw=c1->wxdraw; c2->wydraw=c1->wydraw; c2->xdot=c1->xdot; c2->xmax=c1->xmax; c2->xmin=c1->xmin; c2->xvshow=c1->xvshow; c2->ydot=c1->ydot; c2->ymax=c1->ymax; c2->ymin=c1->ymin; c2->yvshow=c1->yvshow; c2->fontx=c1->fontx; c2->fonty=c1->fonty; c2->zm=1; GetptFromDRECT(c1->rt,c2->pt); return sizeof(N_COORDINATE); } int FileV30::V5TableToBs(void *lp, void *lp2) { N5_TABLE *t1; N_TABLE *t2; t1=(N5_TABLE*)lp; t2=(N_TABLE*)lp2; t2->color=t1->color; t2->dbline=t1->dbline; t2->line=t1->line; t2->width=t1->width; GetptFromDRECT(t1->rt,t2->pt); return sizeof(N_TABLE); } int FileV30::V5SpicToBs(void *lp, void *lp2) { N5_IMG *m1; N_IMG *m2; m1=(N5_IMG*)lp; m2=(N_IMG*)lp2; m2->depth=m1->depth; m2->imgID=m1->imgID; m2->shadow=m1->shadow; m2->zoom=m1->zoom; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_IMG); } int FileV30::V5PathToBs(void *lp, void *lp2) { N5_PATH *p1; N_PATH *p2; p1=(N5_PATH*)lp; p2=(N_PATH*)lp2; p2->ID=p1->ID; p2->ptsum=p1->ptsum; memcpy(p2->pt,p1->pt,p1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(p1->pt,p1->ptsum,p2->pta); return sizeof(N_PATH)+p1->ptsum*sizeof(DPOINT); } int FileV30::V5PicToBs(void *lp, void *lp2) { N5_SPIC *s1; N_SPIC *s2; s1=(N5_SPIC*)lp; s2=(N_SPIC*)lp2; s2->picID=s1->picID; s2->zoom=s1->zoom; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SPIC); } int FileV30::V5Meter1ToBs(void *lp, void *lp2) { int i; N5_METER1 *m1; N_METER1 *m2; m1=(N5_METER1*)lp; m2=(N_METER1*)lp2; for(i=0;i<2;i++) m2->pt[i]=m1->pt[i]; m2->font=m1->font; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showarc=m1->showarc; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->slen=m1->slen; m2->angle=m1->angle; m2->pstyle=m1->pstyle; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; m2->axw=m1->axw; m2->pw=m1->pw; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; m2->zm=1; m2->stype=m1->stype; m2->lstype=m1->lstype; return sizeof(N_METER1); } int FileV30::V5Meter2ToBs(void *lp, void *lp2) { int i; N5_METER2 *m1; N_METER2 *m2; m1=(N5_METER2*)lp; m2=(N_METER2*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER2); } int FileV30::V5Meter3ToBs(void *lp, void *lp2) { int i; N5_METER3 *m1; N_METER3 *m2; m1=(N5_METER3*)lp; m2=(N_METER3*)lp2; m2->Vmin=m1->Vmin; m2->Vmax=m1->Vmax; m2->showbl=m1->showbl; m2->shownum=m1->shownum; m2->numdot=m1->numdot; m2->rev=m1->rev; m2->scale=m1->scale; m2->scales=m1->scales; m2->pcr=m1->pcr; m2->scr=m1->scr; m2->alarm=m1->alarm; for(i=0;i<4;i++) m2->val[i]=m1->val[i]; for(i=0;i<2;i++) m2->cr[i]=m1->cr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER3); } int FileV30::V5Meter4ToBs(void *lp, void *lp2) { int i; N5_METER4 *m1; N_METER4 *m2; m1=(N5_METER4*)lp; m2=(N_METER4*)lp2; m2->num=m1->num; m2->numdot=m1->numdot; m2->bcr=m1->bcr; for(i=0;i<2;i++) m2->ncr[i]=m1->ncr[i]; GetptFromDRECT(m1->rt,m2->pt); return sizeof(N_METER3); } int FileV30::V5AnlToBs(void *lp, void *lp2) { N5_ANL *a1; N_ANL *a2; a1=(N5_ANL*)lp; a2=(N_ANL*)lp2; a2->acolor=a1->acolor; a2->direction=a1->angle==0 ? 0:1; strcpy(a2->dev_name,a1->dev_name); a2->vr.did=a1->did; a2->vr.dtype=a1->dtype; a2->vr.xsmode=(unsigned)a1->xsmode; a2->lf=a1->lf; a2->ncolor=a1->ncolor; // a2->style=a1->style; a2->xs=a1->xs; a2->xsmode=a1->xsmode; a2->lf=a1->lf; // a2->zm=1; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ANL); } int FileV30::V5ReservoirToBs(void *lp, void *lp2) { int i,size; N5_RESERVOIR *a1; N_RESERVOIR *a2; a1=(N5_RESERVOIR*)lp; a2=(N_RESERVOIR *)lp2; a2->color=a1->color; strcpy(a2->dev_name,a1->dev_name); a2->did=a1->did; a2->hcolor=a1->hcolor; a2->lcolor=a1->lcolor; a2->ncolor=a1->ncolor; a2->ptsum=a1->ptsum; size=sizeof(N_RESERVOIR)+a2->ptsum*sizeof(DPOINT); for(i=0;i<a2->ptsum;i++) a2->pt[i]=a1->pt[i]; AllPtTo4Pt(a1->pt,a1->ptsum,a2->pta); memset(&a2->vr,0,sizeof(READDEV)); return size; } int FileV30::V5ElegToBs(void *lp, void *lp2) { N5_ELEGRPA *e1; N_ELEGRPA *e2; e1=(N5_ELEGRPA*)lp; e2=(N_ELEGRPA*)lp2; memset(&e2->vr,0,sizeof(READDEV)); strcpy(e2->dev_name,e1->dev_name); e2->did=e1->did; e2->egrpid=e1->egrpid; e2->genrev=e1->genrev; e2->runshow=e1->runshow; e2->showno=e1->showno; e2->sitesum=e1->sitesum; e2->type=e1->type; e2->subtype=e1->subtype; GetptFromDRECT(e1->rt,e2->pt); memcpy(e2->site,e1->site,3*sizeof(D_SITE)); return sizeof(N_ELEGRPA); } int FileV30::V5YBToBs(void *lp, void *lp2) { int i,j; N5_ELEGRPYB *e1; N_ELEGRPYB *e2; e1=(N5_ELEGRPYB*)lp; e2=(N_ELEGRPYB*)lp2; e2->egrpid=dbm->GetEGPRecNo(e1->egrpid); e2->dbsum=e1->dbsum; for(i=0;i<8;i++){ //e2->dbs[i]=e1->dbs[i]; //e2->pam[i]=e1->pam[i]; strcpy(e2->dbs[i].name,e1->dbs[i].name); e2->dbs[i].did=e1->dbs[i].did; e2->dbs[i].dtype=e1->dbs[i].dtype; e2->dbs[i].xsmode=e1->dbs[i].xsmode; e2->umr[i].ptype=e1->pam[i].ptype; e2->umr[i].vmin=e1->pam[i].vmin; e2->umr[i].vmax=e1->pam[i].vmax; e2->umr[i].alarm=e1->pam[i].alarm; for(j=0;j<4;j++) e2->umr[i].val[j]=e1->pam[i].val[j]; for(j=0;j<2;j++) e2->umr[i].color[j]=e1->pam[i].color[j]; } e2->show=1; GetptFromDRECT(e1->rt,e2->pt); return sizeof(N_ELEGRPYB); } int FileV30::V5BarToBs(void *lp, void *lp2) { N5_BAR *b1; N_BAR *b2; b1=(N5_BAR*)lp; b2=(N_BAR*)lp2; b2->acolor=b1->acolor; b2->aval=b1->aval; //b2->dsrc=b1->dsrc; strcpy(b2->dsrc.name,b1->dsrc.name); b2->dsrc.did=b1->dsrc.did; b2->dsrc.dtype=b1->dsrc.dtype; b2->dsrc.xsmode=b1->dsrc.xsmode; b2->max=b1->max; b2->min=b1->min; b2->ncolor=b1->ncolor; b2->outline=b1->outline; b2->style=b1->style; b2->xy=b1->xy; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BAR); } int FileV30::V5PieToBs(void *lp, void *lp2) { N5_PIE *p1; N_PIE *p2; p1=(N5_PIE*)lp; p2=(N_PIE*)lp2; p2->lf=p1->lf; memcpy(p2->color,p1->color,12); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->type=p1->type; strcpy(p2->name,p1->name); GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PIE); } int FileV30::V5SysPieToBs(void *lp, void *lp2) { N5_SYSPIE *p1; N_SYSPIE *p2; p1=(N5_SYSPIE*)lp; p2=(N_SYSPIE*)lp2; p2->lf=p1->lf; p2->ID=p1->ID; memcpy(p2->color,p1->color,24); p2->fcolor=p1->fcolor; p2->type=p1->type; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_SYSPIE); } int FileV30::V5DateToBs(void *lp, void *lp2) { N5_DATE *d1; N_DATE *d2; d1=(N5_DATE*)lp; d2=(N_DATE*)lp2; d2->bcolor=d1->bcolor; d2->fcolor=d1->fcolor; d2->fmt=d1->fmt; d2->font=d1->font; d2->outcolor=d1->outcolor; d2->shadow=d1->shadow; d2->tran=d1->tran; if(d1->zm!=1&&d1->zm!=0){ d2->font.lfHeight=(int)(d1->font.lfHeight/d1->zm); d2->font.lfWidth=(int)(d1->font.lfWidth/d1->zm); } // d2->zm=1; d2->outline=d1->outline; GetptFromDRECT(d1->rt,d2->pt); return sizeof(N_DATE); } int FileV30::V5GifToBs(void *lp, void *lp2) { N5_GIFAML *g1; N_GIFAML *g2; g1=(N5_GIFAML*)lp; g2=(N_GIFAML*)lp2; //g2->dsrc=g1->dsrc; strcpy(g2->dsrc.name,g1->dsrc.name); g2->dsrc.did=g1->dsrc.did; g2->dsrc.dtype=g1->dsrc.dtype; g2->dsrc.xsmode=g1->dsrc.xsmode; strcpy(g2->fname,g1->fname); g2->rec=g1->rec; g2->zt=0; GetptFromDRECT(g1->rt,g2->pt); return sizeof(N_GIFAML); } int FileV30::V5ScrtxtToBs(void *lp, void *lp2) { N5_SRLTEXT *s1; N_SRLTEXT *s2; s1=(N5_SRLTEXT*)lp; s2=(N_SRLTEXT*)lp2; s2->align=s1->align; s2->depth=s1->depth; s2->direct=s1->direct; s2->fcolor=s1->fcolor; s2->gcolor=s1->gcolor; s2->glass=s1->glass; s2->lf=s1->lf; s2->outline=s1->outline; s2->tcolor=s1->tcolor; if(s1->zm!=1&&s1->zm!=0){ s2->lf.lfHeight=(int)(s1->lf.lfHeight/s1->zm); s2->lf.lfWidth=(int)(s1->lf.lfWidth/s1->zm); } // s2->zm=1; strcpy(s2->text,s1->text); GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SRLTEXT); } int FileV30::V5PushToBs(void *lp, void *lp2) { N5_PUSH *p1; N_PUSH *p2; p1=(N5_PUSH*)lp; p2=(N_PUSH*)lp2; p2->autlin=p1->autlin; p2->cmdnum=p1->cmdnum; p2->cmdtype=p1->cmdtype; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->command,p1->command); p2->lf=p1->lf; p2->selfid=p1->selfid; p2->shadow=p1->shadow; p2->spicid=p1->spicid; p2->style=p1->style; strcpy(p2->title,p1->title); if(p1->zm!=1&&p1->zm!=0){ p2->lf.lfHeight=(int)(p1->lf.lfHeight/p1->zm); p2->lf.lfWidth=(int)(p1->lf.lfWidth/p1->zm); } // p2->zm=1; p2->tosta=p1->tosta; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PUSH); } int FileV30::V5SelfToBs(void *lp, void *lp2) { N5_SELFCTL *s1; N_SELFCTL *s2; s1=(N5_SELFCTL*)lp; s2=(N_SELFCTL*)lp2; s2->abottom=s1->abottom; s2->aleft=s1->aleft; s2->aright=s1->aright; s2->atop=s1->atop; strcpy(s2->dllname,s1->dllname); s2->id=s1->id; memcpy(s2->lkbuf,s1->lkbuf,255); s2->mode=s1->mode; s2->style=s1->style; GetptFromDRECT(s1->rt,s2->pt); return sizeof(N_SELFCTL); } int FileV30::V5FlowToBs(void *lp, void *lp2) { N5_FLOW *f1; N_FLOW *f2; f1=(N5_FLOW*)lp; f2=(N_FLOW*)lp2; memset(&f2->vr,0,sizeof(READDEV)); f2->color1=f1->color1; f2->color2=f1->color2; f2->fpt=NULL; //低频震荡数据 f2->flen=0; //低频震荡数据长度=0; strcpy(f2->dev_name,f1->dev_name); f2->did=f1->did; f2->direct=f1->direct; f2->ptsum=f1->ptsum; memcpy(f2->site,f1->site,2*sizeof(D_SITEB)); f2->type=f1->type; f2->vl=f1->vl; f2->linewidth=f1->linewidth>4 ? 0:f1->linewidth; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_FLOW)+f1->ptsum*sizeof(DPOINT); } int FileV30::V5ZoneToBs(void *lp, void *lp2) { N5_ZONE *f1; N_ZONE *f2; f1=(N5_ZONE*)lp; f2=(N_ZONE*)lp2; f2->lcolor=f1->lcolor; f2->dyval=0; strcpy(f2->zone_name,f1->zone_name); f2->lf=f1->lf; f2->fcolor=f1->fcolor; f2->did=f1->did; f2->ptsum=f1->ptsum; memcpy(f2->pt,f1->pt,f1->ptsum*sizeof(DPOINT)); AllPtTo4Pt(f1->pt,f1->ptsum,f2->pta); return sizeof(N_ZONE)+f1->ptsum*sizeof(DPOINT); } int FileV30::V5MttextToBs(void *lp, void *lp2) { N5_MTTEXT *f1; N_MTTEXT *f2; f1=(N5_MTTEXT*)lp; f2=(N_MTTEXT*)lp2; f2->fcolor=f1->fcolor; strcpy(f2->name,f1->name); f2->lf=f1->lf; f2->did=f1->did; f2->type=f1->type; strcpy(f2->text,f1->text); GetptFromDRECT(f1->rt,f2->pt); return sizeof(N_MTTEXT); } int FileV30::V5ConlToBs(void *lp, void *lp2) { N5_CONLINE *c1; N_CONLINE *c2; c1=(N5_CONLINE*)lp; c2=(N_CONLINE*)lp2; c2->conobj=c1->conobj; memcpy(c2->lobj,c1->lobj,2*sizeof(LOGOBJ)); c2->ptsum=c1->ptsum; c2->vl=c1->vl; memcpy(c2->pt,c1->pt,c2->ptsum*sizeof(DPOINT)); AllPtTo4Pt(c1->pt,c1->ptsum,c2->pta); return sizeof(N_CONLINE)+c2->ptsum*sizeof(DPOINT); } int FileV30::V5BusToBs(void *lp, void *lp2) { /*N5_BUS *b1; N_BUS *b2; b1=(N5_BUS*)lp; b2=(N_BUS*)lp2; memset(&b2->vr,0,sizeof(READDEV)); strcpy(b2->dev_name,b1->dev_name); b2->did=b1->did; b2->eid=b1->eid; b2->type=b1->type; b2->vl=b1->vl; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BUS);*/ N5_BUS *b1; N_BUS *b2; b1=(N5_BUS*)lp; b2=(N_BUS*)lp2; memset(&b2->vr,0,sizeof(READDEV)); strcpy(b2->dev_name,b1->dev_name); b2->did=b1->did; b2->eid=dbm->GetEGPRecNo(b1->eid); b2->type=b1->type; b2->vl=b1->vl; GetptFromDRECT(b1->rt,b2->pt); return sizeof(N_BUS); } int FileV30::V5ActToBs(void *lp, void *lp2) { N5_ACTOBJ *a1; N_ACTOBJ *a2; a1=(N5_ACTOBJ*)lp; a2=(N_ACTOBJ*)lp2; strcpy(a2->dsrc.name,a1->dsrc.name); a2->dsrc.did=a1->dsrc.did; a2->dsrc.dtype=a1->dsrc.dtype; a2->dsrc.xsmode=a1->dsrc.xsmode; a2->gid=a1->gid; a2->pathid=a1->pathid; a2->runmode=a1->runmode; a2->skip=a1->skip; a2->speed=a1->speed; GetptFromDRECT(a1->rt,a2->pt); return sizeof(N_ACTOBJ); } int FileV30::V5FlashToBs(void *lp, void *lp2) { N5_FLASH *f1; N_FLASH *f2; f1=(N5_FLASH*)lp; f2=(N_FLASH*)lp2; f2->align_buttom=f1->align_buttom; f2->align_left=f1->align_left; f2->align_right=f1->align_right; f2->align_top=f1->align_top; strcpy(f2->fname,f1->fname); f2->playmode=f1->playmode; GetptFromDRECT(f1->rt,f2->pt); return sizeof(N_FLASH); } int FileV30::V5PctToBs(void *lp, void *lp2) { N5_PCTPIE *p1; N_PCTPIE *p2; p1=(N5_PCTPIE*)lp; p2=(N_PCTPIE*)lp2; p2->color1=p1->color1; p2->color2=p1->color2; strcpy(p2->dev_name,p1->dev_name); p2->did=p1->did; p2->fcolor=p1->fcolor; p2->lf=p1->lf; p2->maxv=p1->maxv; p2->type=p1->type; GetptFromDRECT(p1->rt,p2->pt); return sizeof(N_PCTPIE); }
7a74fb1d3d2daf2ed12e2f1b1420363d573b9d61
0f55e487db3da823ae18f00e9d049bb0a82e32e0
/WorkSpace/GameLibInclude/glMemoryHelper.h
e6dc8b052d9ab330139b751462bb14031260b52b
[]
no_license
RiverUp2012/Cat
d64dd9995922c904ce10bcb9e9ddab89e8a0aae5
29bdaaa352c659580751e8779875aa2f51f3ee87
refs/heads/master
2020-07-16T23:27:01.862743
2019-09-22T16:07:55
2019-09-22T16:07:55
205,890,421
0
0
null
null
null
null
UTF-8
C++
false
false
217
h
glMemoryHelper.h
#pragma once class glMemoryHelper { public: static void xor(unsigned char * buffer, const int bytesToProcess); static void xor(unsigned char * buffer, const int bytesToProcess, const unsigned char factorChar); };
96ee5ad93556ac9870ffa44856e2bb6ddc433592
11dc889c688e49b25972389a18614618b9480024
/paddle/platform/dynload/curand.cc
5c1fab992c98569d4a95b6e699d97d428511e48e
[ "Apache-2.0" ]
permissive
tangxiangru/Paddle
632f41c81de1383e17510f141b36fd872001c973
2200ff5e3c8322b405395995bd6476058df0e8fb
refs/heads/develop
2021-01-01T19:12:31.720146
2017-07-27T08:06:28
2017-07-27T08:06:28
98,535,637
1
0
null
2017-07-27T12:55:01
2017-07-27T12:55:01
null
UTF-8
C++
false
false
262
cc
curand.cc
#include <paddle/platform/dynload/curand.h> namespace paddle { namespace platform { namespace dynload { std::once_flag curand_dso_flag; void *curand_dso_handle; #define DEFINE_WRAP(__name) DynLoad__##__name __name CURAND_RAND_ROUTINE_EACH(DEFINE_WRAP); } } }
887c1eb56cb82501ea5038f312f34ab64b3ce481
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/DboClient/Lib/NtlGui/gui_effect_path_chase.cpp
f044c390bbf0ff74867583dfdaf1877092a29fb2
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
ISO-8859-7
C++
false
false
7,904
cpp
gui_effect_path_chase.cpp
#include "gui_precomp.h" /* #include "gui_effect_path_chase.h" #include "gui_renderer.h" #include "GuiUtil.h" START_GUI GUI_DEFINITION_MEMORY_POOL( CPathInfo_Pos ) GUI_DEFINITION_MEMORY_POOL( CPathInfo_PosAlpha ) GUI_DEFINITION_MEMORY_POOL( CPathParticle ) /////////////////////////////////////////////////////////////////////////////////////////// // CPathParticle VOID CPathInfo_Pos::Update( CPathParticle* pParticle ) { CPos& posParent = pParticle->GetPos(); CPos posInterpolate; INT nHalfWidth = pParticle->m_SnapShot.rtRect.GetWidth() / 2; INT nHalfHeight= pParticle->m_SnapShot.rtRect.GetHeight() / 2; posInterpolate.x = (INT)( GetResultLineInterpolation( pParticle->GetTime(), m_fPathTime, (FLOAT)m_posSrcCenter.x, (FLOAT)m_posDestCenter.x ) ); posInterpolate.y = (INT)( GetResultLineInterpolation( pParticle->GetTime(), m_fPathTime, (FLOAT)m_posSrcCenter.y, (FLOAT)m_posDestCenter.y ) ); pParticle->m_SnapShot.rtRect.left = posParent.x + posInterpolate.x - nHalfWidth; pParticle->m_SnapShot.rtRect.top = posParent.y + posInterpolate.y - nHalfHeight; pParticle->m_SnapShot.rtRect.right = posParent.x + posInterpolate.x + nHalfWidth; pParticle->m_SnapShot.rtRect.bottom = posParent.y + posInterpolate.y + nHalfHeight; } VOID CPathInfo_PosAlpha::Update( CPathParticle* pParticle ) { CPos& posParent = pParticle->GetPos(); CPos posInterpolate; INT nHalfWidth = pParticle->m_SnapShot.rtRect.GetWidth() / 2; INT nHalfHeight= pParticle->m_SnapShot.rtRect.GetHeight() / 2; posInterpolate.x = (INT)( GetResultLineInterpolation( pParticle->GetTime(), m_fPathTime, (FLOAT)m_posSrcCenter.x, (FLOAT)m_posDestCenter.x ) ); posInterpolate.y = (INT)( GetResultLineInterpolation( pParticle->GetTime(), m_fPathTime, (FLOAT)m_posSrcCenter.y, (FLOAT)m_posDestCenter.y ) ); BYTE ucAlpha = (BYTE)( GetResultLineInterpolation( pParticle->GetTime(), m_fPathTime, (FLOAT)m_ucSrcAlpha, (FLOAT)m_ucDestAlpha ) ); pParticle->m_SnapShot.rtRect.left = posParent.x + posInterpolate.x - nHalfWidth; pParticle->m_SnapShot.rtRect.top = posParent.y + posInterpolate.y - nHalfHeight; pParticle->m_SnapShot.rtRect.right = posParent.x + posInterpolate.x + nHalfWidth; pParticle->m_SnapShot.rtRect.bottom = posParent.y + posInterpolate.y + nHalfHeight; pParticle->m_SnapShot.uAlpha = ucAlpha; } /////////////////////////////////////////////////////////////////////////////////////////// // CPathParticle CPathParticle::CPathParticle( CSurface& surface, std::vector<CPathInfo*>* pvecPath, CPos& posParent ) : m_posParent( posParent ) { m_Original.rtRect.left = surface.m_Original.rtRect.left; m_Original.rtRect.top = surface.m_Original.rtRect.top; m_Original.rtRect.right = surface.m_Original.rtRect.right; m_Original.rtRect.bottom = surface.m_Original.rtRect.bottom; m_Original.uRed = surface.m_Original.uRed; m_Original.uGreen = surface.m_Original.uGreen; m_Original.uBlue = surface.m_Original.uBlue; m_Original.uAlpha = surface.m_Original.uAlpha; m_Original.UVs[0] = surface.m_Original.UVs[0]; m_Original.UVs[1] = surface.m_Original.UVs[1]; m_Original.UVs[2] = surface.m_Original.UVs[2]; m_Original.UVs[3] = surface.m_Original.UVs[3]; m_Original.uBlend = surface.m_Original.uBlend; m_SnapShot.rtRect.left = surface.m_SnapShot.rtRect.left; m_SnapShot.rtRect.top = surface.m_SnapShot.rtRect.top; m_SnapShot.rtRect.right = surface.m_SnapShot.rtRect.right; m_SnapShot.rtRect.bottom = surface.m_SnapShot.rtRect.bottom; m_SnapShot.uRed = surface.m_SnapShot.uRed; m_SnapShot.uGreen = surface.m_SnapShot.uGreen; m_SnapShot.uBlue = surface.m_SnapShot.uBlue; m_SnapShot.uAlpha = surface.m_SnapShot.uAlpha; m_SnapShot.UVs[0] = surface.m_SnapShot.UVs[0]; m_SnapShot.UVs[1] = surface.m_SnapShot.UVs[1]; m_SnapShot.UVs[2] = surface.m_SnapShot.UVs[2]; m_SnapShot.UVs[3] = surface.m_SnapShot.UVs[3]; m_SnapShot.uBlend = surface.m_SnapShot.uBlend; m_pTexture = surface.m_pTexture; m_fAngle = surface.m_fAngle; m_pvecPath = pvecPath; Reset(); } VOID CPathParticle::Reset(VOID) { m_fCurrentTime = 0.0f; m_nPathIndex = 0; } BOOL CPathParticle::Update( FLOAT fElapsedTIme, BOOL bRepeat ) { // return FALSE : »θΑ¦. m_fCurrentTime += fElapsedTIme; // Time Check if( m_fCurrentTime >= (*m_pvecPath)[m_nPathIndex]->m_fPathTime ) { m_fCurrentTime -= (*m_pvecPath)[m_nPathIndex]->m_fPathTime; ++m_nPathIndex; } // Path Check if( m_nPathIndex >= (INT)m_pvecPath->size() ) { if( bRepeat ) Reset(); else return FALSE; } // Apply (*m_pvecPath)[m_nPathIndex]->Update( this ); return TRUE; } VOID CPathParticle::Render(VOID) { g_GuiRenderer.RenderQueue( &m_SnapShot, m_pTexture ); } ///////////////////////////////////////////////////////////////////////////////////////////// // CPathChaseEffect CPathChaseEffect::CPathChaseEffect(VOID) { Init(); } CPathChaseEffect::~CPathChaseEffect(VOID) { ClearPath(); ClearParticle(); } VOID CPathChaseEffect::SetCenterPos( INT nPosX, INT nPosY ) { m_posCenter.SetPos( nPosX, nPosY ); std::list<CPathParticle*>::iterator it; for( it = m_listParticles.begin() ; it != m_listParticles.end() ; ++it ) { (*it)->SetParentPos( m_posCenter ); } } VOID CPathChaseEffect::AddPathInfo( CPathInfo* pPathInfo ) { if( IsWork() ) EndProc(); m_vecPathInfo.push_back( pPathInfo ); } VOID CPathChaseEffect::SetEmitSizer( INT nWidth, INT nHeight ) { if( nWidth == 0 && nHeight == 0 ) { m_EmitSizer.bSizer = FALSE; return; } m_EmitSizer.bSizer = TRUE; m_EmitSizer.nWidth = nWidth; m_EmitSizer.nHeight= nHeight; } VOID CPathChaseEffect::Reset(VOID) { ClearParticle(); m_fCurrentTime = 0.0f; m_fCurrentEmitTime = 0.0f; m_bFinishEmit = FALSE; } VOID CPathChaseEffect::Update( FLOAT fElapsedTime ) { if( !m_bRun ) return; // LifeTime Check m_fCurrentTime += fElapsedTime; if( m_fCurrentTime >= m_fLifeTime ) { if( !m_bRepeat ) { EndProc(); return; } } // EmitTime Check if( !m_bFinishEmit ) { if( m_listParticles.size() < (DWORD)m_nEmitCount ) { m_fCurrentEmitTime += fElapsedTime; if( m_fCurrentEmitTime >= m_fEmitTime ) { EmitParticle(); m_fCurrentEmitTime -= m_fEmitTime; } } else m_bFinishEmit = TRUE; } // Particle Update std::list<CPathParticle*>::iterator it; for( it = m_listParticles.begin() ; it != m_listParticles.end() ; ) { if( (*it)->Update( fElapsedTime, m_bRepeat ) ) { ++it; } else { delete (*it); it = m_listParticles.erase( it ); } } } VOID CPathChaseEffect::Render(VOID) { if( m_bRun ) { std::list<CPathParticle*>::iterator it; for( it = m_listParticles.begin() ; it != m_listParticles.end() ; ++it ) { (*it)->Render(); } } } VOID CPathChaseEffect::Init(VOID) { m_fLifeTime = 0.0f; m_fCurrentEmitTime = 0.0f; m_fEmitTime = 0.0f; m_fCurrentEmitTime = 0.0f; m_nEmitCount = 0; m_bRun = FALSE; m_bRepeat = FALSE; m_bFinishEmit = FALSE; m_EmitSizer.bSizer = FALSE; m_EmitSizer.nWidth = 0; m_EmitSizer.nHeight= 0; } VOID CPathChaseEffect::ClearParticle(VOID) { std::list<CPathParticle*>::iterator it; for( it = m_listParticles.begin() ; it != m_listParticles.end() ; ++it ) { delete (*it); } m_listParticles.clear(); } VOID CPathChaseEffect::ClearPath(VOID) { std::vector<CPathInfo*>::iterator it; for( it = m_vecPathInfo.begin() ; it != m_vecPathInfo.end() ; ++it ) { delete (*it); } m_vecPathInfo.clear(); } VOID CPathChaseEffect::EmitParticle(VOID) { if( m_EmitSizer.bSizer ) { CSurface surface = m_vecSurface[0]; surface.m_SnapShot.rtRect.right += m_EmitSizer.nWidth * (INT)m_listParticles.size(); surface.m_SnapShot.rtRect.bottom+= m_EmitSizer.nHeight* (INT)m_listParticles.size(); m_listParticles.push_back( NTL_NEW CPathParticle( surface, &m_vecPathInfo, m_posCenter ) ); } else { m_listParticles.push_back( NTL_NEW CPathParticle( m_vecSurface[0], &m_vecPathInfo, m_posCenter ) ); } } END_GUI */
6601b5e50f5d596a16671e51624d89d294c754fd
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/protobuf/src/google/protobuf/reflection_ops_unittest.cc
0ae697428f0dfae6ff0b9bee765cc3e489177a87
[ "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-protobuf" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
20,290
cc
reflection_ops_unittest.cc
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 // OWNER 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/reflection_ops.h> #include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace internal { namespace { TEST(ReflectionOpsTest, SanityCheck) { unittest::TestAllTypes message; TestUtil::SetAllFields(&message); TestUtil::ExpectAllFieldsSet(message); } TEST(ReflectionOpsTest, Copy) { unittest::TestAllTypes message, message2; TestUtil::SetAllFields(&message); ReflectionOps::Copy(message, &message2); TestUtil::ExpectAllFieldsSet(message2); // Copying from self should be a no-op. ReflectionOps::Copy(message2, &message2); TestUtil::ExpectAllFieldsSet(message2); } TEST(ReflectionOpsTest, CopyExtensions) { unittest::TestAllExtensions message, message2; TestUtil::SetAllExtensions(&message); ReflectionOps::Copy(message, &message2); TestUtil::ExpectAllExtensionsSet(message2); } TEST(ReflectionOpsTest, CopyOneof) { unittest::TestOneof2 message, message2; TestUtil::SetOneof1(&message); ReflectionOps::Copy(message, &message2); TestUtil::ExpectOneofSet1(message2); TestUtil::SetOneof2(&message); TestUtil::ExpectOneofSet2(message); ReflectionOps::Copy(message, &message2); TestUtil::ExpectOneofSet2(message2); } TEST(ReflectionOpsTest, Merge) { // Note: Copy is implemented in terms of Merge() so technically the Copy // test already tested most of this. unittest::TestAllTypes message, message2; TestUtil::SetAllFields(&message); // This field will test merging into an empty spot. message2.set_optional_int32(message.optional_int32()); message.clear_optional_int32(); // This tests overwriting. message2.set_optional_string(message.optional_string()); message.set_optional_string("something else"); // This tests concatenating. message2.add_repeated_int32(message.repeated_int32(1)); int32_t i = message.repeated_int32(0); message.clear_repeated_int32(); message.add_repeated_int32(i); ReflectionOps::Merge(message2, &message); TestUtil::ExpectAllFieldsSet(message); } TEST(ReflectionOpsTest, MergeExtensions) { // Note: Copy is implemented in terms of Merge() so technically the Copy // test already tested most of this. unittest::TestAllExtensions message, message2; TestUtil::SetAllExtensions(&message); // This field will test merging into an empty spot. message2.SetExtension( unittest::optional_int32_extension, message.GetExtension(unittest::optional_int32_extension)); message.ClearExtension(unittest::optional_int32_extension); // This tests overwriting. message2.SetExtension( unittest::optional_string_extension, message.GetExtension(unittest::optional_string_extension)); message.SetExtension(unittest::optional_string_extension, "something else"); // This tests concatenating. message2.AddExtension( unittest::repeated_int32_extension, message.GetExtension(unittest::repeated_int32_extension, 1)); int32_t i = message.GetExtension(unittest::repeated_int32_extension, 0); message.ClearExtension(unittest::repeated_int32_extension); message.AddExtension(unittest::repeated_int32_extension, i); ReflectionOps::Merge(message2, &message); TestUtil::ExpectAllExtensionsSet(message); } TEST(ReflectionOpsTest, MergeUnknown) { // Test that the messages' UnknownFieldSets are correctly merged. unittest::TestEmptyMessage message1, message2; message1.mutable_unknown_fields()->AddVarint(1234, 1); message2.mutable_unknown_fields()->AddVarint(1234, 2); ReflectionOps::Merge(message2, &message1); ASSERT_EQ(2, message1.unknown_fields().field_count()); ASSERT_EQ(UnknownField::TYPE_VARINT, message1.unknown_fields().field(0).type()); EXPECT_EQ(1, message1.unknown_fields().field(0).varint()); ASSERT_EQ(UnknownField::TYPE_VARINT, message1.unknown_fields().field(1).type()); EXPECT_EQ(2, message1.unknown_fields().field(1).varint()); } TEST(ReflectionOpsTest, MergeOneof) { unittest::TestOneof2 message1, message2; TestUtil::SetOneof1(&message1); // Merge to empty message ReflectionOps::Merge(message1, &message2); TestUtil::ExpectOneofSet1(message2); // Merge with the same oneof fields ReflectionOps::Merge(message1, &message2); TestUtil::ExpectOneofSet1(message2); // Merge with different oneof fields TestUtil::SetOneof2(&message1); ReflectionOps::Merge(message1, &message2); TestUtil::ExpectOneofSet2(message2); } #ifdef PROTOBUF_HAS_DEATH_TEST TEST(ReflectionOpsTest, MergeFromSelf) { // Note: Copy is implemented in terms of Merge() so technically the Copy // test already tested most of this. unittest::TestAllTypes message; EXPECT_DEATH(ReflectionOps::Merge(message, &message), "&from"); } #endif // PROTOBUF_HAS_DEATH_TEST TEST(ReflectionOpsTest, Clear) { unittest::TestAllTypes message; TestUtil::SetAllFields(&message); ReflectionOps::Clear(&message); TestUtil::ExpectClear(message); // Check that getting embedded messages returns the objects created during // SetAllFields() rather than default instances. EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), &message.optionalgroup()); EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), &message.optional_nested_message()); EXPECT_NE(&unittest::ForeignMessage::default_instance(), &message.optional_foreign_message()); EXPECT_NE(&unittest_import::ImportMessage::default_instance(), &message.optional_import_message()); } TEST(ReflectionOpsTest, ClearExtensions) { unittest::TestAllExtensions message; TestUtil::SetAllExtensions(&message); ReflectionOps::Clear(&message); TestUtil::ExpectExtensionsClear(message); // Check that getting embedded messages returns the objects created during // SetAllExtensions() rather than default instances. EXPECT_NE(&unittest::OptionalGroup_extension::default_instance(), &message.GetExtension(unittest::optionalgroup_extension)); EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), &message.GetExtension(unittest::optional_nested_message_extension)); EXPECT_NE( &unittest::ForeignMessage::default_instance(), &message.GetExtension(unittest::optional_foreign_message_extension)); EXPECT_NE(&unittest_import::ImportMessage::default_instance(), &message.GetExtension(unittest::optional_import_message_extension)); } TEST(ReflectionOpsTest, ClearUnknown) { // Test that the message's UnknownFieldSet is correctly cleared. unittest::TestEmptyMessage message; message.mutable_unknown_fields()->AddVarint(1234, 1); ReflectionOps::Clear(&message); EXPECT_EQ(0, message.unknown_fields().field_count()); } TEST(ReflectionOpsTest, ClearOneof) { unittest::TestOneof2 message; TestUtil::ExpectOneofClear(message); TestUtil::SetOneof1(&message); TestUtil::ExpectOneofSet1(message); ReflectionOps::Clear(&message); TestUtil::ExpectOneofClear(message); TestUtil::SetOneof1(&message); TestUtil::ExpectOneofSet1(message); TestUtil::SetOneof2(&message); TestUtil::ExpectOneofSet2(message); ReflectionOps::Clear(&message); TestUtil::ExpectOneofClear(message); } TEST(ReflectionOpsTest, DiscardUnknownFields) { unittest::TestAllTypes message; TestUtil::SetAllFields(&message); // Set some unknown fields in message. message.mutable_unknown_fields()->AddVarint(123456, 654321); message.mutable_optional_nested_message() ->mutable_unknown_fields() ->AddVarint(123456, 654321); message.mutable_repeated_nested_message(0) ->mutable_unknown_fields() ->AddVarint(123456, 654321); EXPECT_EQ(1, message.unknown_fields().field_count()); EXPECT_EQ(1, message.optional_nested_message().unknown_fields().field_count()); EXPECT_EQ(1, message.repeated_nested_message(0).unknown_fields().field_count()); // Discard them. ReflectionOps::DiscardUnknownFields(&message); TestUtil::ExpectAllFieldsSet(message); EXPECT_EQ(0, message.unknown_fields().field_count()); EXPECT_EQ(0, message.optional_nested_message().unknown_fields().field_count()); EXPECT_EQ(0, message.repeated_nested_message(0).unknown_fields().field_count()); } TEST(ReflectionOpsTest, DiscardUnknownExtensions) { unittest::TestAllExtensions message; TestUtil::SetAllExtensions(&message); // Set some unknown fields. message.mutable_unknown_fields()->AddVarint(123456, 654321); message.MutableExtension(unittest::optional_nested_message_extension) ->mutable_unknown_fields() ->AddVarint(123456, 654321); message.MutableExtension(unittest::repeated_nested_message_extension, 0) ->mutable_unknown_fields() ->AddVarint(123456, 654321); EXPECT_EQ(1, message.unknown_fields().field_count()); EXPECT_EQ(1, message.GetExtension(unittest::optional_nested_message_extension) .unknown_fields() .field_count()); EXPECT_EQ(1, message.GetExtension(unittest::repeated_nested_message_extension, 0) .unknown_fields() .field_count()); // Discard them. ReflectionOps::DiscardUnknownFields(&message); TestUtil::ExpectAllExtensionsSet(message); EXPECT_EQ(0, message.unknown_fields().field_count()); EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension) .unknown_fields() .field_count()); EXPECT_EQ(0, message.GetExtension(unittest::repeated_nested_message_extension, 0) .unknown_fields() .field_count()); } TEST(ReflectionOpsTest, IsInitialized) { unittest::TestRequired message; EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); message.set_a(1); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, true)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); message.set_b(2); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, true)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); message.set_c(3); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); } TEST(ReflectionOpsTest, ForeignIsInitialized) { unittest::TestRequiredForeign message; // Starts out initialized because the foreign message is itself an optional // field. EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); // Once we create that field, the message is no longer initialized. message.mutable_optional_message(); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); // Initialize it. Now we're initialized. message.mutable_optional_message()->set_a(1); message.mutable_optional_message()->set_b(2); message.mutable_optional_message()->set_c(3); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); // Add a repeated version of the message. No longer initialized. unittest::TestRequired* sub_message = message.add_repeated_message(); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); // Initialize that repeated version. sub_message->set_a(1); sub_message->set_b(2); sub_message->set_c(3); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); } TEST(ReflectionOpsTest, ExtensionIsInitialized) { unittest::TestAllExtensions message; // Starts out initialized because the foreign message is itself an optional // field. EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); // Once we create that field, the message is no longer initialized. message.MutableExtension(unittest::TestRequired::single); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); // Initialize it. Now we're initialized. message.MutableExtension(unittest::TestRequired::single)->set_a(1); message.MutableExtension(unittest::TestRequired::single)->set_b(2); message.MutableExtension(unittest::TestRequired::single)->set_c(3); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); // Add a repeated version of the message. No longer initialized. message.AddExtension(unittest::TestRequired::multi); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); // Initialize that repeated version. message.MutableExtension(unittest::TestRequired::multi, 0)->set_a(1); message.MutableExtension(unittest::TestRequired::multi, 0)->set_b(2); message.MutableExtension(unittest::TestRequired::multi, 0)->set_c(3); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); } TEST(ReflectionOpsTest, OneofIsInitialized) { unittest::TestRequiredOneof message; EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); message.mutable_foo_message(); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); message.set_foo_int(1); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); message.mutable_foo_message(); EXPECT_FALSE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true)); message.mutable_foo_message()->set_required_double(0.1); EXPECT_TRUE(ReflectionOps::IsInitialized(message)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false)); EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true)); } static std::string FindInitializationErrors(const Message& message) { std::vector<std::string> errors; ReflectionOps::FindInitializationErrors(message, "", &errors); return Join(errors, ","); } TEST(ReflectionOpsTest, FindInitializationErrors) { unittest::TestRequired message; EXPECT_EQ("a,b,c", FindInitializationErrors(message)); } TEST(ReflectionOpsTest, FindForeignInitializationErrors) { unittest::TestRequiredForeign message; message.mutable_optional_message(); message.add_repeated_message(); message.add_repeated_message(); EXPECT_EQ( "optional_message.a," "optional_message.b," "optional_message.c," "repeated_message[0].a," "repeated_message[0].b," "repeated_message[0].c," "repeated_message[1].a," "repeated_message[1].b," "repeated_message[1].c", FindInitializationErrors(message)); } TEST(ReflectionOpsTest, FindExtensionInitializationErrors) { unittest::TestAllExtensions message; message.MutableExtension(unittest::TestRequired::single); message.AddExtension(unittest::TestRequired::multi); message.AddExtension(unittest::TestRequired::multi); EXPECT_EQ( "(protobuf_unittest.TestRequired.single).a," "(protobuf_unittest.TestRequired.single).b," "(protobuf_unittest.TestRequired.single).c," "(protobuf_unittest.TestRequired.multi)[0].a," "(protobuf_unittest.TestRequired.multi)[0].b," "(protobuf_unittest.TestRequired.multi)[0].c," "(protobuf_unittest.TestRequired.multi)[1].a," "(protobuf_unittest.TestRequired.multi)[1].b," "(protobuf_unittest.TestRequired.multi)[1].c", FindInitializationErrors(message)); } TEST(ReflectionOpsTest, FindOneofInitializationErrors) { unittest::TestRequiredOneof message; message.mutable_foo_message(); EXPECT_EQ("foo_message.required_double", FindInitializationErrors(message)); } TEST(ReflectionOpsTest, GenericSwap) { Arena arena; { unittest::TestAllTypes message; auto* arena_message = Arena::CreateMessage<unittest::TestAllTypes>(&arena); TestUtil::SetAllFields(arena_message); const uint64_t initial_arena_size = arena.SpaceUsed(); GenericSwap(&message, arena_message); TestUtil::ExpectAllFieldsSet(message); TestUtil::ExpectClear(*arena_message); // The temp should be allocated on the arena in this case. EXPECT_GT(arena.SpaceUsed(), initial_arena_size); } { unittest::TestAllTypes message; auto* arena_message = Arena::CreateMessage<unittest::TestAllTypes>(&arena); TestUtil::SetAllFields(arena_message); const uint64_t initial_arena_size = arena.SpaceUsed(); GenericSwap(arena_message, &message); TestUtil::ExpectAllFieldsSet(message); TestUtil::ExpectClear(*arena_message); // The temp should be allocated on the arena in this case. EXPECT_GT(arena.SpaceUsed(), initial_arena_size); } } } // namespace } // namespace internal } // namespace protobuf } // namespace google
a5e1cc0c37d2c448a08341ec35c8b7ec12ec3a22
213b6b25c8606491e822b29f43e06305852c9e1a
/src/pipe.h
1ce0519d82edf86b2c080cd2da6222abe5a4a612
[]
no_license
NormenL/Hyperion
112f9eea8b93fcf2298047d7417d857566e0339e
f820a52266f9156fbf1976b0e4324e67d4d0b4e1
refs/heads/master
2023-03-11T17:31:10.499468
2021-02-22T14:06:36
2021-02-22T14:06:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,184
h
pipe.h
#pragma once #include <inttypes.h> #include "inputs/input.h" #include "outputs/output.h" #include "luts/lut.h" using HandlerFunc = int (*)(uint8_t *data, int length, Output *out, LUT *lut); const int MTU = 3100; uint8_t data[MTU]; //i used to malloc this, but the MTU is 1500, so i just set it to the upped bound //Pipes are object that tie everything together: a pipe has an input and an output. //The input privodes the data and the output sends it out to the lamps. //Additionally you can provide a custom transfer function. This is the function that will copy the data //from input to output. One that is often used is the static function //Pipe::transfer<SourceColour,TargetColour>. This function will convert the data from source format //to target format. eg. from RGB to RGBW or from RGB to Monochrome. The pipe also stores a reference //to the lut that that the transfer function can apply. class Pipe { public: Pipe(Input *in, Output *out, HandlerFunc converter = Pipe::transfer, LUT *lut = NULL) { this->in = in; this->out = out; this->converter = converter; this->lut = lut; } Output *out; Input *in; HandlerFunc converter; LUT *lut; inline void process() { //check if the output is done sending the previous message if (!out->Ready()) return; //load the new frame from the input, or quit if none was available //TODO: either pass the MTU size here so the input knows when to stop copying, //or better: ask for the size and realloc more space if needed. int datalength = in->loadData(data); if (datalength == 0) return; numPixels = this->converter(data, datalength, out, lut); out->Show(); } //Basic transfer function without bells and whistles static int transfer(uint8_t *data, int length, Output *out, LUT *lut) { out->SetLength(length); out->SetData(data, length, 0); return length; //unkown number of pixels, assume 1 pixel per byte } //Transfer function that can convert between colour representations and apply LUTs //This function has been thoroughly optimized, because this is the workhorse of the //device. When making changes be absolutely sure that you keep performance in mind. //See docs/speed and call stack for steps taken to optimize template <class T_SOURCECOLOUR, class T_TARGETCOLOUR> static int transfer(uint8_t *data, int length, Output *out, LUT *lut) { //tell the output the new length so it can allocate enough space for the data //we are going to send //todo this function should return the actual length it has allocated, so we can use tht later out->SetLength(length / sizeof(T_SOURCECOLOUR) * sizeof(T_TARGETCOLOUR)); int numPixels = length / sizeof(T_SOURCECOLOUR); for (int i = 0; i < numPixels; i++) { //store the ith pixel in an object of type T (source datatype) T_SOURCECOLOUR col = ((T_SOURCECOLOUR *)data)[i]; //this is where the actual conversion takes place. static cast will use //the cast operators in the Colour classes to convert between the //representations. T_TARGETCOLOUR outcol = static_cast<T_TARGETCOLOUR>(col); //Apply lookup table to do gamma correction and other non linearities if (lut) outcol.ApplyLut(lut); //Pass the data to the output //TODO why provide the data pixel by pixel als have a function call overhead for each //pixel. cant we dump the entire byte array in one go? //What about a function that passes us a datapointer, and we place the items directly into it //this saves a function call for each pixel, and an additional memcpy. out->SetData((uint8_t *)&outcol, sizeof(T_TARGETCOLOUR), i * sizeof(T_TARGETCOLOUR)); } return numPixels; } int getNumPixels() { return numPixels; } private: int numPixels=0; //keep track of the number of pixels is for stats only. };
42f12aa3b89b81c45cb07527c277b190d6ab60be
9a661069c8ec79402747d44e18cf7aec80ed453a
/heart/test/monodomain/TestMonodomainProblem.hpp
e1db705f435cf29e06a89d9e4994f6e361fe1bed
[ "BSD-3-Clause" ]
permissive
Chaste/Chaste
474e589bc49995cd08674e1649c01d99bc920391
f21282cbe6e3c644cba4c24e7a3fa9d55480d9b2
refs/heads/develop
2023-08-16T19:22:40.524860
2023-08-16T09:30:04
2023-08-16T09:30:04
62,891,278
116
62
NOASSERTION
2023-09-14T16:37:19
2016-07-08T13:37:56
C++
UTF-8
C++
false
false
84,314
hpp
TestMonodomainProblem.hpp
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _TESTMONODOMAINPROBLEM_HPP_ #define _TESTMONODOMAINPROBLEM_HPP_ #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <cxxtest/TestSuite.h> #include <vector> #include "AbstractCardiacCellFactory.hpp" #include "AbstractCvodeCell.hpp" #include "LuoRudy1991.hpp" #include "LuoRudy1991Cvode.hpp" #include "MonodomainProblem.hpp" //#include "LuoRudy1991BackwardEulerOpt.hpp" #include "ActivationOutputModifier.hpp" #include "ArchiveOpener.hpp" #include "CardiacSimulationArchiver.hpp" #include "ChasteSyscalls.hpp" #include "CheckMonoLr91Vars.hpp" #include "CmguiMeshWriter.hpp" #include "CompareHdf5ResultsFiles.hpp" #include "FaberRudy2000.hpp" #include "FileComparison.hpp" #include "Hdf5DataReader.hpp" #include "NumericFileComparison.hpp" #include "PetscTools.hpp" #include "PlaneStimulusCellFactory.hpp" #include "ReplicatableVector.hpp" #include "SingleTraceOutputModifier.hpp" #include "TetrahedralMesh.hpp" #include "VtkMeshReader.hpp" #include "Warnings.hpp" #include "PetscSetupAndFinalize.hpp" /* * This cell factory introduces a stimulus in the very centre of mesh/test/data/2D_0_to_1mm_400_elements. * This is node 60 at (0.5, 0.5) */ class PointStimulus2dCellFactory : public AbstractCardiacCellFactory<2> { private: boost::shared_ptr<SimpleStimulus> mpStimulus; unsigned mFoundMiddlePoint; public: PointStimulus2dCellFactory() : AbstractCardiacCellFactory<2>(), mpStimulus(new SimpleStimulus(-6000.0, 0.5)), mFoundMiddlePoint(0) { } AbstractCardiacCell* CreateCardiacCellForTissueNode(Node<2>* pNode) { ChastePoint<2> location = pNode->GetPoint(); if (fabs(location[0] - 0.05) < 1e-6 && fabs(location[1] - 0.05) < 1e-6) { mFoundMiddlePoint++; return new CellLuoRudy1991FromCellML(mpSolver, mpStimulus); } else { return new CellLuoRudy1991FromCellML(mpSolver, mpZeroStimulus); } } void FinaliseCellCreation(std::vector<AbstractCardiacCellInterface*>* pCellsDistributed, unsigned lo, unsigned hi) { unsigned found_middle_point_reduced; MPI_Allreduce(&mFoundMiddlePoint, &found_middle_point_reduced, 1, MPI_UNSIGNED, MPI_SUM, PETSC_COMM_WORLD); assert(found_middle_point_reduced == 1); // Only 1 cell should be stimulated } }; #ifdef CHASTE_CVODE /* * Cell factory for TestOutputDoesNotDependOnPrintTimestep. Returns CVODE cells */ class Cvode1dCellFactory : public AbstractCardiacCellFactory<1> { private: boost::shared_ptr<SimpleStimulus> mpStimulus; public: Cvode1dCellFactory() : AbstractCardiacCellFactory<1>(), mpStimulus(new SimpleStimulus(-70000.0, 1.0, 0.0)) { } AbstractCvodeCell* CreateCardiacCellForTissueNode(Node<1>* pNode) { AbstractCvodeCell* p_cell; boost::shared_ptr<AbstractIvpOdeSolver> p_empty_solver; double x = pNode->rGetLocation()[0]; if (x < 0.3) { p_cell = new CellLuoRudy1991FromCellMLCvode(p_empty_solver, mpStimulus); } else { p_cell = new CellLuoRudy1991FromCellMLCvode(p_empty_solver, mpZeroStimulus); } // Beefed-up CVODE tolerances. p_cell->SetTolerances(1e-7, 1e-9); return p_cell; } }; #endif // CHASTE_CVODE class TestMonodomainProblem : public CxxTest::TestSuite { private: std::vector<double> mVoltageReplicated1d2ms; ///<Used to test differences between tests public: void setUp() { HeartConfig::Reset(); } // This is a test on a very small mesh (where there may be more processes than there are nodes) // // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblemSimplestMesh1D() { if (PetscTools::GetNumProcs() > 2u) { // There are only 2 nodes in this simulation TS_TRACE("This test is not suitable for more than 2 processes."); return; } DistributedTetrahedralMesh<1, 1> mesh; //TrianglesMeshReader<1,1> reader("mesh/test/data/1D_0_to_1_1_element"); mesh.ConstructLinearMesh(1); TS_ASSERT_EQUALS(mesh.GetNumNodes(), 2u); TS_ASSERT_EQUALS(mesh.GetNumElements(), 1u); if (!PetscTools::IsSequential()) { if (PetscTools::GetMyRank() < 2) { TS_ASSERT_EQUALS(mesh.GetNumLocalNodes(), 1u); TS_ASSERT_EQUALS(mesh.GetNumLocalElements(), 1u); } else { TS_ASSERT_EQUALS(mesh.GetNumLocalNodes(), 0u); TS_ASSERT_EQUALS(mesh.GetNumLocalElements(), 0u); } } HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms HeartConfig::Instance()->SetOutputDirectory("MonoProblem1dSimplest"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); //HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1_1_element"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.SetMesh(&mesh); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(10.0); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[0], -52.1698, atol); TS_ASSERT_DELTA(voltage_replicated[1], -83.8381, atol); } // Solve on a 1D string of cells, 1mm long with a space step of 0.1mm. // // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem1D() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1d"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); // Set extra variable (to cover extension of HDF5 with named variables) in a later test std::vector<std::string> output_variables; /* * HOW_TO_TAG Cardiac/Output * Calculating and outputting ionic currents ('derived quantities') in a tissue simulation using * class:HeartConfig - see also [wiki:ChasteGuides/CodeGenerationFromCellML#Derivedquantities this page]. */ // This is how to output an additional state variable output_variables.push_back("cytosolic_calcium_concentration"); // or indeed an additional parameter or derived quantity. In the CellML // the variable 'potassium_currents' (sum of potassium currents) is annotated as a // derived quantity to be calculated. output_variables.push_back("potassium_currents"); HeartConfig::Instance()->SetOutputVariables(output_variables); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); // Just checking an exception message here. TS_ASSERT_THROWS_THIS(monodomain_problem.GetTissue(), "Tissue not yet set up, you may need to call Initialise() before GetTissue()."); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { mVoltageReplicated1d2ms.push_back(voltage_replicated[index]); } //How close is our "standard" answer? atol = 5e-3; TS_ASSERT_DELTA(mVoltageReplicated1d2ms[1], 20.7710232, atol); TS_ASSERT_DELTA(mVoltageReplicated1d2ms[3], 21.5319692, atol); TS_ASSERT_DELTA(mVoltageReplicated1d2ms[5], 22.9280817, atol); TS_ASSERT_DELTA(mVoltageReplicated1d2ms[7], 24.0611303, atol); TS_ASSERT_DELTA(mVoltageReplicated1d2ms[9], -0.770330519, atol); TS_ASSERT_DELTA(mVoltageReplicated1d2ms[10], -19.2234919, atol); // coverage monodomain_problem.GetTissue(); // check a progress report exists OutputFileHandler handler("MonoProblem1d", false); TS_ASSERT(handler.FindFile("progress_status.txt").Exists()); } // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem1DWithRelativeTolerance() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); HeartConfig::Instance()->SetUseRelativeTolerance(1e-9); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1dRelTol"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); /// \todo: If we request "relative" tolerance we shouldn't testing in an "absolute" manner double atol = 2e-5; TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { TS_ASSERT_DELTA(voltage_replicated[index], mVoltageReplicated1d2ms[index], 5e-3); } } // Same as TestMonodomainProblem1D, except the 1D mesh is embedded in 3D space. // // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem1Din3D() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_in_3D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1din3d"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1din3d"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1, 3> cell_factory; MonodomainProblem<1, 3> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); // Now compare with the TestMonodomainProblem1D simulation above for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { TS_ASSERT_DELTA(voltage_replicated[index], mVoltageReplicated1d2ms[index], 5e-12); } // cover get pde monodomain_problem.GetTissue(); // check a progress report exists OutputFileHandler handler("MonoProblem1din3d", false); TS_ASSERT(handler.FindFile("progress_status.txt").Exists()); } // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem1DWithAbsoluteTolerance() { double atol = 1e-4; HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetSimulationDuration(2); //ms HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); TS_ASSERT_EQUALS(HeartConfig::Instance()->GetAbsoluteTolerance(), 2e-4); HeartConfig::Instance()->SetUseAbsoluteTolerance(atol / 20.0); ///\todo this is dependent on the number of processes used TS_ASSERT_EQUALS(HeartConfig::Instance()->GetAbsoluteTolerance(), 5e-6); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1dAbsTol"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { TS_ASSERT_DELTA(voltage_replicated[index], mVoltageReplicated1d2ms[index], 5e-3); } } // Solve on a 2D 1mm by 1mm mesh (space step = 0.1mm), stimulating the left // edge. // Should behave like the 1D case, extrapolated. // See also TestMonodomainSlab.hpp (nightly test) for the 3D version. // // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem2DWithEdgeStimulus() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(2); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem2dWithEdgeStimulus"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_2dWithEdgeStimulus"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory; // using the criss-cross mesh so wave propagates properly MonodomainProblem<2> monodomain_problem(&cell_factory); // Coverage TS_ASSERT(!monodomain_problem.GetHasBath()); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars(monodomain_problem); //Since we are going to compare voltages that may be owned by //various processes it makes sense to replicate the data. Vec voltage = monodomain_problem.GetSolution(); ReplicatableVector voltage_replicated; voltage_replicated.ReplicatePetscVector(voltage); /* * Test the top right node against the right one in the 1D case, * comparing voltage, and then test all the nodes on the right hand * side of the square against the top right one, comparing voltage. */ bool need_initialisation = true; double probe_voltage = 0.0; need_initialisation = true; // Test the RHS of the mesh AbstractTetrahedralMesh<2, 2>& r_mesh = monodomain_problem.rGetMesh(); for (AbstractTetrahedralMesh<2, 2>::NodeIterator iter = r_mesh.GetNodeIteratorBegin(); iter != r_mesh.GetNodeIteratorEnd(); ++iter) { unsigned i = (*iter).GetIndex(); if ((*iter).GetPoint()[0] == 0.1) { // x = 0 is where the stimulus has been applied // x = 0.1cm is the other end of the mesh and where we want to // to test the value of the nodes if (need_initialisation) { probe_voltage = voltage_replicated[i]; need_initialisation = false; } else { // Tests the final voltages for all the RHS edge nodes // are close to each other. // This works as we are using the 'criss-cross' mesh, // the voltages would vary more with a mesh with all the // triangles aligned in the same direction. TS_ASSERT_DELTA(voltage_replicated[i], probe_voltage, 7e-4); } // Check against 1d case - THIS TEST HAS BEEN REMOVED AS THE MESH // IS FINER THAN THE 1D MESH SO WE DONT EXPECT THE RESULTS TO BE THE SAME // TS_ASSERT_DELTA(p_voltage_array[i], -35.1363, 35*0.1); // test the RHS edge voltages // hardcoded result that looks accurate - this is a test to see // that nothing has changed // assumes endtime = 2ms TS_ASSERT_DELTA(voltage_replicated[i], -59.6488, 5e-4); } } } // Solve on a 2D 1mm by 1mm mesh (space step = 0.1mm), stimulating in the // very centre of the mesh. // // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainProblem2DWithPointStimulusInTheVeryCentreOfTheMesh() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(1.3); //ms - needs to be 1.3 ms to pass test HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem2dWithPointStimulus"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_2dWithPointStimulus"); // To time the solve time_t start, end; time(&start); PointStimulus2dCellFactory cell_factory; MonodomainProblem<2> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); monodomain_problem.Solve(); // To time the solve time(&end); //double dif; //dif = difftime (end,start); //printf ("\nSolve took %.2lf seconds. \n", dif ); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars(monodomain_problem); /* * Test that corners are 'equal', and centres of sides. * Irregularities in which way the triangles are oriented make * this rather difficult, especially since the edges are sampled * during the upstroke. */ DistributedVector voltage = monodomain_problem.GetSolutionDistributedVector(); // corners -> 0, 10, 110, 120 // hardcoded result to check against // assumes endtime = 1.3 unsigned corners_checked = 0; for (DistributedVector::Iterator node_index = voltage.Begin(); node_index != voltage.End(); ++node_index) { ChastePoint<2> location = monodomain_problem.rGetMesh().GetNode(node_index.Global)->GetPoint(); if (fabs(location[0] - 0.0) < 1e-6 && fabs(location[1] - 0.0) < 1e-6) // Corner 0 { TS_ASSERT_DELTA(voltage[node_index.Global], -34.3481, 1e-3); corners_checked++; } if (fabs(location[0] - 0.1) < 1e-6 && fabs(location[1] - 0.0) < 1e-6) // Corner 10 { TS_ASSERT_DELTA(voltage[node_index.Global], -34.3481, 1e-3); corners_checked++; } if (fabs(location[0] - 0.0) < 1e-6 && fabs(location[1] - 0.0) < 1e-6) // Corner 110 { TS_ASSERT_DELTA(voltage[node_index.Global], -34.3481, 1e-3); corners_checked++; } if (fabs(location[0] - 0.0) < 1e-6 && fabs(location[1] - 0.0) < 1e-6) // Corner 120 { TS_ASSERT_DELTA(voltage[node_index.Global], -34.3481, 1e-3); corners_checked++; } } unsigned corners_checked_reduced; MPI_Allreduce(&corners_checked, &corners_checked_reduced, 1, MPI_UNSIGNED, MPI_SUM, PETSC_COMM_WORLD); TS_ASSERT(corners_checked_reduced == 4); // centre of edges -> 5, 55, 65, 115 // hardcoded result to check against // assumes endtime = 1.3 unsigned edges_checked = 0; for (DistributedVector::Iterator node_index = voltage.Begin(); node_index != voltage.End(); ++node_index) { ChastePoint<2> location = monodomain_problem.rGetMesh().GetNode(node_index.Global)->GetPoint(); if (fabs(location[0] - 0.05) < 1e-6 && fabs(location[1] - 0.0) < 1e-6) // Node 5 { TS_ASSERT_DELTA(voltage[node_index.Global], 34.6692, 1e-3); edges_checked++; } if (fabs(location[0] - 0.0) < 1e-6 && fabs(location[1] - 0.05) < 1e-6) // Node 55 { TS_ASSERT_DELTA(voltage[node_index.Global], 34.6692, 1e-3); edges_checked++; } if (fabs(location[0] - 0.1) < 1e-6 && fabs(location[1] - 0.05) < 1e-6) // Node 65 { TS_ASSERT_DELTA(voltage[node_index.Global], 34.6692, 1e-3); edges_checked++; } if (fabs(location[0] - 0.05) < 1e-6 && fabs(location[1] - 0.1) < 1e-6) // Node 115 { TS_ASSERT_DELTA(voltage[node_index.Global], 34.6692, 1e-3); edges_checked++; } } unsigned edges_checked_reduced; MPI_Allreduce(&edges_checked, &edges_checked_reduced, 1, MPI_UNSIGNED, MPI_SUM, PETSC_COMM_WORLD); TS_ASSERT(edges_checked_reduced == 4); } /////////////////////////////////////////////////////////////////// // Solve a simple simulation and check the output was only // printed out at the correct times /////////////////////////////////////////////////////////////////// void TestMonodomainProblemPrintsOnlyAtRequestedTimes() { HeartConfig::Instance()->SetPrintingTimeStep(0.1); HeartConfig::Instance()->SetSimulationDuration(0.3); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1dRequestedTimes"); HeartConfig::Instance()->SetOutputFilenamePrefix("mono_testPrintTimes"); // run testing PrintingTimeSteps PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1>* p_monodomain_problem = new MonodomainProblem<1>(&cell_factory); p_monodomain_problem->Initialise(); p_monodomain_problem->SetWriteInfo(); p_monodomain_problem->Solve(); // read data entries for the time file and check correct //Hdf5DataReader data_reader1("MonoProblem1d", "mono_testPrintTimes"); Hdf5DataReader data_reader1 = p_monodomain_problem->GetDataReader(); delete p_monodomain_problem; std::vector<double> times = data_reader1.GetUnlimitedDimensionValues(); TS_ASSERT_EQUALS(times.size(), 4u); TS_ASSERT_DELTA(times[0], 0.00, 1e-12); TS_ASSERT_DELTA(times[1], 0.10, 1e-12); TS_ASSERT_DELTA(times[2], 0.20, 1e-12); TS_ASSERT_DELTA(times[3], 0.30, 1e-12); } // NOTE: This test uses NON-PHYSIOLOGICAL parameters values (conductivities, // surface-area-to-volume ratio, capacitance, stimulus amplitude). Essentially, // the equations have been divided through by the surface-area-to-volume ratio. // (Historical reasons...) void TestMonodomainWithMeshInMemoryToMeshalyzer() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(0.1); //ms HeartConfig::Instance()->SetOutputDirectory("Monodomain2d"); HeartConfig::Instance()->SetOutputFilenamePrefix("monodomain2d"); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(); //set the postprocessing information we want std::vector<unsigned> origin_nodes; origin_nodes.push_back(0u); HeartConfig::Instance()->SetConductionVelocityMaps(origin_nodes); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory; /////////////////////////////////////////////////////////////////// // monodomain /////////////////////////////////////////////////////////////////// MonodomainProblem<2> monodomain_problem(&cell_factory); TetrahedralMesh<2, 2> mesh; mesh.ConstructRegularSlabMesh(0.01, 0.1, 0.1); monodomain_problem.SetMesh(&mesh); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); //Clean previous output OutputFileHandler handler1("Monodomain2d", true); //This one makes sure that we leave a signature file in Monodomain2d so that we can clean up later OutputFileHandler handler("Monodomain2d/output", true); PetscTools::Barrier(); // Checking that the following files don't exist in the output directory before calling Solve() unsigned num_files = 5; std::string test_file_names[5] = { "monodomain2d_mesh.pts", "monodomain2d_mesh.tri", "monodomain2d_V.dat", "ChasteParameters.xml", "ConductionVelocityFromNode0.dat" }; for (unsigned i = 0; i < num_files; i++) { TS_ASSERT(!handler.FindFile(test_file_names[i]).Exists()); } // now solve monodomain_problem.Solve(); PetscTools::Barrier(); // Compare output files for (unsigned i = 0; i < num_files; i++) { if (test_file_names[i] == "monodomain2d_V.dat") { /** * Since we started using bjacobi as the default preconditioner, parallel and sequential tests * may return different results (always accurate to the tolerance requested). * A straight FileComparison is unable to take this consideration into account. * \todo can we use a NumericFileComparison then? * * We will test that the file exists though. */ TS_ASSERT(handler.FindFile(test_file_names[i]).Exists()); } else { std::string file_1 = handler.GetOutputDirectoryFullPath() + "/" + test_file_names[i]; std::string file_2 = "heart/test/data/Monodomain2d/" + test_file_names[i]; /* In parallel, we want result (below) to be consistent across processes. For this to happen no process * should abort the file check. This is why we pretend not to be called collectively. */ FileComparison comparer(file_1, file_2, false /*Pretend that it's not called collectively*/); comparer.SetIgnoreLinesBeginningWith("<cp:ChasteParameters"); comparer.IgnoreBlankLines(); // Needed for XSD 4.0, which strips blanks on writing bool result = comparer.CompareFiles(0, false); // Don't throw a TS_ASSERT if (!result && (i == 3)) { // For "ChasteParameters.xml" there is an alternative file // This is because different versions of XSD produce rounded/full precision floating point numbers FileComparison comparer2(file_1, file_2 + "_alt"); comparer2.SetIgnoreLinesBeginningWith("<cp:ChasteParameters"); TS_ASSERT(comparer2.CompareFiles()); } else { TS_ASSERT(comparer.CompareFiles()); } } } } void TestMonodomainProblemCreates1DGeometry() { HeartConfig::Instance()->SetSpaceDimension(1); HeartConfig::Instance()->SetFibreLength(1, 0.01); HeartConfig::Instance()->SetSimulationDuration(5.0); //ms HeartConfig::Instance()->SetOutputDirectory("MonodomainCreates1dGeometry"); HeartConfig::Instance()->SetOutputFilenamePrefix("monodomain1d"); // Switch on 1D VTK output HeartConfig::Instance()->SetVisualizeWithVtk(true); HeartConfig::Instance()->SetVisualizeWithParallelVtk(true); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory(-600 * 5000); MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); monodomain_problem.Solve(); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 13.9682, atol); TS_ASSERT_DELTA(voltage_replicated[3], 13.9149, atol); TS_ASSERT_DELTA(voltage_replicated[5], 13.8216, atol); TS_ASSERT_DELTA(voltage_replicated[7], 13.7275, atol); #ifdef CHASTE_VTK // Requires "sudo aptitude install libvtk5-dev" or similar std::string filepath = OutputFileHandler::GetChasteTestOutputDirectory() + "MonodomainCreates1dGeometry/vtk_output/"; std::string basename = filepath + "monodomain1d"; if (PetscTools::IsParallel()) { FileFinder pvtk_file(basename + ".pvtu", RelativeTo::Absolute); TS_ASSERT(pvtk_file.Exists()); } FileFinder vtu_file(basename + ".vtu", RelativeTo::Absolute); TS_ASSERT(vtu_file.Exists()); #endif //CHASTE_VTK } void TestMonodomainProblemCreates2DGeometry() { HeartConfig::Instance()->SetSpaceDimension(2); HeartConfig::Instance()->SetSheetDimensions(0.3, 0.3, 0.01); HeartConfig::Instance()->SetSimulationDuration(4.0); //ms HeartConfig::Instance()->SetOutputDirectory("MonodomainCreatesGeometry"); HeartConfig::Instance()->SetOutputFilenamePrefix("monodomain2d"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory(-600 * 5000); MonodomainProblem<2> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); monodomain_problem.Solve(); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 17.5728, atol); TS_ASSERT_DELTA(voltage_replicated[3], 17.4562, atol); TS_ASSERT_DELTA(voltage_replicated[5], 17.2559, atol); TS_ASSERT_DELTA(voltage_replicated[7], 17.0440, atol); } void TestMonodomainProblemCreates3DGeometry() { HeartConfig::Instance()->SetSpaceDimension(3); HeartConfig::Instance()->SetSlabDimensions(0.1, 0.1, 0.1, 0.01); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms HeartConfig::Instance()->SetOutputDirectory("MonodomainCreatesGeometry"); HeartConfig::Instance()->SetOutputFilenamePrefix("monodomain3d"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 3> cell_factory(-600 * 5000); MonodomainProblem<3> monodomain_problem(&cell_factory); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(true); HeartConfig::Instance()->SetVisualizeWithCmgui(true); HeartConfig::Instance()->SetVisualizeWithVtk(true); HeartConfig::Instance()->SetVisualizeWithParallelVtk(true); HeartConfig::Instance()->SetVisualizerOutputPrecision(6); monodomain_problem.Initialise(); monodomain_problem.Solve(); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 31.8958, atol); TS_ASSERT_DELTA(voltage_replicated[3], 32.1109, atol); TS_ASSERT_DELTA(voltage_replicated[5], 32.7315, atol); TS_ASSERT_DELTA(voltage_replicated[7], 33.7011, atol); #ifdef CHASTE_VTK // Requires "sudo aptitude install libvtk5-dev" or similar if (PetscTools::IsParallel()) { std::string filepath = OutputFileHandler::GetChasteTestOutputDirectory() + "MonodomainCreatesGeometry/vtk_output/"; std::string basename = filepath + "monodomain3d"; std::stringstream vtu_path; vtu_path << basename << "_" << PetscTools::GetMyRank() << ".vtu"; FileFinder pvtk_file(basename + ".pvtu", RelativeTo::Absolute); TS_ASSERT(pvtk_file.Exists()); FileFinder vtk_file(vtu_path.str(), RelativeTo::Absolute); TS_ASSERT(vtk_file.Exists()); FileFinder param_file(filepath + "ChasteParameters.xml", RelativeTo::Absolute); TS_ASSERT(param_file.Exists()); FileFinder info_file(basename + "_times.info", RelativeTo::Absolute); TS_ASSERT(info_file.Exists()); } #else std::cout << "This test ran, but did not test VTK-dependent functions as VTK visualization is not enabled." << std::endl; std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl; #endif //CHASTE_VTK // We check that the cmgui files generated by the convert command in the problem class are OK // We compare against mesh files and one data file that are known to be visualized correctly in Cmgui. // The files written in parallel are different from the ones written in sequential because of the different node // numbering, therefore we test only the sequential case. // Note that the outputs of sequential and parallel simulations look the same when loaded with cmgui. // There are also minor rounding differences at the last decimal figure between sequential and parallel. EXIT_IF_PARALLEL std::string results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "MonodomainCreatesGeometry/cmgui_output/"; //the mesh files... std::string node_file1 = results_dir + "/monodomain3d.exnode"; std::string node_file2 = "heart/test/data/CmguiData/monodomain/monodomain3dValid.exnode"; std::string elem_file1 = results_dir + "/monodomain3d.exelem"; std::string elem_file2 = "heart/test/data/CmguiData/monodomain/monodomain3dValid.exelem"; FileComparison comparer(node_file1, node_file2); TS_ASSERT(comparer.CompareFiles()); FileComparison comparer2(elem_file1, elem_file2); TS_ASSERT(comparer2.CompareFiles()); //...and one data file as example FileComparison comparer3(results_dir + "/monodomain3d_43.exnode", "heart/test/data/CmguiData/monodomain/monodomain3dValidData.exnode"); TS_ASSERT(comparer3.CompareFiles()); //Info file FileComparison comparer4(results_dir + "/monodomain3d_times.info", "heart/test/data/CmguiData/monodomain/monodomain3dValidData_times.info"); TS_ASSERT(comparer4.CompareFiles()); //HeartConfig XML TS_ASSERT(FileFinder(results_dir + "ChasteParameters.xml").Exists()); #ifdef CHASTE_VTK // Requires "sudo aptitude install libvtk5-dev" or similar results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "MonodomainCreatesGeometry/vtk_output/"; VtkMeshReader<3, 3> mesh_reader(results_dir + "monodomain3d.vtu"); TS_ASSERT_EQUALS(mesh_reader.GetNumNodes(), 1331U); TS_ASSERT_EQUALS(mesh_reader.GetNumElements(), 6000U); std::vector<double> first_node = mesh_reader.GetNextNode(); TS_ASSERT_DELTA(first_node[0], 0.0, 1e-6); TS_ASSERT_DELTA(first_node[1], 0.0, 1e-6); TS_ASSERT_DELTA(first_node[2], 0.0, 1e-6); std::vector<double> next_node = mesh_reader.GetNextNode(); TS_ASSERT_DELTA(next_node[0], 0.01, 1e-6); TS_ASSERT_DELTA(next_node[1], 0.0, 1e-6); TS_ASSERT_DELTA(next_node[2], 0.0, 1e-6); //Last time step and midway time step for V_m std::vector<double> v_at_last, v_at_100; mesh_reader.GetPointData("V_000100", v_at_100); TS_ASSERT_DELTA(v_at_100[0], 48.0637, 1e-3); TS_ASSERT_DELTA(v_at_100[665], 26.5404, 1e-3); TS_ASSERT_DELTA(v_at_100[1330], -55.3058, 1e-3); mesh_reader.GetPointData("V_000200", v_at_last); TS_ASSERT_DELTA(v_at_last[0], 31.8730, 1e-3); TS_ASSERT_DELTA(v_at_last[665], 32.6531, 1e-3); TS_ASSERT_DELTA(v_at_last[1330], 34.5152, 1e-3); //HeartConfig XML TS_ASSERT(FileFinder(results_dir + "ChasteParameters.xml").Exists()); #else std::cout << "This test ran, but did not test VTK-dependent functions as VTK visualization is not enabled." << std::endl; std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl; #endif //CHASTE_VTK } // Test the functionality for outputing the values of requested cell state variables void TestMonodomainProblemPrintsMultipleVariables() { // Set configuration file HeartConfig::Instance()->SetParametersFile("heart/test/data/xml/MultipleVariablesMonodomain.xml"); // Set up problem PlaneStimulusCellFactory<CellFaberRudy2000FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); // Solve monodomain_problem.Initialise(); monodomain_problem.Solve(); // Get a reference to a reader object for the simulation results Hdf5DataReader data_reader1 = monodomain_problem.GetDataReader(); std::vector<double> times = data_reader1.GetUnlimitedDimensionValues(); // Check there is information about 101 timesteps (0, 0.01, 0.02, ...) TS_ASSERT_EQUALS(times.size(), 11u); TS_ASSERT_DELTA(times[0], 0.0, 1e-12); TS_ASSERT_DELTA(times[1], 0.01, 1e-12); TS_ASSERT_DELTA(times[2], 0.02, 1e-12); TS_ASSERT_DELTA(times[3], 0.03, 1e-12); // There should be 101 values per variable and node. std::vector<double> node_5_v = data_reader1.GetVariableOverTime("V", 5); TS_ASSERT_EQUALS(node_5_v.size(), 11u); std::vector<double> node_5_cai = data_reader1.GetVariableOverTime("cytosolic_calcium_concentration", 5); TS_ASSERT_EQUALS(node_5_cai.size(), 11U); std::vector<double> node_5_nai = data_reader1.GetVariableOverTime("ionic_concentrations__Nai", 5); TS_ASSERT_EQUALS(node_5_nai.size(), 11U); std::vector<double> node_5_ki = data_reader1.GetVariableOverTime("ionic_concentrations__Ki", 5); TS_ASSERT_EQUALS(node_5_ki.size(), 11U); } void TestMonodomainProblemExceptions() { HeartConfig::Instance()->SetSimulationDuration(1.0); //ms TS_ASSERT_THROWS_THIS(MonodomainProblem<1> monodomain_problem(NULL), "AbstractCardiacProblem: Please supply a cell factory pointer to your cardiac problem constructor."); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); // Throws because we've not called initialise TS_ASSERT_THROWS_THIS(monodomain_problem.Solve(), "Cardiac tissue is null, Initialise() probably hasn\'t been called"); // Throws because mesh filename is unset TS_ASSERT_THROWS_CONTAINS(monodomain_problem.Initialise(), "No mesh given: define it in XML parameters file or call SetMesh()\n" "No XML element Simulation/Mesh found in parameters when calling"); // Throws because initialise hasn't been called TS_ASSERT_THROWS_THIS(monodomain_problem.Solve(), "Cardiac tissue is null, Initialise() probably hasn\'t been called"); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory(""); HeartConfig::Instance()->SetOutputFilenamePrefix(""); monodomain_problem.Initialise(); //Throws because the HDF5 slab isn't on the disk TS_ASSERT_THROWS_THIS(monodomain_problem.GetDataReader(), "Data reader invalid as data writer cannot be initialised"); // throw because end time is negative HeartConfig::Instance()->SetSimulationDuration(-1.0); //ms TS_ASSERT_THROWS_THIS(monodomain_problem.Solve(), "End time should be in the future"); HeartConfig::Instance()->SetSimulationDuration(1.0); //ms // throws because output dir and filename are both "" TS_ASSERT_THROWS_THIS(monodomain_problem.Solve(), "Either explicitly specify not to print output (call PrintOutput(false)) or " "specify the output directory and filename prefix"); // Throws because can't open the results file std::string directory("UnwriteableFolder"); HeartConfig::Instance()->SetOutputDirectory(directory); HeartConfig::Instance()->SetOutputFilenamePrefix("results"); OutputFileHandler handler(directory, false); if (PetscTools::AmMaster()) { chmod(handler.GetOutputDirectoryFullPath().c_str(), CHASTE_READ_EXECUTE); } H5E_BEGIN_TRY //Suppress HDF5 error in this test { TS_ASSERT_THROWS_THIS(monodomain_problem.Solve(), "Hdf5DataWriter could not create " + handler.GetOutputDirectoryFullPath() + "results.h5 , H5Fcreate error code = -1"); } H5E_END_TRY; if (PetscTools::AmMaster()) { chmod(handler.GetOutputDirectoryFullPath().c_str(), CHASTE_READ_WRITE_EXECUTE); } } /** * Not a very thorough test yet - just checks we can load a problem, simulate it, and * get expected results. * * This test relies on the h5 file generated in TestMonodomainProblem1D. Always run after! */ void TestArchiving() { // Based on TestMonodomainProblem1D() FileFinder archive_dir("monodomain_problem_archive", RelativeTo::ChasteTestOutput); std::string archive_file = "monodomain_problem.arch"; // Values to test against after load unsigned num_cells; // Save { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblemArchive"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); // Set extra variables (to cover extension of HDF5 with named variables) - in a later test std::vector<std::string> output_variables; output_variables.push_back("cytosolic_calcium_concentration"); output_variables.push_back("potassium_currents"); HeartConfig::Instance()->SetOutputVariables(output_variables); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSimulationDuration(1.0); //ms monodomain_problem.Solve(); num_cells = monodomain_problem.GetTissue()->rGetCellsDistributed().size(); ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file); boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive(); AbstractCardiacProblem<1, 1, 1>* const p_monodomain_problem = &monodomain_problem; (*p_arch) & p_monodomain_problem; } // Load { ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file); boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive(); AbstractCardiacProblem<1, 1, 1>* p_monodomain_problem; (*p_arch) >> p_monodomain_problem; // Check values TS_ASSERT_EQUALS(p_monodomain_problem->GetTissue()->rGetCellsDistributed().size(), num_cells); TS_ASSERT(!p_monodomain_problem->mUseHdf5DataWriterCache); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms p_monodomain_problem->Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(static_cast<MonodomainProblem<1, 1>&>(*p_monodomain_problem)); // check some voltages ReplicatableVector voltage_replicated(p_monodomain_problem->GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { //Shouldn't differ from the original run at all TS_ASSERT_DELTA(voltage_replicated[index], mVoltageReplicated1d2ms[index], 5e-11); } // check a progress report exists OutputFileHandler handler("MonoProblemArchive", false); TS_ASSERT(handler.FindFile("progress_status.txt").Exists()); // check output file contains results for the whole simulation TS_ASSERT(CompareFilesViaHdf5DataReader("MonoProblemArchive", "MonodomainLR91_1d", true, "MonoProblem1d", "MonodomainLR91_1d", true)); // Free memory delete p_monodomain_problem; } } /** * Same as TestMonodomainProblem1D, except run the simulation in 2 halves: first to 1ms, * then continue to 2ms. * * This test relies on the h5 file generated in TestMonodomainProblem1D. Always run after! */ void TestMonodomainProblem1dInTwoHalves() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005)); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem1dInTwoHalves"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d"); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); // Set extra variables (to cover extension of HDF5 with named variables) std::vector<std::string> output_variables; output_variables.push_back("cytosolic_calcium_concentration"); output_variables.push_back("potassium_currents"); HeartConfig::Instance()->SetOutputVariables(output_variables); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSimulationDuration(1.0); //ms monodomain_problem.Solve(); ReplicatableVector voltage_replicated_midway(monodomain_problem.GetSolution()); HeartConfig::Instance()->SetSimulationDuration(2.0); //ms monodomain_problem.Solve(); // test whether voltages and gating variables are in correct ranges CheckMonoLr91Vars<1>(monodomain_problem); // check some voltages ReplicatableVector voltage_replicated(monodomain_problem.GetSolution()); double atol = 5e-3; TS_ASSERT_DELTA(voltage_replicated[1], 20.7710232, atol); TS_ASSERT_DELTA(voltage_replicated[3], 21.5319692, atol); TS_ASSERT_DELTA(voltage_replicated[5], 22.9280817, atol); TS_ASSERT_DELTA(voltage_replicated[7], 24.0611303, atol); TS_ASSERT_DELTA(voltage_replicated[9], -0.770330519, atol); TS_ASSERT_DELTA(voltage_replicated[10], -19.2234919, atol); for (unsigned index = 0; index < voltage_replicated.GetSize(); index++) { TS_ASSERT_DELTA(voltage_replicated[index], mVoltageReplicated1d2ms[index], 5e-11); } // check output file contains results for the whole simulation and agree with normal test TS_ASSERT(CompareFilesViaHdf5DataReader("MonoProblem1dInTwoHalves", "MonodomainLR91_1d", true, "MonoProblem1d", "MonodomainLR91_1d", true)); } void TestMonodomain2dOriginalPermutationInParallel() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(0.5); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem2dOriginalPermutation"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_2d"); HeartConfig::Instance()->SetOutputUsingOriginalNodeOrdering(true); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory; // using the criss-cross mesh so wave propagates properly MonodomainProblem<2> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(); HeartConfig::Instance()->SetVisualizeWithVtk(); HeartConfig::Instance()->SetVisualizeWithCmgui(); monodomain_problem.Solve(); // The following lines check that the output is always in the same permutation // order, regardless of whether it has been permuted internally. // In sequential mode, no permutation is applied if (PetscTools::IsSequential()) { TS_ASSERT_EQUALS(HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering(), false); } else { // In parallel the mesh in memory has been permuted. Will check the output has been unpermuted. TS_ASSERT_EQUALS(HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering(), true); } OutputFileHandler handler("MonoProblem2dOriginalPermutation/", false); //Note that without the "SetOutputUsingOriginalNodeOrdering" above the following would fail //since METIS partitioning will have changed the permutation /* * Meshalyzer format */ //Mesh FileComparison comparer(handler.GetOutputDirectoryFullPath() + "/output/MonodomainLR91_2d_mesh.pts", "heart/test/data/MonoProblem2dOriginalPermutation/MonodomainLR91_2d_mesh.pts"); TS_ASSERT(comparer.CompareFiles()); //Transmembrane std::string file1 = handler.GetOutputDirectoryFullPath() + "/output/MonodomainLR91_2d_V.dat"; std::string file2 = "heart/test/data/MonoProblem2dOriginalPermutation/MonodomainLR91_2d_V.dat"; NumericFileComparison comp(file1, file2); TS_ASSERT(comp.CompareFiles(1e-3)); //This can be quite flexible since the permutation differences will be quite large /* * Cmgui format */ //Mesh FileComparison comparer2(handler.GetOutputDirectoryFullPath() + "/cmgui_output/MonodomainLR91_2d.exnode", "heart/test/data/MonoProblem2dOriginalPermutation/MonodomainLR91_2d.exnode"); TS_ASSERT(comparer2.CompareFiles()); //Transmembrane file1 = handler.GetOutputDirectoryFullPath() + "/cmgui_output/MonodomainLR91_2d_50.exnode"; file2 = "heart/test/data/MonoProblem2dOriginalPermutation/MonodomainLR91_2d_50.exnode"; NumericFileComparison comp_cmgui(file1, file2); TS_ASSERT(comp_cmgui.CompareFiles(1e-3)); //This can be quite flexible since the permutation differences will be quite large /* * Vtk Format */ #ifdef CHASTE_VTK // Read in a VTKUnstructuredGrid as a mesh VtkMeshReader<2, 2> mesh_reader(handler.GetOutputDirectoryFullPath() + "vtk_output/MonodomainLR91_2d.vtu"); TS_ASSERT_EQUALS(mesh_reader.GetNumNodes(), 221U); TS_ASSERT_EQUALS(mesh_reader.GetNumElements(), 400U); TS_ASSERT_EQUALS(mesh_reader.GetNumFaces(), 40U); std::vector<double> first_node = mesh_reader.GetNextNode(); TS_ASSERT_DELTA(first_node[0], 0.0, 1e-6); TS_ASSERT_DELTA(first_node[1], 0.0, 1e-6); TS_ASSERT_DELTA(first_node[2], 0.0, 1e-6); std::vector<double> next_node = mesh_reader.GetNextNode(); TS_ASSERT_DELTA(next_node[0], 0.01, 1e-6); TS_ASSERT_DELTA(next_node[1], 0.0, 1e-6); TS_ASSERT_DELTA(next_node[2], 0.0, 1e-6); //Last time step V_m std::vector<double> v_at_last; mesh_reader.GetPointData("V_000050", v_at_last); TS_ASSERT_DELTA(v_at_last[0], 13.146, 1e-3); TS_ASSERT_DELTA(v_at_last[110], 13.146, 1e-3); TS_ASSERT_DELTA(v_at_last[220], -83.855, 1e-3); #else std::cout << "This test ran, but did not test VTK-dependent functions as VTK visualization is not enabled." << std::endl; std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl; #endif //CHASTE_VTK } /** * Run same setup as above, but this time only outputting at a certain node */ void TestMonodomain2dOutputAtSpecificNodes() { HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(0.5); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); HeartConfig::Instance()->SetOutputDirectory("MonoProblem2dSpecificNode"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_2d_specific_node"); HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory; // Check an exception for coverage { MonodomainProblem<2> monodomain_problem_fail(&cell_factory); // Check output at specific nodes in parallel std::vector<unsigned> output_node; output_node.push_back(10); monodomain_problem_fail.SetOutputNodes(output_node); monodomain_problem_fail.Initialise(); if (monodomain_problem_fail.rGetMesh().rGetNodePermutation().size() > 0) { HeartConfig::Instance()->SetOutputUsingOriginalNodeOrdering(true); // TS_ASSERT_THROWS_THIS(monodomain_problem_fail.Solve(), "HeartConfig setting `GetOutputUsingOriginalNodeOrdering` is meaningless when outputting particular nodes in parallel. (Nodes are written with their original indices by default)."); HeartConfig::Instance()->SetOutputUsingOriginalNodeOrdering(false); // } } MonodomainProblem<2> monodomain_problem(&cell_factory); // Check output at specific nodes in parallel std::vector<unsigned> output_nodes; unsigned my_favourite_node1 = 123u; unsigned my_other_node = 205u; unsigned my_favourite_node2 = 219u; output_nodes.push_back(my_favourite_node1); output_nodes.push_back(my_other_node); output_nodes.push_back(my_favourite_node2); // sequential {123,205,219} // 2 procs: {174,211,106} (not increasing) // 3 procs: {47,211,150} (not increasing) monodomain_problem.SetOutputNodes(output_nodes); monodomain_problem.Initialise(); monodomain_problem.Solve(); Hdf5DataReader reader("MonoProblem2dSpecificNode", "MonodomainLR91_2d_specific_node", true); std::vector<unsigned> permuted_nodes = reader.GetIncompleteNodeMap(); TS_ASSERT_EQUALS(permuted_nodes.size(), 3u); std::vector<double> right_answer1{ -83.853, -83.8535, -83.8572, -83.8647, -83.8722, -83.8739, -83.8642, -83.8389, -83.7954, -83.7321, -83.6485, -83.5446, -83.4211, -83.2788, -83.1186, -82.9416, -82.749, -82.5418, -82.321, -82.0877, -81.8427, -81.587, -81.3213, -81.0464, -80.763, -80.4716, -80.1727, -79.8668, -79.5543, -79.2354, -78.9103, -78.5791, -78.2418, -77.8984, -77.5484, -77.1917, -76.8276, -76.4555, -76.0744, -75.6833, -75.2809, -74.8655, -74.4354, -73.9883, -73.5218, -73.0331, -72.5191, -71.9766, -71.402, -70.7915, -70.1413 }; std::vector<double> our_answer1 = reader.GetVariableOverTime("V", my_favourite_node1); for (unsigned i = 0; i < right_answer1.size(); i++) { TS_ASSERT_DELTA(our_answer1[i], right_answer1[i], 2e-4); } std::vector<double> our_answer2 = reader.GetVariableOverTime("V", my_favourite_node2); for (unsigned i = 0; i < our_answer2.size(); i++) { TS_ASSERT_DELTA(our_answer2[i], -83.85, 1e-2); } } void TestOutputDoesNotDependOnPrintTimestep() { #ifdef CHASTE_CVODE // Switch this back on to watch linear solver converge on each step. //PetscTools::SetOption("-ksp_monitor", ""); // Make sure that this test isn't having problems because of PDE tolerances. HeartConfig::Instance()->SetUseAbsoluteTolerance(1e-12); const double mesh_spacing = 0.01; const double x_size = 1.0; DistributedTetrahedralMesh<1, 1> mesh; mesh.ConstructRegularSlabMesh(mesh_spacing, x_size); const unsigned max_node_index = mesh.GetNumNodes() - 1; Cvode1dCellFactory cell_factory; HeartConfig::Instance()->SetSimulationDuration(10.0); //ms HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(2.0)); // Test two values of print timestep const unsigned num_print_steps_to_test = 2u; c_vector<double, num_print_steps_to_test> print_steps = Create_c_vector(0.1, 0.01); // Always use the same ODE and PDE timestep of 0.01. const double ode_and_pde_steps = 0.01; //ms for (unsigned i = 0; i < num_print_steps_to_test; ++i) { std::stringstream str_stream; str_stream << print_steps[i]; HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d_" + str_stream.str()); HeartConfig::Instance()->SetOutputDirectory("TestCvodePrintTimestepDependence" + str_stream.str()); HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(ode_and_pde_steps, ode_and_pde_steps, print_steps[i]); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(); MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.SetMesh(&mesh); //monodomain_problem.SetWriteInfo(); //Uncomment for progress monodomain_problem.Initialise(); monodomain_problem.Solve(); for (AbstractTetrahedralMesh<1, 1>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { AbstractCardiacCellInterface* p_cell = monodomain_problem.GetTissue()->GetCardiacCell(node_iter->GetIndex()); // This checks the maximum timestep in each Cvode cell has been set correctly. TS_ASSERT_EQUALS(static_cast<AbstractCvodeCell*>(p_cell)->GetTimestep(), ode_and_pde_steps); } } // Read results in and compare std::vector<double> V_to_compare; for (unsigned i = 0; i < num_print_steps_to_test; ++i) { std::stringstream str_stream; str_stream << print_steps[i]; Hdf5DataReader simulation_data("TestCvodePrintTimestepDependence" + str_stream.str(), "MonodomainLR91_1d_" + str_stream.str()); std::vector<double> V_over_time = simulation_data.GetVariableOverTime("V", max_node_index); V_to_compare.push_back(V_over_time.back()); // Voltage at final time. } std::cout << "Difference in printing time steps of " << print_steps[0] << " and " << print_steps[1] << " = " << V_to_compare[0] - V_to_compare[1] << " mV" << std::endl; // N.B. This tolerance can be reduced to less than 1e-6 if you reduce the ODE+PDE time step to 0.001 instead of 0.01ms. // This would be unfeasibly small for 'proper' simulations though, so not sure how to proceed with this! TS_ASSERT_DELTA(V_to_compare[0], V_to_compare[1], 4e-3); #else std::cout << "Chaste is not configured to use CVODE on this machine, check your hostconfig settings if required.\n"; #endif // CHASTE_CVODE } /* * This test is to try to trigger a CVODE error by changing voltage too much * at the start of its solve, so that it fails to find an ODE solution that is * sufficiently converged. * * It covers code that we have introduced for #2594, see that for more details. */ void TestCvodeErrorHandling() { #ifdef CHASTE_CVODE std::cout << "Don't worry about a few errors below here, we are testing that we can recover from them!" << std::endl; const double mesh_spacing = 0.1; const double x_size = 1.0; DistributedTetrahedralMesh<1, 1> mesh; mesh.ConstructRegularSlabMesh(mesh_spacing, x_size); Cvode1dCellFactory cell_factory; double all_steps = 1.0; HeartConfig::Instance()->SetSimulationDuration(3); //ms HeartConfig::Instance()->SetOutputDirectory("TestCvodeInTissueErrorHandling"); HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(all_steps, all_steps, all_steps); MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.SetMesh(&mesh); monodomain_problem.Initialise(); monodomain_problem.Solve(); #else std::cout << "Chaste is not configured to use CVODE on this machine, check your hostconfig settings if required.\n"; #endif // CHASTE_CVODE } void TestArchivingOfSingleTraceOutputModifier() { OutputFileHandler handler("TestArchivingOfSingleTraceOutputModifier", false); // The next two lines ensure that different processes read/write different archive files when running in parallel ArchiveLocationInfo::SetArchiveDirectory(handler.FindFile("")); std::string archive_filename = ArchiveLocationInfo::GetProcessUniqueFilePath("SingleTraceOutputModifier.arch"); // Create data structures to store variables to test for equality here // Save { AbstractOutputModifier* const p_abstract_class = new SingleTraceOutputModifier("SomeFileName", 123, 3.142); // Create an output file std::ofstream ofs(archive_filename.c_str()); // And create a boost output archive that goes to this file boost::archive::text_oarchive output_arch(ofs); // Record values to test into data structures // If necessary you can use static_cast<ConcreteClass*>(p_abstract_class) // (if your abstract class doesn't contain the necessary variables and methods) output_arch << p_abstract_class; delete p_abstract_class; } // Load { AbstractOutputModifier* p_abstract_class_2; // Read from this input file std::ifstream ifs(archive_filename.c_str(), std::ios::binary); // And choose a boost input_archive object to translate this file boost::archive::text_iarchive input_arch(ifs); // restore from the archive input_arch >> p_abstract_class_2; // Check things in the data structures with TS_ASSERTS here. // If necessary you can use static_cast<ConcreteClass*>(p_abstract_class_2) // (if your abstract class doesn't contain the necessary variables and methods) TS_ASSERT_EQUALS(p_abstract_class_2->mFilename, "SomeFileName"); SingleTraceOutputModifier* p_concrete_class = static_cast<SingleTraceOutputModifier*>(p_abstract_class_2); TS_ASSERT_EQUALS(p_concrete_class->mGlobalIndex, 123u); TS_ASSERT_DELTA(p_abstract_class_2->mFlushTime, 3.142, 1e-3); delete p_abstract_class_2; } } void TestMonodomainProblem2DWithArchiving() { // Names of output and archive directories std::string output_dir = "MonodomainProblem2DWithArchiving_Parallel"; std::string archive_location_1 = output_dir + "/" + "monodomain_2d_archive_1"; std::string archive_location_2 = output_dir + "/" + "monodomain_2d_archive_2"; std::string archive_location_3 = output_dir + "/" + "monodomain_2d_archive_3"; // Do first stage of simulation { // Standard HeartConfig set-up HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(0.0005, 0.0005)); HeartConfig::Instance()->SetSimulationDuration(.5); //ms HeartConfig::Instance()->SetMeshFileName("mesh/test/data/2D_0_to_1mm_400_elements"); HeartConfig::Instance()->SetOutputDirectory(output_dir); HeartConfig::Instance()->SetOutputFilenamePrefix(output_dir); HeartConfig::Instance()->SetVisualizeWithMeshalyzer(); HeartConfig::Instance()->SetVisualizeWithVtk(); HeartConfig::Instance()->SetVisualizeWithParallelVtk(); HeartConfig::Instance()->SetOutputUsingOriginalNodeOrdering(true); // Use cell factory to create monodomain problem PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 2> cell_factory; MonodomainProblem<2> monodomain_problem(&cell_factory); monodomain_problem.Initialise(); monodomain_problem.SetUseHdf5DataWriterCache(true); // cache on, for coveraging of archiving this HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1.0); HeartConfig::Instance()->SetCapacitance(1.0); { // Add output modifiers boost::shared_ptr<SingleTraceOutputModifier> trace_5(new SingleTraceOutputModifier("trace_5.txt", 5)); boost::shared_ptr<ActivationOutputModifier> activation(new ActivationOutputModifier("activation.txt", 0.0)); TS_ASSERT_EQUALS(monodomain_problem.mOutputModifiers.size(), 0u); monodomain_problem.AddOutputModifier(trace_5); monodomain_problem.AddOutputModifier(activation); TS_ASSERT_EQUALS(monodomain_problem.mOutputModifiers.size(), 2u); TS_ASSERT_EQUALS(monodomain_problem.mOutputModifiers[0]->mFilename, "trace_5.txt"); TS_ASSERT_EQUALS(monodomain_problem.mOutputModifiers[1]->mFilename, "activation.txt"); } // Solve and save monodomain_problem.Solve(); CardiacSimulationArchiver<MonodomainProblem<2> >::Save(monodomain_problem, archive_location_1); } // Second stage - load from archive and run for an extra time before saving again { // Load and run - first go MonodomainProblem<2>* p_monodomain_problem = CardiacSimulationArchiver<MonodomainProblem<2> >::Load(archive_location_1); HeartConfig::Instance()->SetSimulationDuration(1.0); //ms TS_ASSERT(p_monodomain_problem->mUseHdf5DataWriterCache); p_monodomain_problem->Solve(); CardiacSimulationArchiver<MonodomainProblem<2> >::Save(*p_monodomain_problem, archive_location_2); delete p_monodomain_problem; } // Third stage - repeat procedure from second { // Load and run - second go MonodomainProblem<2>* p_monodomain_problem = CardiacSimulationArchiver<MonodomainProblem<2> >::Load(archive_location_2); HeartConfig::Instance()->SetSimulationDuration(1.5); //ms TS_ASSERT(p_monodomain_problem->mUseHdf5DataWriterCache); p_monodomain_problem->Solve(); { // Check that the modifiers are still there TS_ASSERT_EQUALS(p_monodomain_problem->mOutputModifiers.size(), 2u); TS_ASSERT_EQUALS(p_monodomain_problem->mOutputModifiers[0]->mFilename, "trace_5.txt"); TS_ASSERT_EQUALS(p_monodomain_problem->mOutputModifiers[1]->mFilename, "activation.txt"); } CardiacSimulationArchiver<MonodomainProblem<2> >::Save(*p_monodomain_problem, archive_location_3); delete p_monodomain_problem; } // Compare file (possibly produced in parallel) with the original sequential ordering OutputFileHandler handler(output_dir, false); std::string file1 = handler.GetOutputDirectoryFullPath() + "/output/" + output_dir + "_V.dat"; std::string file2 = "heart/test/data/MonoProblem2dOriginalPermutation/AfterArchivingTwice_V.dat"; NumericFileComparison comp_meshalyzer_original_order(file1, file2); TS_ASSERT(comp_meshalyzer_original_order.CompareFiles(1e-3)); } /* * HOW_TO_TAG Cardiac/Output * On large-scale parallel simulations it is advantageous to cache HDF5 output and only * write to disk at end of simulation (or at checkpoint). This is achieved with `SetUseHdf5DataWriterCache()` */ void TestMonodomainProblemWithWriterCache() { HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(0.01, 0.01, 0.01); HeartConfig::Instance()->SetSimulationDuration(1.0); HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonodomainWithWriterCache"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d_with_cache"); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.SetUseHdf5DataWriterCache(true); // cache on monodomain_problem.Initialise(); monodomain_problem.Solve(); TS_ASSERT(monodomain_problem.mUseHdf5DataWriterCache); TS_ASSERT(CompareFilesViaHdf5DataReader("MonodomainWithWriterCache", "MonodomainLR91_1d_with_cache", true, "heart/test/data/MonodomainWithWriterCache", "MonodomainLR91_1d_with_cache", false, 2e-4)); } void TestMonodomainProblemWithWriterCacheIncomplete() { HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements"); HeartConfig::Instance()->SetOutputDirectory("MonodomainWithWriterCacheIncomplete"); HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d_with_cache_incomplete"); HeartConfig::Instance()->SetSimulationDuration(1.0); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory; MonodomainProblem<1> monodomain_problem(&cell_factory); monodomain_problem.SetUseHdf5DataWriterCache(true); // cache on std::vector<unsigned> nodes_to_be_output; nodes_to_be_output.push_back(0); nodes_to_be_output.push_back(5); nodes_to_be_output.push_back(10); monodomain_problem.SetOutputNodes(nodes_to_be_output); monodomain_problem.Initialise(); monodomain_problem.Solve(); TS_ASSERT(monodomain_problem.mUseHdf5DataWriterCache); TS_ASSERT(CompareFilesViaHdf5DataReader("MonodomainWithWriterCacheIncomplete", "MonodomainLR91_1d_with_cache_incomplete", true, "heart/test/data/MonodomainWithWriterCache", "MonodomainLR91_1d_with_cache_incomplete", false, 1e-4)); } void TestMonodomainProblemWithTargetChunkSizeAndAlignment() { { DistributedTetrahedralMesh<3, 3> mesh; mesh.ConstructRegularSlabMesh(0.01, 0.42, 0.12, 0.03); HeartConfig::Instance()->SetOutputDirectory("MonodomainWithTargetChunkSizeAndAlignment"); HeartConfig::Instance()->SetOutputFilenamePrefix("results"); HeartConfig::Instance()->SetSimulationDuration(10.0); // Some postprocessing to test passing chunk size through to PostProcessingWriter std::vector<double> upstroke_voltages; upstroke_voltages.push_back(0.0); HeartConfig::Instance()->SetUpstrokeTimeMaps(upstroke_voltages); PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 3> cell_factory(-600 * 5000); MonodomainProblem<3> monodomain_problem(&cell_factory); monodomain_problem.SetMesh(&mesh); monodomain_problem.SetHdf5DataWriterTargetChunkSizeAndAlignment(0x2000); // 8 K monodomain_problem.Initialise(); monodomain_problem.Solve(); CardiacSimulationArchiver<MonodomainProblem<3> >::Save(monodomain_problem, "MonodomainWithTargetChunkSizeAndAlignment/checkpoint"); } // Open file OutputFileHandler file_handler("MonodomainWithTargetChunkSizeAndAlignment", false); FileFinder file = file_handler.FindFile("results.h5"); hid_t h5_file = H5Fopen(file.GetAbsolutePath().c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); /* Need this next line as using the 1.8 API in this test suite * (haven't explicitly included AbstractHdf5Access.hpp) */ hid_t dset = H5Dopen(h5_file, "Data", H5P_DEFAULT); // open dataset hid_t dcpl = H5Dget_create_plist(dset); // get dataset creation property list /* Check chunk dimensions */ hsize_t expected_dims[3] = { 32, 32, 1 }; //(exactly 8K!) hsize_t chunk_dims[3]; H5Pget_chunk(dcpl, 3, chunk_dims); for (int i = 0; i < 3; ++i) { TS_ASSERT_EQUALS(chunk_dims[i], expected_dims[i]); } /* * Check the "location" of the datasets (the offset from the start of * file, a bit like a pointer to the start of the dataset) to get a * hint that alignment was switched on. It's not the most specific * test but I can't think of a better way. * (These numbers might be machine-dependent!) */ H5O_info_t data_info; H5Oget_info(dset, &data_info); TS_ASSERT_EQUALS(data_info.addr, 0x8000u); // 32 KB H5Dclose(dset); dset = H5Dopen(h5_file, "Data_Unlimited", H5P_DEFAULT); H5Oget_info(dset, &data_info); TS_ASSERT_EQUALS(data_info.addr, 18735104u); // About 17.8 MB H5Dclose(dset); dset = H5Dopen(h5_file, "UpstrokeTimeMap_0", H5P_DEFAULT); H5Oget_info(dset, &data_info); TS_ASSERT_EQUALS(data_info.addr, 18809856u); // About 17.9 MB // And chunk dims for this one hsize_t expected_dims_upstroke[3] = { 1, 746, 1 }; dcpl = H5Dget_create_plist(dset); // get dataset creation property list H5Pget_chunk(dcpl, 3, chunk_dims); for (int i = 0; i < 3; ++i) { TS_ASSERT_EQUALS(chunk_dims[i], expected_dims_upstroke[i]); } // Close H5Dclose(dset); H5Fclose(h5_file); } void TestResumeMonodomainProblemWithTargetChunkSizeAndAlignment() { // Resume from previous test { MonodomainProblem<3>* p_monodomain_problem = CardiacSimulationArchiver<MonodomainProblem<3> >::Load("MonodomainWithTargetChunkSizeAndAlignment/checkpoint"); HeartConfig::Instance()->SetSimulationDuration(11.0); std::vector<double> upstroke_voltages; upstroke_voltages.push_back(3.0); HeartConfig::Instance()->SetUpstrokeTimeMaps(upstroke_voltages); p_monodomain_problem->Solve(); //Tidy up delete p_monodomain_problem; } /* Check new dataset has the right chunk dims. This will confirm that * the option was unarchived properly and that it works correctly when * adding a new dataset to an existing file. */ // Open file OutputFileHandler file_handler("MonodomainWithTargetChunkSizeAndAlignment", false); FileFinder file = file_handler.FindFile("results.h5"); TS_ASSERT(file.IsFile()); hid_t h5_file = H5Fopen(file.GetAbsolutePath().c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); hid_t dapl = H5Pcreate(H5P_DATASET_ACCESS); hid_t dset = H5Dopen(h5_file, "UpstrokeTimeMap_3", dapl); // open dataset hid_t dcpl = H5Dget_create_plist(dset); // get dataset creation property list // Check chunk dimensions hsize_t expected_dims[3] = { 1, 746, 1 }; hsize_t chunk_dims[3]; H5Pget_chunk(dcpl, 3, chunk_dims); for (int i = 0; i < 3; ++i) { TS_ASSERT_EQUALS(chunk_dims[i], expected_dims[i]); } // Check location H5O_info_t data_info; H5Oget_info(dset, &data_info); TS_ASSERT_DELTA(data_info.addr, 20567968u, 41u); // About 19.6 MB with a little leeway H5Dclose(dset); H5Fclose(h5_file); } }; #endif //_TESTMONODOMAINPROBLEM_HPP_
b31f4e12d0483f1904700de9ede7a641fd20ae34
7e45abc2361dd4cb31474b4442f93aef4b833d8a
/QT/day05/exec03/Test/mainwindow.cpp
e979709770f2df6a07d770a791ac7ee35e3d4724
[]
no_license
qyqgit/MyDoc
187da579fc920f9f9e2bd238cfa11387060eeb57
92f23732efa2ada09a4311520ebd1c8fd3e86e86
refs/heads/master
2020-06-12T05:40:27.691706
2019-11-17T08:49:44
2019-11-17T08:49:44
194,210,236
0
0
null
null
null
null
UTF-8
C++
false
false
601
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QPainter> #include <QRect> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mrc = new MyRect(); clock = startTimer(1000); } MainWindow::~MainWindow() { delete ui; } void MainWindow::paintEvent(QPaintEvent *){ qDebug() << "paint"; QPainter painter(this); mrc->showMrc(&painter); } void MainWindow::timerEvent(QTimerEvent *){ this->update(); mrc->moveMrc(0,0); mrc->resizeMrc(100,100); mrc->setTextMrc("sss"); }
4a0f61006a720ef12e6e677429276cc0320eaa48
f2f70ca3e14bf57d9ef2d573ec4c946e4c289724
/Mainfrm.cpp
0081fec0b013cd991320ad4ae09f21ce001de3e2
[]
no_license
KB3NZQ/hexedit4
a746a46a25537cf88278a5bc863cbeaae2e8b41c
39d64bf320a7712f7cc275d574598ab0a3f1d1f3
refs/heads/master
2021-01-22T13:42:55.317318
2014-08-02T16:26:53
2014-08-02T16:26:53
22,550,304
1
1
null
null
null
null
UTF-8
C++
false
false
163,736
cpp
Mainfrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // // Copyright (c) 2011 by Andrew W. Phillips. // // This file is distributed under the MIT license, which basically says // you can do what you want with it but I take no responsibility for bugs. // See http://www.opensource.org/licenses/mit-license.php for full details. // #include "stdafx.h" #include <io.h> // For _access() #include <MultiMon.h> #include <imagehlp.h> // For ::MakeSureDirectoryPathExists() #include <afxpriv.h> // for WM_COMMANDHELP #include "HexEdit.h" #include "ChildFrm.h" #include "HexEditDoc.h" #include "HexEditView.h" #include "MainFrm.h" #include "Bookmark.h" #include "BookmarkDlg.h" #include "BookmarkFind.h" #include "HexFileList.h" #include "Boyer.h" #include "SystemSound.h" #include "Misc.h" #include "BCGMisc.h" #include <afxribbonres.h> #include "HelpID.hm" // User defined help IDs #include "GRIDCTRL_SRC\InPlaceEdit.h" #include <HtmlHelp.h> #pragma warning(push) #pragma warning(disable:4005) #include <afxhh.h> #pragma warning(pop) extern CHexEditApp theApp; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CHexEditApp theApp; IMPLEMENT_SERIAL(CHexEditFontCombo, CMFCToolBarFontComboBox, 1) // see BCGMisc.h IMPLEMENT_SERIAL(CHexEditFontSizeCombo, CMFCToolBarFontSizeComboBox, 1) // see BCGMisc.h // We need to derive our own class from BCG customize class so we can // handle What's This help properly using Html Help. class CHexEditCustomize : public CMFCToolBarsCustomizeDialog { public: CHexEditCustomize(CFrameWnd* pParent) : CMFCToolBarsCustomizeDialog(pParent, TRUE, AFX_CUSTOMIZE_MENU_SHADOWS | AFX_CUSTOMIZE_TEXT_LABELS | AFX_CUSTOMIZE_MENU_ANIMATIONS | AFX_CUSTOMIZE_CONTEXT_HELP) { } // DECLARE_DYNAMIC(CHexEditCustomize) protected: afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); DECLARE_MESSAGE_MAP() }; //IMPLEMENT_DYNAMIC(CHexEditCustomize, CMFCToolBarsCustomizeDialog) BEGIN_MESSAGE_MAP(CHexEditCustomize, CMFCToolBarsCustomizeDialog) ON_WM_HELPINFO() END_MESSAGE_MAP() BOOL CHexEditCustomize::OnHelpInfo(HELPINFO* pHelpInfo) { #if 0 // xxx needs fix for MFC 9 CWaitCursor wait; if (::HtmlHelp((HWND)pHelpInfo->hItemHandle, theApp.htmlhelp_file_+"::BcgIdMap.txt", HH_TP_HELP_WM_HELP, (DWORD)(LPVOID)dwBCGResHelpIDs) == HWND(0)) { AfxMessageBox(AFX_IDP_FAILED_TO_LAUNCH_HELP); return FALSE; } #endif return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWndEx) // static UINT WM_FINDREPLACE = ::RegisterWindowMessage(FINDMSGSTRING); BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWndEx) ON_WM_INITMENU() //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_WM_CLOSE() ON_WM_SIZE() ON_COMMAND(ID_EDIT_FIND, OnEditFind) ON_UPDATE_COMMAND_UI(ID_EDIT_FIND, OnUpdateEditFind) ON_COMMAND(ID_EDIT_FIND2, OnEditFind2) ON_COMMAND(ID_CALCULATOR, OnCalculator) ON_COMMAND(ID_CUSTOMIZE, OnCustomize) ON_WM_HELPINFO() ON_UPDATE_COMMAND_UI(ID_EDIT_FIND2, OnUpdateEditFind) ON_WM_CONTEXTMENU() //}}AFX_MSG_MAP ON_WM_SYSCOMMAND() ON_WM_MENUSELECT() //ON_WM_ENTERIDLE() ON_COMMAND(ID_HELP_FINDER, OnHelpFinder) ON_COMMAND(ID_HELP, OnHelp) ON_COMMAND(ID_HELP_INDEX, OnHelpIndex) ON_MESSAGE(WM_COMMANDHELP, OnCommandHelp) ON_COMMAND(ID_CONTEXT_HELP, OnContextHelp) ON_COMMAND(ID_DEFAULT_HELP, OnHelpFinder) ON_COMMAND(ID_HELP_KEYBOARDMAP, OnHelpKeyboardMap) ON_COMMAND_RANGE(ID_HELP_TUTE1, ID_HELP_TUTE1+9, OnHelpTute) ON_COMMAND_EX(ID_WINDOW_ARRANGE, OnMDIWindowCmd) ON_COMMAND_EX(ID_WINDOW_CASCADE, OnMDIWindowCmd) ON_COMMAND_EX(ID_WINDOW_TILE_HORZ, OnMDIWindowCmd) ON_COMMAND_EX(ID_WINDOW_TILE_VERT, OnMDIWindowCmd) ON_COMMAND(ID_WINDOW_NEW, OnWindowNew) // Searching ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace) ON_UPDATE_COMMAND_UI(ID_EDIT_REPLACE, OnUpdateEditFind) ON_COMMAND(ID_FIND_NEXT, OnFindNext) ON_UPDATE_COMMAND_UI(ID_FIND_NEXT, OnUpdateSearch) ON_COMMAND(ID_BOOKMARK_ALL, OnBookmarkAll) ON_UPDATE_COMMAND_UI(ID_BOOKMARK_ALL, OnUpdateSearch) ON_COMMAND(ID_REPLACE, OnReplace) ON_UPDATE_COMMAND_UI(ID_REPLACE, OnUpdateSearch) ON_COMMAND(ID_REPLACE_ALL, OnReplaceAll) ON_UPDATE_COMMAND_UI(ID_REPLACE_ALL, OnUpdateSearch) ON_COMMAND(ID_SEARCH_FORW, OnSearchForw) ON_UPDATE_COMMAND_UI(ID_SEARCH_FORW, OnUpdateSearch) ON_COMMAND(ID_SEARCH_BACK, OnSearchBack) ON_UPDATE_COMMAND_UI(ID_SEARCH_BACK, OnUpdateSearch) ON_COMMAND(ID_SEARCH_SEL, OnSearchSel) ON_UPDATE_COMMAND_UI(ID_SEARCH_SEL, OnUpdateSearchSel) // ON_REGISTERED_MESSAGE(WM_FINDREPLACE, OnFindDlgMess) // Toolbars, ruler, status bar ON_COMMAND(ID_VIEW_VIEWBAR, OnViewViewbar) ON_UPDATE_COMMAND_UI(ID_VIEW_VIEWBAR, OnUpdateViewViewbar) ON_COMMAND(ID_VIEW_EDITBAR, OnViewEditbar) ON_UPDATE_COMMAND_UI(ID_VIEW_EDITBAR, OnUpdateViewEditbar) ON_COMMAND(ID_VIEW_FORMATBAR, OnViewFormatbar) ON_UPDATE_COMMAND_UI(ID_VIEW_FORMATBAR, OnUpdateViewFormatbar) ON_COMMAND(ID_VIEW_NAVBAR, OnViewNavbar) ON_UPDATE_COMMAND_UI(ID_VIEW_NAVBAR, OnUpdateViewNavbar) ON_COMMAND(ID_VIEW_CALCULATOR, OnViewCalculator) ON_UPDATE_COMMAND_UI(ID_VIEW_CALCULATOR, OnUpdateViewCalculator) ON_COMMAND(ID_VIEW_BOOKMARKS, OnViewBookmarks) ON_UPDATE_COMMAND_UI(ID_VIEW_BOOKMARKS, OnUpdateViewBookmarks) ON_COMMAND(ID_VIEW_FIND, OnViewFind) ON_UPDATE_COMMAND_UI(ID_VIEW_FIND, OnUpdateViewFind) ON_COMMAND(ID_VIEW_EXPL, OnViewExpl) ON_UPDATE_COMMAND_UI(ID_VIEW_EXPL, OnUpdateViewExpl) ON_COMMAND(ID_VIEW_RULER, OnViewRuler) ON_UPDATE_COMMAND_UI(ID_VIEW_RULER, OnUpdateViewRuler) ON_COMMAND(ID_VIEW_HL_CURSOR, OnViewHighlightCaret) ON_UPDATE_COMMAND_UI(ID_VIEW_HL_CURSOR, OnUpdateViewHighlightCaret) ON_COMMAND(ID_VIEW_HL_MOUSE, OnViewHighlightMouse) ON_UPDATE_COMMAND_UI(ID_VIEW_HL_MOUSE, OnUpdateViewHighlightMouse) ON_COMMAND(ID_VIEW_PROPERTIES, OnViewProperties) ON_UPDATE_COMMAND_UI(ID_VIEW_PROPERTIES, OnUpdateViewProperties) ON_COMMAND(ID_DIALOGS_DOCKABLE, OnDockableToggle) ON_UPDATE_COMMAND_UI(ID_DIALOGS_DOCKABLE, OnUpdateDockableToggle) ON_COMMAND_EX(ID_VIEW_STATUS_BAR, OnPaneCheck) ON_UPDATE_COMMAND_UI(ID_INDICATOR_OCCURRENCES, OnUpdateOccurrences) ON_UPDATE_COMMAND_UI(ID_INDICATOR_VALUES, OnUpdateValues) ON_UPDATE_COMMAND_UI(ID_INDICATOR_HEX_ADDR, OnUpdateAddrHex) ON_UPDATE_COMMAND_UI(ID_INDICATOR_DEC_ADDR, OnUpdateAddrDec) ON_UPDATE_COMMAND_UI(ID_INDICATOR_FILE_LENGTH, OnUpdateFileLength) ON_UPDATE_COMMAND_UI(ID_INDICATOR_BIG_ENDIAN, OnUpdateBigEndian) ON_UPDATE_COMMAND_UI(ID_INDICATOR_READONLY, OnUpdateReadonly) ON_UPDATE_COMMAND_UI(ID_INDICATOR_OVR, OnUpdateOvr) ON_UPDATE_COMMAND_UI(ID_INDICATOR_REC, OnUpdateRec) ON_REGISTERED_MESSAGE(CHexEditApp::wm_hexedit, OnOpenMsg) // MFC9 (BCG) stuff ON_REGISTERED_MESSAGE(AFX_WM_RESETTOOLBAR, OnToolbarReset) ON_REGISTERED_MESSAGE(AFX_WM_RESETMENU, OnMenuReset) //ON_REGISTERED_MESSAGE(AFX_WM_TOOLBARMENU, OnToolbarContextMenu) //ON_COMMAND_EX_RANGE(ID_VIEW_USER_TOOLBAR1, ID_VIEW_USER_TOOLBAR10, OnToolsViewUserToolbar) //ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_USER_TOOLBAR1, ID_VIEW_USER_TOOLBAR10, OnUpdateToolsViewUserToolbar) ON_REGISTERED_MESSAGE(AFX_WM_CUSTOMIZEHELP, OnHelpCustomizeToolbars) ON_COMMAND(ID_WINDOW_MANAGER, ShowWindowsDialog) // When vertically docked the combobox reverts to a button and sends this command when clicked ON_COMMAND(ID_SEARCH_COMBO, OnSearchCombo) ON_UPDATE_COMMAND_UI(ID_SEARCH_COMBO, OnUpdateSearchCombo) ON_COMMAND(ID_JUMP_HEX_COMBO, OnHexCombo) ON_UPDATE_COMMAND_UI(ID_JUMP_HEX_COMBO, OnUpdateHexCombo) ON_COMMAND(ID_JUMP_DEC_COMBO, OnDecCombo) ON_UPDATE_COMMAND_UI(ID_JUMP_DEC_COMBO, OnUpdateDecCombo) ON_COMMAND(ID_BOOKMARKS_COMBO, OnBookmarks) ON_UPDATE_COMMAND_UI(ID_BOOKMARKS_COMBO, OnUpdateBookmarksCombo) ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_OFF_2007_AQUA, &CMainFrame::OnApplicationLook) ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_OFF_2007_AQUA, &CMainFrame::OnUpdateApplicationLook) // Misc commands ON_COMMAND(ID_NAV_BACK, OnNavigateBackwards) ON_UPDATE_COMMAND_UI(ID_NAV_BACK, OnUpdateNavigateBackwards) ON_COMMAND_RANGE(ID_NAV_BACK_FIRST, ID_NAV_BACK_FIRST+NAV_RESERVED-1, OnNavBack) ON_COMMAND(ID_NAV_FORW, OnNavigateForwards) ON_UPDATE_COMMAND_UI(ID_NAV_FORW, OnUpdateNavigateForwards) ON_COMMAND_RANGE(ID_NAV_FORW_FIRST, ID_NAV_FORW_FIRST+NAV_RESERVED-1, OnNavForw) ON_REGISTERED_MESSAGE(AFX_WM_ON_GET_TAB_TOOLTIP, OnGetTabToolTip) // ON_MESSAGE(WM_USER, OnReturn) ON_COMMAND_RANGE(ID_MACRO_FIRST, ID_MACRO_LAST-1, OnMacro) ON_COMMAND(ID_TEST, OnTest) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { preview_page_ = -1; progress_on_ = false; // timer_id_ = 0; // Load background image CString filename; if (::GetDataPath(filename)) filename += FILENAME_BACKGROUND; else filename = ::GetExePath() + FILENAME_BACKGROUND; // No data path only on Win 95? CString bgfile = theApp.GetProfileString("MainFrame", "BackgroundFileName", filename); /* // Test creating a big bitmap using FreeImage m_dib = FreeImage_Allocate(1000, 200000, 24); // 200 million pixels seems to be OK!! int sz = FreeImage_GetDIBSize(m_dib); FreeImage_Unload(m_dib); m_dib = NULL; */ if ((m_dib = FreeImage_Load(FIF_BMP, bgfile)) == NULL) // MUST be 24-bit BMP file m_dib = FreeImage_Load(FIF_BMP, ::GetExePath() + FILENAME_BACKGROUND); m_background_pos = theApp.GetProfileInt("MainFrame", "BackgroundPosition", 4); // 4 = bottom-right theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_OFF_2007_BLUE); // Status bar stuff m_search_image.LoadBitmap(IDB_SEARCH); ComparesWidth = OccurrencesWidth = ValuesWidth = AddrHexWidth = AddrDecWidth = FileLengthWidth = -999; bg_progress_colour_ = -1; // History lists hex_hist_changed_ = dec_hist_changed_ = clock(); } CMainFrame::~CMainFrame() { //if (pcalc_ != NULL) // delete pcalc_; } static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_OCCURRENCES, ID_INDICATOR_VALUES, ID_INDICATOR_HEX_ADDR, ID_INDICATOR_DEC_ADDR, ID_INDICATOR_FILE_LENGTH, ID_INDICATOR_BIG_ENDIAN, ID_INDICATOR_READONLY, ID_INDICATOR_OVR, ID_INDICATOR_REC, ID_INDICATOR_CAPS, ID_INDICATOR_NUM, // ID_INDICATOR_SCRL, }; int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWndEx::OnCreate(lpCreateStruct) == -1) return -1; //menu_tip_.SetParent(this); // set the visual manager and style based on persisted value CMFCButton::EnableWindowsTheming(); OnApplicationLook(theApp.m_nAppLook); if (theApp.mditabs_) { EnableMDITabs(TRUE, theApp.tabicons_, theApp.tabsbottom_ ? CMFCTabCtrl::LOCATION_BOTTOM : CMFCTabCtrl::LOCATION_TOP, 0, CMFCTabCtrl::STYLE_3D_ONENOTE, 1); // TBD: TODO - replace with call to EnableMDITabbedGroups? } EnableDocking(CBRS_ALIGN_ANY); // Enable new docking window and auto-hide behavior CDockingManager::SetDockingMode(DT_SMART); EnableAutoHidePanes(CBRS_ALIGN_ANY); // Create BCG menu bar if (!m_wndMenuBar.Create(this)) { TRACE0("Failed to create a menu bar\n"); return -1; // fail to create } m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY); m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndMenuBar); // Create main Tool bar //if (!m_wndStandardBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_STDBAR) || if (!m_wndStandardBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, CRect(1, 1, 1, 1), IDR_STDBAR ) || #if SHADED_TOOLBARS !m_wndStandardBar.LoadToolBar(IDR_STDBAR, IDB_STDBAR_C, 0, FALSE, IDB_STDBAR_D, 0, IDB_STDBAR_H)) #else !m_wndStandardBar.LoadToolBar(IDR_STDBAR)) #endif { TRACE0("Failed to create Standard Toolbar\n"); return -1; // fail to create } m_wndStandardBar.SetWindowText("Standard Toolbar"); //m_wndStandardBar.SetPaneStyle(m_wndStandardBar.GetPaneStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndStandardBar.EnableCustomizeButton(TRUE, ID_CUSTOMIZE, _T("Customize...")); m_wndStandardBar.EnableDocking(CBRS_ALIGN_ANY); //m_wndStandardBar.EnableTextLabels(); DockPane(&m_wndStandardBar); // Create "edit" bar //if (!m_wndEditBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_EDITBAR) || if (!m_wndEditBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, CRect(1, 1, 1, 1), IDR_EDITBAR ) || #if SHADED_TOOLBARS !m_wndEditBar.LoadToolBar(IDR_EDITBAR, IDB_EDITBAR_C, 0, FALSE, IDB_EDITBAR_D, 0, IDB_EDITBAR_H)) #else !m_wndEditBar.LoadToolBar(IDR_EDITBAR)) #endif { TRACE0("Failed to create Edit Bar\n"); return -1; // fail to create } m_wndEditBar.SetWindowText("Edit Bar"); //m_wndEditBar.SetPaneStyle(m_wndEditBar.GetPaneStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndEditBar.EnableCustomizeButton(TRUE, ID_CUSTOMIZE, _T("Customize...")); m_wndEditBar.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndEditBar); // Create Format bar //if (!m_wndFormatBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_FORMATBAR) || if (!m_wndFormatBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, CRect(1, 1, 1, 1), IDR_FORMATBAR ) || #if SHADED_TOOLBARS !m_wndFormatBar.LoadToolBar(IDR_FORMATBAR, IDB_FMTBAR_C, 0, FALSE, IDB_FMTBAR_D, 0, IDB_FMTBAR_H)) #else !m_wndFormatBar.LoadToolBar(IDR_FORMATBAR)) #endif { TRACE0("Failed to create Format Bar\n"); return -1; // fail to create } m_wndFormatBar.SetWindowText("Format Bar"); //m_wndFormatBar.SetPaneStyle(m_wndFormatBar.GetPaneStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndFormatBar.EnableCustomizeButton(TRUE, ID_CUSTOMIZE, _T("Customize...")); m_wndFormatBar.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndFormatBar); m_wndFormatBar.ShowPane(FALSE, FALSE, FALSE); // Create Navigation bar //if (!m_wndNavBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_NAVBAR) || if (!m_wndNavBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC, CRect(1, 1, 1, 1), IDR_NAVBAR ) || #if SHADED_TOOLBARS !m_wndNavBar.LoadToolBar(IDR_NAVBAR, IDB_NAVBAR_C, 0, FALSE, IDB_NAVBAR_D, 0, IDB_NAVBAR_H)) #else !m_wndNavBar.LoadToolBar(IDR_NAVBAR)) #endif { TRACE0("Failed to create Nav Bar\n"); return -1; // fail to create } m_wndNavBar.SetWindowText("Navigation Bar"); //m_wndNavBar.SetPaneStyle(m_wndNavBar.GetPaneStyle() |CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndNavBar.EnableCustomizeButton(TRUE, ID_CUSTOMIZE, _T("Customize...")); m_wndNavBar.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndNavBar); m_wndNavBar.ShowPane(FALSE, FALSE, FALSE); if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(*indicators))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndStatusBar.SetPaneWidth(0, 340); m_wndStatusBar.SetToolTips(); ASSERT(m_wndStatusBar.CommandToIndex(ID_INDICATOR_OCCURRENCES) > -1); if (HBITMAP(m_search_image) != 0) m_wndStatusBar.SetPaneIcon(m_wndStatusBar.CommandToIndex(ID_INDICATOR_OCCURRENCES), HBITMAP(m_search_image), RGB(255,255,255)); for (int pane = 1; pane < sizeof(indicators)/sizeof(*indicators)-3; ++pane) m_wndStatusBar.SetPaneText(pane, ""); // clear out dummy text // Create the dockable windows if (!m_paneBookmarks.Create("Bookmarks", this, CSize(500, 250), TRUE, IDD_BOOKMARKS_PARENT, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI) || !m_wndBookmarks.Create(&m_paneBookmarks) ) { return FALSE; // failed to create } m_paneBookmarks.InitialUpdate(&m_wndBookmarks); m_paneBookmarks.EnableDocking(CBRS_ALIGN_ANY); if (!m_paneFind.Create("Find", this, CSize(500, 250), TRUE, IDD_FIND_PARENT, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI) || !m_wndFind.Create(&m_paneFind, WS_CHILD | WS_VISIBLE) ) { return FALSE; // failed to create } m_paneFind.InitialUpdate(&m_wndFind); m_paneFind.EnableDocking(CBRS_ALIGN_ANY); if (!m_paneCalc.Create("Calculator", this, CSize(500, 250), TRUE, IDD_CALC_PARENT, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI) || !m_wndCalc.Create(&m_paneCalc) ) { return FALSE; // failed to create } CRect rct; m_wndCalc.GetWindowRect(&rct); // get window size before it is fiddled with m_paneCalc.InitialUpdate(&m_wndCalc); // Now set min size (height = 3/4 of initial size) rct.bottom = rct.top + (rct.bottom - rct.top)*3/4; m_paneCalc.SetMinSize(rct.Size()); m_paneCalc.EnableDocking(CBRS_ALIGN_ANY); if (!m_paneProp.Create("Properties", this, CSize(500, 250), TRUE, IDD_PROP_PARENT, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI) || !m_wndProp.Create(&m_paneProp, WS_CHILD | WS_VISIBLE) ) { return FALSE; // failed to create } m_paneProp.InitialUpdate(&m_wndProp); m_paneProp.EnableDocking(CBRS_ALIGN_ANY); if (!m_paneExpl.Create("HexEdit Explorer", this, CSize(500, 250), TRUE, IDD_EXPLORER_PARENT, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI) || !m_wndExpl.Create(&m_paneExpl) ) { return FALSE; // failed to create } m_paneExpl.InitialUpdate(&m_wndExpl); m_paneExpl.EnableDocking(CBRS_ALIGN_ANY); // Set initial positions and docking/floating status but then hide all the windows InitDockWindows(); m_paneBookmarks.DockToFrameWindow(CBRS_ALIGN_LEFT); m_paneCalc.DockToWindow(&m_paneBookmarks, CBRS_ALIGN_BOTTOM); m_paneExpl.DockToFrameWindow(CBRS_ALIGN_BOTTOM); m_paneBookmarks.Hide(); m_paneFind.Hide(); m_paneProp.Hide(); m_paneCalc.Hide(); m_paneExpl.Hide(); // Get extra command images (without creating a toolbar) #if SHADED_TOOLBARS CMFCToolBar::AddToolBarForImageCollection(IDR_MISC, IDB_MISCBAR_H, IDB_MISCBAR_C, 0, IDB_MISCBAR_D); CMFCToolBar::AddToolBarForImageCollection(IDR_OPER, IDB_OPERBAR_H, IDB_OPERBAR_C, 0, IDB_OPERBAR_D); #else CMFCToolBar::AddToolBarForImageCollection(IDR_MISC); CMFCToolBar::AddToolBarForImageCollection(IDR_OPER); #endif CString strDefault = ::GetExePath() + "DefaultToolbarImages.bmp"; ::GetDataPath(m_strImagesFileName); if (!m_strImagesFileName.IsEmpty()) { // We have a data path so check if the toolbar images file is there m_strImagesFileName += "ToolbarImages.bmp"; CFileFind ff; if (!ff.FindFile(m_strImagesFileName)) { // The user's toolbar images file was not found so copy it from the default ::MakeSureDirectoryPathExists(m_strImagesFileName); if (!::CopyFile(strDefault, m_strImagesFileName, TRUE)) { // Could not copy the default images file to user's toolbar images file if (GetLastError() == ERROR_PATH_NOT_FOUND) { AfxMessageBox("The HexEdit Application Data folder is invalid"); m_strImagesFileName = strDefault; } else { ASSERT(GetLastError() == ERROR_FILE_NOT_FOUND); AfxMessageBox("The default toolbar images file was not found in the HexEdit folder."); m_strImagesFileName.Empty(); // we can't do anything so signal that the file is not available } } } } else { AfxMessageBox("The HexEdit Application Data folder is not found"); m_strImagesFileName = strDefault; } if (!m_strImagesFileName.IsEmpty()) { // Open images files and allow user to use/edit toolbar images VERIFY(m_UserImages.Load(m_strImagesFileName)); if (m_UserImages.IsValid()) CMFCToolBar::SetUserImages (&m_UserImages); } CMFCToolBar::EnableQuickCustomization(); InitUserToolbars(NULL, ID_VIEW_USER_TOOLBAR1, ID_VIEW_USER_TOOLBAR10); EnableWindowsDialog (ID_WINDOW_MANAGER, _T("Windows..."), TRUE); EnablePaneMenu(TRUE, ID_CUSTOMIZE, _T("Customize..."), ID_VIEW_TOOLBARS, FALSE, FALSE); // Load search strings into mainframe edit bar LoadSearchHistory(&theApp); LoadJumpHistory(&theApp); VERIFY(expr_.LoadVars()); // VERIFY(timer_id_ = SetTimer(1, 1000, NULL)); // Set main window title (mucked up by CBCGSizingControlBar::OnSetText) CString strMain; strMain.LoadString(IDR_MAINFRAME); SetWindowText(strMain); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { WNDCLASS wndclass; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); HINSTANCE hInst = AfxGetInstanceHandle(); BOOL retval = CMDIFrameWndEx::PreCreateWindow(cs); ::GetClassInfo(hInst, cs.lpszClass, &wndclass); wndclass.style &= ~(CS_HREDRAW|CS_VREDRAW); wndclass.lpszClassName = aa->szHexEditClassName; wndclass.hIcon = ::LoadIcon(hInst, MAKEINTRESOURCE(IDR_MAINFRAME)); ASSERT(wndclass.hIcon != 0); if (!AfxRegisterClass(&wndclass)) AfxThrowResourceException(); cs.lpszClass = aa->szHexEditClassName; if (aa->open_restore_) { int ss; if ((ss = aa->GetProfileInt("MainFrame", "WindowState", -1)) != -1) aa->m_nCmdShow = ss; // Get the window position/size int top, left, bottom, right; top = aa->GetProfileInt("MainFrame", "WindowTop", -30000); left = aa->GetProfileInt("MainFrame", "WindowLeft", -30000); bottom = aa->GetProfileInt("MainFrame", "WindowBottom", -30000); right = aa->GetProfileInt("MainFrame", "WindowRight", -30000); // If the values look OK change the CREATESTRUCT value correspondingly if (top != -30000 && right != -30000 && top < bottom && left < right) { // Get the work area within the display CRect rct; if (aa->mult_monitor_) { CRect rr(left, top, right, bottom); HMONITOR hh = MonitorFromRect(&rr, MONITOR_DEFAULTTONEAREST); MONITORINFO mi; mi.cbSize = sizeof(mi); if (hh != 0 && GetMonitorInfo(hh, &mi)) rct = mi.rcWork; // work area of nearest monitor else { // Shouldn't happen but if it does use the whole virtual screen ASSERT(0); rct = CRect(::GetSystemMetrics(SM_XVIRTUALSCREEN), ::GetSystemMetrics(SM_YVIRTUALSCREEN), ::GetSystemMetrics(SM_XVIRTUALSCREEN) + ::GetSystemMetrics(SM_CXVIRTUALSCREEN), ::GetSystemMetrics(SM_YVIRTUALSCREEN) + ::GetSystemMetrics(SM_CYVIRTUALSCREEN)); } } else if (!::SystemParametersInfo(SPI_GETWORKAREA, 0, &rct, 0)) { // I don't know if this will ever happen since the Windows documentation // is pathetic and does not say when or why SystemParametersInfo might fail. rct = CRect(0, 0, ::GetSystemMetrics(SM_CXFULLSCREEN), ::GetSystemMetrics(SM_CYFULLSCREEN)); } // Make sure that the window is not off the screen (or just on it). // (There might be a different screen resolution since options were saved.) if (left > rct.right - 20) { left = rct.right - (right - left); right = rct.right; } if (right < rct.left + 20) { right = rct.left + (right - left); left = rct.left; } if (top > rct.bottom - 20) { top = rct.bottom - (bottom - top); bottom = rct.bottom; } // Make sure top is not more than a little bit off the top of screen if (top < rct.top - 15) { bottom = rct.top + (bottom - top); top = rct.top; } // Set window width and height cs.cx = right - left; cs.cy = bottom - top; cs.x = left; cs.y = top; } } return retval; } BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) { CWnd *pwnd = CWnd::FromHandlePermanent(pMsg->hwnd); if (pwnd != NULL && (pwnd->IsKindOf(RUNTIME_CLASS(CSearchEditControl)) || pwnd->IsKindOf(RUNTIME_CLASS(CHexEditControl)) || pwnd->IsKindOf(RUNTIME_CLASS(CDecEditControl)) || pwnd->IsKindOf(RUNTIME_CLASS(CCalcEdit)) || pwnd->IsKindOf(RUNTIME_CLASS(CInPlaceEdit)) ) ) { return FALSE; } return CMDIFrameWndEx::PreTranslateMessage(pMsg); } void CMainFrame::OnClose() { // Save state (posn, docked, hidden etc) of control bars (tool, edit // & status bars) if save options on exit is on CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); SaveSearchHistory(aa); SaveJumpHistory(aa); expr_.SaveVars(); SaveBarState("DockState"); if (aa->save_exit_) SaveFrameOptions(); // The following were moved here from HexEditApp::ExitInstance as they require // access to the main windows (AfxGetMainWnd() returns NULL in ExitInstance) // Clear histories if the option to clear on exit is on if (theApp.clear_on_exit_) { CHexFileList *pfl = theApp.GetFileList(); if (pfl != NULL && theApp.clear_recent_file_list_) { pfl->ClearAll(); } CBookmarkList *pbl = theApp.GetBookmarkList(); if (pbl != NULL && theApp.clear_bookmarks_) { pbl->ClearAll(); } } if (aa->delete_all_settings_) remove(m_strImagesFileName); CMDIFrameWndEx::OnClose(); } void CMainFrame::OnSize(UINT nType, int cx, int cy) { CMDIFrameWndEx::OnSize(nType, cx, cy); Invalidate(TRUE); } // Handles control menu commands and system buttons (Minimize etc) void CMainFrame::OnSysCommand(UINT nID, LONG lParam) { CMDIFrameWndEx::OnSysCommand(nID, lParam); nID &= 0xFFF0; if (nID == SC_MINIMIZE || nID == SC_RESTORE || nID == SC_MAXIMIZE) theApp.SaveToMacro(km_mainsys, nID); } // Given a popup menu and an ID of an item within the menu return the // rectangle of the item in screen coordinates CRect CMainFrame::item_rect(CMFCPopupMenu *pm, UINT id) { CRect rct; pm->GetMenuBar()->GetWindowRect(&rct); rct.top += ::GetSystemMetrics(SM_CYEDGE) + 1; for (int ii = 0; ii < pm->GetMenuItemCount(); ++ii) { CRect item_rct; pm->GetMenuItem(ii)->GetImageRect(item_rct); #if _MSC_VER < 1400 if (::GetMenuItemID(pm->GetMenu(), ii) == id) #else if (::GetMenuItemID(pm->GetMenu()->m_hMenu, ii) == id) #endif { rct.bottom = rct.top + item_rct.Height(); return rct; } rct.top += item_rct.Height(); } return CRect(0, 0, 0, 0); } void CMainFrame::show_tip(UINT id /* = -1 */) { menu_tip_.Hide(); if (id == -1) id = last_id_; else last_id_ = id; if (popup_menu_.empty()) return; CHexEditView *pview = GetView(); menu_tip_.Clear(); menu_tip_.SetBgCol(::GetSysColor(COLOR_INFOBK)); menu_tip_.SetStockFont(ANSI_VAR_FONT); if (id >= ID_NAV_BACK_FIRST && id < ID_NAV_BACK_FIRST + NAV_RESERVED) { menu_tip_.AddString(theApp.navman_.GetInfo(true, id - ID_NAV_BACK_FIRST)); } else if (id >= ID_NAV_FORW_FIRST && id < ID_NAV_FORW_FIRST + NAV_RESERVED) { menu_tip_.AddString(theApp.navman_.GetInfo(false, id - ID_NAV_FORW_FIRST + 1)); } else if (pview != NULL) { CRect rct; COLORREF addr_col = pview->DecAddresses() ? pview->GetDecAddrCol() : pview->GetHexAddrCol(); COLORREF text_col = pview->GetDefaultTextCol(); menu_tip_.SetBgCol(pview->GetBackgroundCol()); menu_tip_.SetStockFont(ANSI_FIXED_FONT); switch (id) { case ID_DISPLAY_HEX: menu_tip_.AddString("200: ", addr_col); menu_tip_.AddString("206: ", addr_col); rct = menu_tip_.GetRect(0); menu_tip_.AddString("23 68 71 62 53 2A", text_col, &CPoint(rct.Width(), rct.top)); rct = menu_tip_.GetRect(1); menu_tip_.AddString("68 6E 62 78 79 00", text_col, &CPoint(rct.Width(), rct.top)); break; case ID_DISPLAY_CHAR: menu_tip_.AddString("200: ", addr_col); menu_tip_.AddString("206: ", addr_col); rct = menu_tip_.GetRect(0); menu_tip_.AddString("#hqbS*", text_col, &CPoint(rct.Width(), rct.top)); rct = menu_tip_.GetRect(1); menu_tip_.AddString("hnbxy.", text_col, &CPoint(rct.Width(), rct.top)); break; case ID_DISPLAY_BOTH: menu_tip_.AddString("200: ", addr_col); menu_tip_.AddString("206: ", addr_col); rct = menu_tip_.GetRect(0); menu_tip_.AddString("23 68 71 62 53 2A #hqbS*", text_col, &CPoint(rct.Width(), rct.top)); rct = menu_tip_.GetRect(1); menu_tip_.AddString("68 6E 62 78 79 00 hnbxy.", text_col, &CPoint(rct.Width(), rct.top)); break; case ID_DISPLAY_STACKED: menu_tip_.AddString("200: ", addr_col); rct = menu_tip_.GetRect(0); menu_tip_.AddString("#hqb S*hn bxy.", text_col, &CPoint(rct.Width(), rct.top)); rct = menu_tip_.GetRect(1); menu_tip_.AddString("2676 5266 6770", text_col, &CPoint(rct.left, rct.bottom)); rct = menu_tip_.GetRect(2); menu_tip_.AddString("3812 3A8E 2890", text_col, &CPoint(rct.left, rct.bottom)); break; } //menu_tip_.SetFont(pview->GetFont()); // We need a non-prop. font but this does not do anything } if (menu_tip_.Count() > 0) { menu_tip_.Hide(0); CRect rct = item_rect(popup_menu_.back(), id); menu_tip_.Move(CPoint(rct.right, rct.top), false); CRect wnd_rct; menu_tip_.GetWindowRect(&wnd_rct); if (::OutsideMonitor(wnd_rct)) menu_tip_.Move(CPoint(rct.left, rct.bottom), false); menu_tip_.Show(); } } void CMainFrame::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hMenu) { //TRACE("WM_MENUSELECT %d, %x, %d\n", nItemID, nFlags, int(hMenu)); if ((nFlags & 0xFFFF) == 0xFFFF || (nFlags & MF_POPUP) != 0 || (nFlags & MF_SEPARATOR) != 0) menu_tip_.Hide(); else show_tip(nItemID); CMDIFrameWndEx::OnMenuSelect(nItemID, nFlags, hMenu); } // We could draw into the MDI client area here (eg HexEdit logo). BOOL CMainFrame::OnEraseMDIClientBackground(CDC* pDC) { if (m_dib == NULL || m_background_pos == 0) return FALSE; // No bitmap so let Windows draw the background CRect rct; m_wndClientArea.GetClientRect(rct); // TBD: TODO check the problem below still occurs with MFC10 // Before MFC9 drawing the background was simple - even if drawing relative to bottom // or right side it was a simple matter to redraw the background whenever this event was // generated - even when things were docked to the sides of the window. // With MFC9, if the user docks (toolbar or tool window) to the sides of the window then // the background is not refreshed properly unless drawing relative to top-left. Ie: // - if drawing relative to top-left (m_background_pos == 1) drawing is always OK // - if resizing the window drawing is always OK // - when docking/undocking (and m_background_pos != 1) some parts of the background are not redrawn // Solutions tried that did not work: // - ignore clipping rect and redraw the whole window - somehow Windows prevents this working // - if clip rect smaller than whole window invalidate the whole window (see code below) - causes weird side effects #if 0 // Get rectangle to be drawn into CRect clip_rct; pDC->GetClipBox(&clip_rct); if (m_background_pos != 1 && rct != clip_rct) { // The kludgey solution was to invalidate the whole window if the clip rect is smaller than it. m_wndClientArea.InvalidateRect(&rct, TRUE); return TRUE; // prevent any other erasure since we will erase everything shortly anyway. } #endif // pDC->FillSolidRect(rct, ::GetSysColor(COLOR_APPWORKSPACE)); CSize siz; siz.cx = FreeImage_GetWidth(m_dib); siz.cy = FreeImage_GetHeight(m_dib); CPoint point; CBrush backBrush; switch (m_background_pos) { case 1: // top left point.x = point.y = 0; break; case 2: // top right point.x = rct.Width() - siz.cx; point.y = 0; break; case 3: // bottom left point.x = 0; point.y = rct.Height() - siz.cy; break; case 4: // bottom right point.x = rct.Width() - siz.cx; point.y = rct.Height() - siz.cy; break; case 5: // centre point.x = (rct.Width() - siz.cx)/2; point.y = (rct.Height() - siz.cy)/2; break; case 6: // stretch { ::StretchDIBits(pDC->GetSafeHdc(), 0, 0, rct.Width(), rct.Height(), 0, 0, siz.cx, siz.cy, FreeImage_GetBits(m_dib), FreeImage_GetInfo(m_dib), DIB_RGB_COLORS, SRCCOPY); } goto no_fill; case 7: // tile for (point.x = 0; point.x < rct.Width(); point.x += siz.cx) for (point.y = 0; point.y < rct.Height(); point.y += siz.cy) ::StretchDIBits(pDC->GetSafeHdc(), point.x, point.y, siz.cx, siz.cy, 0, 0, siz.cx, siz.cy, FreeImage_GetBits(m_dib), FreeImage_GetInfo(m_dib), DIB_RGB_COLORS, SRCCOPY); goto no_fill; } // Create background brush using top left pixel of bitmap { RGBQUAD px = { 192, 192, 192, 0}; // default to grey in case GetPixelColor fails int height = FreeImage_GetHeight(m_dib); VERIFY(FreeImage_GetPixelColor(m_dib, 0, height - 1, &px)); // get colour from top-left pixel (may fail if not 24 bit colours) backBrush.CreateSolidBrush(RGB(px.rgbRed, px.rgbGreen, px.rgbBlue)); backBrush.UnrealizeObject(); } // dcTmp destroyed here pDC->FillRect(rct, &backBrush); ::StretchDIBits(pDC->GetSafeHdc(), point.x, point.y, siz.cx, siz.cy, 0, 0, siz.cx, siz.cy, FreeImage_GetBits(m_dib), FreeImage_GetInfo(m_dib), DIB_RGB_COLORS, SRCCOPY); no_fill: return TRUE; } // The following bizare stuff is used to set the current page in print preview // mode. This is necessary due to a bug in MFC. CPreviewViewKludge is just // used to get access to the protected members of CPreviewView. class CPreviewViewKludge : public CPreviewView { public: BOOL Inited() { return CPreviewView::m_hMagnifyCursor != 0; } void SetCurrentPage2(UINT nPage, BOOL bClearRatios) { CPreviewView::SetCurrentPage(nPage, bClearRatios); } }; void CMainFrame::RecalcLayout(BOOL bNotify) { CPreviewViewKludge *ppv = (CPreviewViewKludge *)GetActiveView(); if (ppv != NULL && ppv->IsKindOf(RUNTIME_CLASS(CPreviewView))) { if (!ppv->Inited() && preview_page_ != -1) ppv->SetCurrentPage2(preview_page_, TRUE); } CMDIFrameWndEx::RecalcLayout(bNotify); } LONG CMainFrame::OnOpenMsg(UINT, LONG lParam) { char filename[256]; filename[0] = '\0'; if (::GlobalGetAtomName((ATOM)lParam, filename, sizeof(filename)) == 0) return FALSE; ASSERT(theApp.open_current_readonly_ == -1); return theApp.OpenDocumentFile(filename) != NULL; } void CMainFrame::SaveFrameOptions() { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Save info about the main frame window position aa->WriteProfileInt("MainFrame", "Restore", aa->open_restore_ ? 1 : 0); if (aa->open_restore_) { WINDOWPLACEMENT wp; GetWindowPlacement(&wp); aa->WriteProfileInt("MainFrame", "WindowState", wp.showCmd); aa->WriteProfileInt("MainFrame", "WindowTop", wp.rcNormalPosition.top); aa->WriteProfileInt("MainFrame", "WindowLeft", wp.rcNormalPosition.left); aa->WriteProfileInt("MainFrame", "WindowBottom", wp.rcNormalPosition.bottom); aa->WriteProfileInt("MainFrame", "WindowRight", wp.rcNormalPosition.right); } } // Set the default positions of all docking windows void CMainFrame::InitDockWindows() { // Initially all are floating m_paneFind.Float(false); m_paneBookmarks.Float(false); m_paneProp.Float(false); m_paneCalc.Float(false); m_paneExpl.Float(false); // We get the main window rectangle so we can position the floating // windows around its edges. CSize sz; CRect mainRect, rct; GetWindowRect(&mainRect); // get main window in order to set float positions // Position bookmarks in middle of left side sz = m_paneBookmarks.GetFrameSize(); rct.left = mainRect.left; rct.right = rct.left + sz.cx; rct.top = mainRect.top + mainRect.Size().cy/2 - sz.cy/2; rct.bottom = rct.top + sz.cy; m_paneBookmarks.GetParent()->MoveWindow(rct); // Position Find dialog at bottom left sz = m_paneFind.GetFrameSize(); rct.left = mainRect.left; rct.right = rct.left + sz.cx; rct.top = mainRect.bottom - sz.cy; rct.bottom = rct.top + sz.cy; m_paneFind.GetParent()->MoveWindow(rct); // Position Properties dialog at middle of bottom sz = m_paneProp.GetFrameSize(); rct.left = mainRect.left + mainRect.Size().cx/2 - sz.cx/2; rct.right = rct.left + sz.cx; rct.top = mainRect.bottom - sz.cy; rct.bottom = rct.top + sz.cy; m_paneProp.GetParent()->MoveWindow(rct); // Position Calculator at bottom right sz = m_paneCalc.GetFrameSize(); rct.left = mainRect.right - sz.cx; rct.right = rct.left + sz.cx; rct.top = mainRect.bottom - sz.cy; rct.bottom = rct.top + sz.cy; m_paneCalc.GetParent()->MoveWindow(rct); // Position Explorer at top right sz = m_paneExpl.GetFrameSize(); rct.left = mainRect.right - sz.cx; rct.right = rct.left + sz.cx; rct.top = mainRect.top; rct.bottom = rct.top + sz.cy; m_paneExpl.GetParent()->MoveWindow(rct); } void CMainFrame::FixPanes() { // Doing this at the strat avoids a problem where panes floating by themself are // not drawn properly when their position is restored on startup. The disadvantage // to the user is that any window they left floating will not be restored when they // reopen HexEdit (though the position is remembered and restored when they open it). if (m_paneBookmarks.IsFloating()) m_paneBookmarks.Hide(); if (m_paneFind.IsFloating()) m_paneFind.Hide(); if (m_paneCalc.IsFloating()) m_paneCalc.Hide(); if (m_paneProp.IsFloating()) m_paneProp.Hide(); if (m_paneExpl.IsFloating()) m_paneExpl.Hide(); } void CMainFrame::move_dlgbar(CGenDockablePane &bar, const CRect &rct) { // We don't need to move it if hidden or docked if (!bar.IsWindowVisible() || bar.IsDocked() && !bar.IsInFloatingMultiPaneFrameWnd()) return; // Get height of screen (needed later) int scr_height = GetSystemMetrics(SM_CYSCREEN); int scr_width = GetSystemMetrics(SM_CXSCREEN); CWnd * pFrm = &bar; // Window we (may) need to move CRect wnd_rct; // Rect of the window we need to move while ((pFrm = pFrm->GetParent()) != NULL) { if (pFrm->IsKindOf(RUNTIME_CLASS(CMultiPaneFrameWnd))) break; } if (pFrm == NULL) { ASSERT(0); // We din't find it which should not happen return; } pFrm->GetWindowRect(&wnd_rct); CRect intersect_rct; // Intersection of dialog & selection if (!intersect_rct.IntersectRect(&wnd_rct, &rct)) return; // No intersection so we do nothing CRect new_rct(wnd_rct); // New position of dialog bool move_horiz = rct.top > wnd_rct.top && rct.bottom < wnd_rct.bottom && (rct.left < wnd_rct.left && rct.right < wnd_rct.right || rct.left > wnd_rct.left && rct.right > wnd_rct.right); // Most of the time we move vertically - this is when if (!move_horiz) { if (new_rct.CenterPoint().y > rct.CenterPoint().y) { // Move downwards new_rct.OffsetRect(0, rct.bottom - new_rct.top); if (new_rct.bottom > scr_height - 40) new_rct.OffsetRect(0, rct.top - new_rct.bottom); if (new_rct.top < 0) move_horiz = true; } else { new_rct.OffsetRect(0, rct.top - new_rct.bottom); if (new_rct.top < 40) new_rct.OffsetRect(0, rct.bottom - new_rct.top); if (new_rct.top > scr_height - 80) move_horiz = true; } } if (move_horiz) { new_rct = wnd_rct; // Start again if (new_rct.CenterPoint().x > rct.CenterPoint().x) { // Move right new_rct.OffsetRect(rct.right - new_rct.left, 0); if (new_rct.right > scr_width - 40) new_rct.OffsetRect(rct.left - new_rct.right, 0); if (new_rct.right < 40) new_rct = wnd_rct; // Give up } else { // Move left new_rct.OffsetRect(rct.left - new_rct.right, 0); if (new_rct.left < 40) new_rct.OffsetRect(rct.right - new_rct.left, 0); if (new_rct.left > scr_width - 40) new_rct = wnd_rct; // Give up } } pFrm->MoveWindow(&new_rct); #if 0 // causes weird things if dragging a selection // If the mouse ptr (cursor) was over the dialog move it too CPoint mouse_pt; ::GetCursorPos(&mouse_pt); if (wnd_rct.PtInRect(mouse_pt)) { // Mouse was over find dialog (probably over "Find Next" button) mouse_pt.x += new_rct.left - wnd_rct.left; mouse_pt.y += new_rct.top - wnd_rct.top; ::SetCursorPos(mouse_pt.x, mouse_pt.y); } #endif } void CMainFrame::show_calc() { m_wndCalc.SetWindowText("Calculator"); m_paneCalc.ShowAndUnroll(); m_wndCalc.update_controls(); m_wndCalc.ShowBinop(); } void CMainFrame::OnContextMenu(CWnd* pWnd, CPoint point) { if (pWnd->GetSafeHwnd () == m_wndClientArea.GetMDITabs().GetSafeHwnd()) { const CMFCTabCtrl & wndTab = m_wndClientArea.GetMDITabs(); CRect rectTabs; wndTab.GetTabsRect (rectTabs); CPoint ptTab = point; wndTab.ScreenToClient (&ptTab); int iClickedTab = wndTab.GetTabFromPoint (ptTab); if (iClickedTab >= 0) m_wndClientArea.SetActiveTab(wndTab.GetTabWnd(iClickedTab)->m_hWnd); theApp.ShowPopupMenu (IDR_CONTEXT_TABS, point, pWnd); } } BOOL CMainFrame::OnHelpInfo(HELPINFO* pHelpInfo) { return CMDIFrameWndEx::OnHelpInfo(pHelpInfo); } void CMainFrame::OnContextHelp() { CMDIFrameWndEx::OnContextHelp(); } void CMainFrame::OnHelpFinder() { CMDIFrameWndEx::OnHelpFinder(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_topics); } void CMainFrame::OnHelpKeyboardMap() { CMFCKeyMapDialog dlg(this, TRUE); dlg.DoModal(); } void CMainFrame::OnHelpTute(UINT nID) { // Display help for this page if (!::HtmlHelp(m_hWnd, theApp.htmlhelp_file_, HH_HELP_CONTEXT, 0x10000+nID)) AfxMessageBox(AFX_IDP_FAILED_TO_LAUNCH_HELP); } void CMainFrame::OnHelp() { CMDIFrameWndEx::OnHelp(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_help); } void CMainFrame::HtmlHelp(DWORD_PTR dwData, UINT nCmd) { if (dwData == AFX_HIDD_FILEOPEN || dwData == AFX_HIDD_FILESAVE) dwData = hid_last_file_dialog; CMDIFrameWndEx::HtmlHelp(dwData, nCmd); } // This is here just so we can intercept calls in the debugger LRESULT CMainFrame::OnCommandHelp(WPARAM wParam, LPARAM lParam) { return CMDIFrameWndEx::OnCommandHelp(wParam, lParam); } ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWndEx::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWndEx::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers void CMainFrame::OnNavigateBackwards() { theApp.navman_.GoBack(); } void CMainFrame::OnUpdateNavigateBackwards(CCmdUI* pCmdUI) { pCmdUI->Enable(theApp.navman_.BackAllowed()); } void CMainFrame::OnNavigateForwards() { theApp.navman_.GoForw(); } void CMainFrame::OnUpdateNavigateForwards(CCmdUI* pCmdUI) { pCmdUI->Enable(theApp.navman_.ForwAllowed()); } void CMainFrame::OnNavBack(UINT nID) { ASSERT(nID - ID_NAV_BACK_FIRST < NAV_RESERVED); theApp.navman_.GoBack(nID - ID_NAV_BACK_FIRST); } void CMainFrame::OnNavForw(UINT nID) { ASSERT(nID - ID_NAV_FORW_FIRST < NAV_RESERVED); theApp.navman_.GoForw(nID - ID_NAV_FORW_FIRST + 1); } LRESULT CMainFrame::OnGetTabToolTip(WPARAM /*wp*/, LPARAM lp) { CMFCTabToolTipInfo * pInfo = (CMFCTabToolTipInfo *)lp; CFrameWnd * pFrame; CDocument * pDoc; if (pInfo == NULL || !pInfo->m_pTabWnd->IsMDITab() || (pFrame = DYNAMIC_DOWNCAST(CFrameWnd, pInfo->m_pTabWnd->GetTabWnd(pInfo->m_nTabIndex))) == NULL || (pDoc = pFrame->GetActiveDocument()) == NULL ) { return 0; } pInfo->m_strText = pDoc->GetPathName(); return 0; } void CMainFrame::OnMacro(UINT nID) { ASSERT(nID >= ID_MACRO_FIRST && nID < ID_MACRO_LAST); std::vector<CString> mac = GetMacroCommands(); int ii = nID - ID_MACRO_FIRST; if (ii >= 0 && ii < mac.size()) theApp.play_macro_file(mac[ii]); } void CMainFrame::OnDockableToggle() { theApp.dlg_dock_ = !theApp.dlg_dock_; if (!theApp.dlg_dock_) { // Make sure the windows aren't docked and turn off dockability m_paneFind.Float(); m_paneFind.EnableDocking(0); m_paneBookmarks.Float(); m_paneBookmarks.EnableDocking(0); m_paneProp.Float(); m_paneProp.EnableDocking(0); m_paneCalc.Float(); m_paneCalc.EnableDocking(0); m_paneExpl.Float(); m_paneExpl.EnableDocking(0); } else { // Turn on dockability for all modeless (pane) dialogs m_paneFind.EnableDocking(CBRS_ALIGN_ANY); m_paneBookmarks.EnableDocking(CBRS_ALIGN_ANY); m_paneProp.EnableDocking(CBRS_ALIGN_ANY); m_paneCalc.EnableDocking(CBRS_ALIGN_ANY); m_paneExpl.EnableDocking(CBRS_ALIGN_ANY); } } void CMainFrame::OnUpdateDockableToggle(CCmdUI* pCmdUI) { pCmdUI->SetCheck(theApp.dlg_dock_); } void CMainFrame::OnWindowNew() { // Store options for the active view so that the new view will get the same ones if (GetView() != NULL) GetView()->StoreOptions(); CMDIFrameWndEx::OnWindowNew(); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_ && aa->mac_.size() > 0 && (aa->mac_.back()).ktype == km_focus) { // We don't want focus change recorded (see CHexEditView::OnSetFocus) aa->mac_.pop_back(); } aa->SaveToMacro(km_win_new); } // Handles the window menu commands: cascade, tile, arrange BOOL CMainFrame::OnMDIWindowCmd(UINT nID) { BOOL retval = CMDIFrameWndEx::OnMDIWindowCmd(nID); CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (retval) aa->SaveToMacro(km_win_cmd, nID); else aa->mac_error_ = 20; return retval; } void CMainFrame::OnUpdateViewViewbar(CCmdUI* pCmdUI) { pCmdUI->SetCheck((m_wndStandardBar.GetStyle() & WS_VISIBLE) != 0); } void CMainFrame::OnViewViewbar() { m_wndStandardBar.ShowPane((m_wndStandardBar.GetStyle() & WS_VISIBLE) == 0, FALSE, FALSE); //ShowControlBar(&m_wndStandardBar, (m_wndStandardBar.GetStyle() & WS_VISIBLE) == 0, FALSE); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_toolbar, 1); } void CMainFrame::OnUpdateViewEditbar(CCmdUI* pCmdUI) { pCmdUI->SetCheck((m_wndEditBar.GetStyle() & WS_VISIBLE) != 0); } void CMainFrame::OnViewEditbar() { m_wndEditBar.ShowPane((m_wndEditBar.GetStyle() & WS_VISIBLE) == 0, FALSE, FALSE); //ShowControlBar(&m_wndEditBar, (m_wndEditBar.GetStyle() & WS_VISIBLE) == 0, FALSE); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_toolbar, 2); } void CMainFrame::OnUpdateViewFormatbar(CCmdUI* pCmdUI) { pCmdUI->SetCheck((m_wndFormatBar.GetStyle() & WS_VISIBLE) != 0); } void CMainFrame::OnViewFormatbar() { m_wndFormatBar.ShowPane((m_wndFormatBar.GetStyle() & WS_VISIBLE) == 0, FALSE, FALSE); //ShowControlBar(&m_wndFormatBar, (m_wndFormatBar.GetStyle() & WS_VISIBLE) == 0, FALSE); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_toolbar, 4); } void CMainFrame::OnUpdateViewNavbar(CCmdUI* pCmdUI) { pCmdUI->SetCheck((m_wndNavBar.GetStyle() & WS_VISIBLE) != 0); } void CMainFrame::OnViewNavbar() { m_wndNavBar.ShowPane((m_wndNavBar.GetStyle() & WS_VISIBLE) == 0, FALSE, FALSE); //ShowControlBar(&m_wndNavBar, (m_wndNavBar.GetStyle() & WS_VISIBLE) == 0, FALSE); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_toolbar, 5); } void CMainFrame::OnUpdateViewCalculator(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_paneCalc.IsWindowVisible()); } void CMainFrame::OnViewCalculator() { m_paneCalc.Toggle(); theApp.SaveToMacro(km_toolbar, 10); } void CMainFrame::OnUpdateViewBookmarks(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_paneBookmarks.IsWindowVisible()); } void CMainFrame::OnViewBookmarks() { m_paneBookmarks.Toggle(); theApp.SaveToMacro(km_toolbar, 11); } void CMainFrame::OnUpdateViewFind(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_paneFind.IsWindowVisible()); } void CMainFrame::OnViewFind() { m_paneFind.Toggle(); theApp.SaveToMacro(km_toolbar, 12); } void CMainFrame::OnUpdateViewProperties(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_paneProp.IsWindowVisible()); } void CMainFrame::OnViewProperties() { m_paneProp.Toggle(); theApp.SaveToMacro(km_toolbar, 13); } void CMainFrame::OnUpdateViewExpl(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_paneExpl.IsWindowVisible()); } void CMainFrame::OnViewExpl() { m_paneExpl.Toggle(); theApp.SaveToMacro(km_toolbar, 14); } void CMainFrame::OnUpdateViewRuler(CCmdUI* pCmdUI) { pCmdUI->SetCheck(theApp.ruler_); } void CMainFrame::OnViewRuler() { theApp.ruler_ = !theApp.ruler_; theApp.UpdateAllViews(); theApp.SaveToMacro(km_toolbar, 15); } void CMainFrame::OnUpdateViewHighlightCaret(CCmdUI* pCmdUI) { pCmdUI->SetCheck(theApp.hl_caret_); } void CMainFrame::OnViewHighlightCaret() { CHexEditView *pview = GetView(); if (pview != NULL) { theApp.hl_caret_ = !theApp.hl_caret_; } theApp.SaveToMacro(km_toolbar, 16); } void CMainFrame::OnUpdateViewHighlightMouse(CCmdUI* pCmdUI) { pCmdUI->SetCheck(theApp.hl_mouse_); } void CMainFrame::OnViewHighlightMouse() { CHexEditView *pview = GetView(); if (pview != NULL) { theApp.hl_mouse_ = !theApp.hl_mouse_; } theApp.SaveToMacro(km_toolbar, 17); } void CMainFrame::OnUpdateReadonly(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview != NULL) { pCmdUI->Enable(TRUE); if (pview->ReadOnly()) pCmdUI->SetText("RO"); else pCmdUI->SetText("RW"); } else pCmdUI->Enable(FALSE); } void CMainFrame::OnUpdateOvr(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview != NULL && !pview->ReadOnly()) { pCmdUI->Enable(TRUE); if (pview->OverType()) pCmdUI->SetText("OVR"); else pCmdUI->SetText("INS"); } else pCmdUI->Enable(FALSE); } void CMainFrame::OnUpdateRec(CCmdUI *pCmdUI) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (aa->recording_) { pCmdUI->Enable(TRUE); // pCmdUI->SetText("REC"); } else pCmdUI->Enable(FALSE); } BOOL CMainFrame::UpdateBGSearchProgress() { CHexEditView *pview = GetView(); int ii; if (pview != NULL) { if ((ii = pview->GetDocument()->SearchOccurrences()) == -2) { int index = m_wndStatusBar.CommandToIndex(ID_INDICATOR_OCCURRENCES); //COLORREF text_col = RGB(0,0,0); //int hue, luminance, saturation; //get_hls(::GetSearchCol(), hue, luminance, saturation); //if (hue != -1) //{ // if (luminance > 50) luminance = 1; else luminance = 99; // text_col = get_rgb((hue+50)%100, luminance, 99); //} if (bg_progress_colour_ != pview->GetSearchCol()) { bg_progress_colour_ = pview->GetSearchCol(); m_wndStatusBar.EnablePaneProgressBar(index, 100, TRUE, bg_progress_colour_); } m_wndStatusBar.SetPaneProgress(index, pview->GetDocument()->SearchProgress(ii)); return TRUE; } } return FALSE; } void CMainFrame::OnUpdateOccurrences(CCmdUI *pCmdUI) { CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int index = psb->CommandToIndex(ID_INDICATOR_OCCURRENCES); CHexEditView *pview = GetView(); int pane_width = 80; if (pview != NULL) { int ii; if ((ii = pview->GetDocument()->SearchOccurrences()) > -1) { psb->EnablePaneProgressBar(index, -1); // turn off progress bar so we can show the text bg_progress_colour_ = -1; CString ss; ss.Format("%ld ", long(ii)); AddCommas(ss); // Work out pane width CClientDC dc(psb); dc.SelectObject(psb->GetFont()); pane_width = max(dc.GetTextExtent(ss, ss.GetLength()).cx + 20, 35); pCmdUI->SetText(ss); pCmdUI->Enable(); } else if (ii == -2) { UpdateBGSearchProgress(); // pCmdUI->SetText("..."); pCmdUI->Enable(); } else if (ii == -4) { psb->EnablePaneProgressBar(index, -1); // turn off progress bar so we can show the text bg_progress_colour_ = -1; pCmdUI->SetText("OFF"); pCmdUI->Enable(); } else pCmdUI->Enable(FALSE); } else { psb->EnablePaneProgressBar(index, -1); // turn off progress bar so we can show the text bg_progress_colour_ = -1; pCmdUI->SetText(""); pCmdUI->Enable(FALSE); } if (pane_width != OccurrencesWidth) { psb->SetPaneWidth(index, pane_width); OccurrencesWidth = pane_width; } } void CMainFrame::OnUpdateValues(CCmdUI *pCmdUI) { unsigned char cc; CHexEditView *pview = GetView(); if (pview != NULL && pview->GetDocument()->GetData(&cc, 1, pview->GetPos()) == 1) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); // Update pane with values of current byte char binbuf[9]; // To display binary value for (int ii = 0; ii < 8; ++ii) binbuf[ii] = (cc & (0x80>>ii)) ? '1' : '0'; binbuf[8] = '\0'; CString ss; if (aa->hex_ucase_) { if (!pview->EbcdicMode() && cc < 0x20) // Control char? ss.Format("%02X, %d, %03o, %8s, '^%c' ",cc,cc,cc,binbuf,cc+0x40); else if (!pview->EbcdicMode()) ss.Format("%02X, %d, %03o, %8s, '%c' ",cc,cc,cc,binbuf,cc); else if (e2a_tab[cc] != '\0') ss.Format("%02X, %d, %03o, %8s, '%c' ",cc,cc,cc,binbuf, e2a_tab[cc]); else ss.Format("%02X, %d, %03o, %8s, none ",cc,cc,cc,binbuf); } else { if (!pview->EbcdicMode() && cc < 0x20) // Control char? ss.Format("%02x, %d, %03o, %8s, '^%c' ",cc,cc,cc,binbuf,cc+0x40); else if (!pview->EbcdicMode()) ss.Format("%02x, %d, %03o, %8s, '%c' ",cc,cc,cc,binbuf,cc); else if (e2a_tab[cc] != '\0') ss.Format("%02x, %d, %03o, %8s, '%c' ",cc,cc,cc,binbuf, e2a_tab[cc]); else ss.Format("%02x, %d, %03o, %8s, none ",cc,cc,cc,binbuf); } // Get status bar control CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int idx = psb->CommandToIndex(ID_INDICATOR_VALUES); // index of the byte values pane // Set pane width CClientDC dc(psb); dc.SelectObject(psb->GetFont()); int text_width = dc.GetTextExtent(ss, ss.GetLength()).cx + 4; if (abs(text_width - ValuesWidth) > 4) { psb->SetPaneWidth(idx, text_width); ValuesWidth = text_width; } pCmdUI->SetText(ss); pCmdUI->Enable(); } else { pCmdUI->SetText(""); pCmdUI->Enable(FALSE); } } void CMainFrame::OnUpdateAddrHex(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview != NULL) { // Update pane with Current offset from marked position (hex) char buf[32]; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); __int64 mark = __int64(pview->GetMarkOffset()); size_t len; if (aa->hex_ucase_) len = sprintf(buf, "%I64X", mark); else len = sprintf(buf, "%I64x", mark); if (mark > 9) strcpy(buf+len, "h"); CString ss(buf); AddSpaces(ss); ss += " "; #if 0 // Colours now handled by CMFCStatusBar // We don't want text drawn since it will write over our own custom text pCmdUI->SetText(""); pCmdUI->Enable(); CStatBar *psb = (CStatBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CStatBar, psb); ASSERT_VALID(psb); CRect rct; psb->GetItemRect(pCmdUI->m_nIndex, &rct); rct.DeflateRect(2,2); CClientDC dc(psb); dc.FillSolidRect(rct, GetSysColor(COLOR_3DFACE)); dc.SetBkMode(TRANSPARENT); dc.SetTextColor(::GetHexAddrCol()); dc.DrawText(ss, rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS); #else // Get status bar control CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int idx = psb->CommandToIndex(ID_INDICATOR_HEX_ADDR); // index of the hex addr pane // Set pane colour psb->SetPaneTextColor(idx, ::GetHexAddrCol()); // Set pane width CClientDC dc(psb); dc.SelectObject(psb->GetFont()); int text_width = max(dc.GetTextExtent(ss, ss.GetLength()).cx + 2, 35); if (abs(text_width - AddrHexWidth) > 4) { psb->SetPaneWidth(idx, text_width); AddrHexWidth = text_width; } pCmdUI->SetText(ss); pCmdUI->Enable(); #endif } else pCmdUI->Enable(FALSE); } void CMainFrame::OnUpdateAddrDec(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview != NULL) { // Update pane with Current offset from marked position (decimal) char buf[32]; sprintf(buf, "%I64d", __int64(pview->GetMarkOffset())); CString ss(buf); AddCommas(ss); if (buf[0] == '-') ss = " " + ss; // Add a space before minus sign for visibility ss += " "; #if 0 // Colours now handled by CMFCStatusBar // We don't want text drawn since it will write over our own custom text pCmdUI->SetText(""); pCmdUI->Enable(); CStatusBar *psb = (CStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CStatusBar, psb); ASSERT_VALID(psb); CRect rct; psb->GetItemRect(pCmdUI->m_nIndex, &rct); rct.DeflateRect(2,2); CClientDC dc(psb); dc.FillSolidRect(rct, GetSysColor(COLOR_3DFACE)); dc.SetBkMode(TRANSPARENT); dc.SetTextColor(::GetDecAddrCol()); dc.DrawText(ss, rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS); #else CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int idx = psb->CommandToIndex(ID_INDICATOR_DEC_ADDR); // Set pane colour psb->SetPaneTextColor(idx, ::GetDecAddrCol()); // Set pane width CClientDC dc(psb); dc.SelectObject(psb->GetFont()); int text_width = max(dc.GetTextExtent(ss, ss.GetLength()).cx + 2, 30); if (abs(text_width - AddrDecWidth) > 4) { psb->SetPaneWidth(idx, text_width); AddrDecWidth = text_width; } pCmdUI->SetText(ss); pCmdUI->Enable(); #endif } else pCmdUI->Enable(FALSE); } void CMainFrame::OnUpdateFileLength(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview != NULL) { // Get ptr to status bar and index of file length pane CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int idx = psb->CommandToIndex(ID_INDICATOR_FILE_LENGTH); CString ss; // text to put in the pane char buf[32]; // used with sprintf (CString::Format can't handle __int64) int seclen = pview->GetDocument()->GetSectorSize(); ASSERT(seclen > 0 || !pview->GetDocument()->IsDevice()); // no sectors (sec len is zero) if its an unsaved file (but not device) if (pview->GetDocument()->IsDevice() && seclen > 0) { // Show sector + total sectors __int64 end = pview->GetDocument()->length(); __int64 now = pview->GetPos(); CString tmp; if (pview->DecAddresses()) { sprintf(buf, "%I64d", __int64(now/seclen)); ss = buf; AddCommas(ss); sprintf(buf, "%I64d", __int64(end/seclen)); tmp = buf; AddCommas(tmp); psb->SetPaneTextColor(idx, ::GetDecAddrCol()); psb->SetTipText(psb->CommandToIndex(ID_INDICATOR_FILE_LENGTH), "Current/total sectors (decimal)"); } else { if (theApp.hex_ucase_) sprintf(buf, "%I64X", __int64(now/seclen)); else sprintf(buf, "%I64x", __int64(now/seclen)); ss = buf; AddSpaces(ss); if (theApp.hex_ucase_) sprintf(buf, "%I64X", __int64(end/seclen)); else sprintf(buf, "%I64x", __int64(end/seclen)); tmp = buf; AddSpaces(tmp); psb->SetPaneTextColor(idx, ::GetHexAddrCol()); psb->SetTipText(psb->CommandToIndex(ID_INDICATOR_FILE_LENGTH), "Current/total sectors (hex)"); } ss = "Sector: " + ss + "/" + tmp + " "; } else { // Show file length + difference FILE_ADDRESS orig_len = 0, curr_len, diff; curr_len = pview->GetDocument()->length(); if (pview->GetDocument()->pfile1_ != NULL) orig_len = pview->GetDocument()->pfile1_->GetLength(); else orig_len = curr_len; // Don't display diff if there is no disk file diff = curr_len - orig_len; // Update pane with original file length and difference in length if (pview->DecAddresses()) { sprintf(buf, "%I64d ", __int64(curr_len)); ss = buf; AddCommas(ss); // Set pane colour for decimal addresses psb->SetPaneTextColor(idx, ::GetDecAddrCol()); } else { // hex addresses size_t len; if (theApp.hex_ucase_) len = sprintf(buf, "%I64X", __int64(curr_len)); else len = sprintf(buf, "%I64x", __int64(curr_len)); ss = buf; AddSpaces(ss); if (curr_len > 9) ss += "h"; // Set pane colour for hex addresses psb->SetPaneTextColor(idx, ::GetHexAddrCol()); } if (diff != 0) { if (diff < -9) ss += " [-*]"; else if (diff > 9) ss += " [+*]"; else { sprintf(buf, " [%+I64d]", __int64(diff)); ss += buf; } psb->SetTipText(psb->CommandToIndex(ID_INDICATOR_FILE_LENGTH), "Length [+ bytes inserted]"); } else psb->SetTipText(psb->CommandToIndex(ID_INDICATOR_FILE_LENGTH), "File length"); ss = "Length: " + ss + " "; } // Set pane width CClientDC dc(psb); dc.SelectObject(psb->GetFont()); int text_width = max(dc.GetTextExtent(ss, ss.GetLength()).cx, 40); if (text_width != FileLengthWidth) { psb->SetPaneWidth(idx, text_width); FileLengthWidth = text_width; } pCmdUI->SetText(ss); pCmdUI->Enable(); } else pCmdUI->Enable(FALSE); } void CMainFrame::OnUpdateBigEndian(CCmdUI *pCmdUI) { // Get the active view CHexEditView *pview = GetView(); if (pview == NULL) { pCmdUI->Enable(FALSE); return; } // Get ptr to status bar and index of file length pane CMFCStatusBar *psb = (CMFCStatusBar *)pCmdUI->m_pOther; ASSERT_KINDOF(CMFCStatusBar, psb); ASSERT_VALID(psb); int idx = psb->CommandToIndex(ID_INDICATOR_BIG_ENDIAN); if (pview->BigEndian()) { // Set pane colour psb->SetPaneTextColor(idx, RGB(224,0,0)); pCmdUI->SetText("BE "); } else { // Set pane colour psb->SetPaneTextColor(idx, ::GetSysColor(COLOR_BTNTEXT)); pCmdUI->SetText("LE "); } pCmdUI->Enable(); } void CMainFrame::StatusBarText(const char *mess /*=NULL*/) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (mess == NULL) m_wndStatusBar.SetPaneText(0, last_mess_); // Update now else if (aa->refresh_off_) last_mess_ = mess; // Save message for later update else m_wndStatusBar.SetPaneText(0, mess); // Display immediately } // Saves a decimal address or expression for later retrieval void CMainFrame::SetDecAddress(const char *ss) { current_dec_address_ = ss; current_hex_address_.Empty(); CString dummy1, dummy2; (void)GetDecAddress(dummy1, dummy2); } // Saves an expression (involving hex ints) for later retrieval void CMainFrame::SetHexAddress(const char *ss) { current_hex_address_ = ss; current_dec_address_.Empty(); CString dummy1, dummy2; (void)GetHexAddress(dummy1, dummy2); } FILE_ADDRESS CMainFrame::GetDecAddress(CString &ss, CString &err_str) { ss = current_dec_address_; // Work out address from dec address string int ac; CJumpExpr::value_t vv; if (current_dec_address_.IsEmpty()) { err_str = "Expression is empty"; return -1; } vv = expr_.evaluate(current_dec_address_, 0 /*unused*/, ac /*unused*/, 10 /*dec ints*/); if (vv.typ == CJumpExpr::TYPE_INT) return current_address_ = vv.int64; else if (vv.typ == CJumpExpr::TYPE_NONE) { err_str = expr_.get_error_message(); return -1; } else { err_str = "Expression does not return an integer"; return -1; } } FILE_ADDRESS CMainFrame::GetHexAddress(CString &ss, CString &err_str) { ss = current_hex_address_; // Work out address from hex address string int ac; CJumpExpr::value_t vv; if (current_hex_address_.IsEmpty()) { err_str = "Expression is empty"; return -1; } vv = expr_.evaluate(current_hex_address_, 0 /*unused*/, ac /*unused*/, 16 /*hex int*/); if (vv.typ == CJumpExpr::TYPE_INT) return current_address_ = vv.int64; else if (vv.typ == CJumpExpr::TYPE_NONE) { err_str = expr_.get_error_message(); return -1; } else { err_str = "Expression does not return an integer"; return -1; } } // Add an address to the list of hex address combo void CMainFrame::AddHexHistory(const CString &ss) { if (ss.IsEmpty()) return; SetHexAddress(ss); // If recording macro indicate jump & save address jumped to // ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_address_tool, current_address_); if (hex_hist_.size() > 0 && hex_hist_.back() == ss) return; // Remove any duplicate entry from the list for (std::vector<CString>::iterator ps = hex_hist_.begin(); ps != hex_hist_.end(); ++ps) { if (*ps == ss) { hex_hist_.erase(ps); break; } } hex_hist_.push_back(ss); hex_hist_changed_ = clock(); } // Add an address to the list of dec address combo void CMainFrame::AddDecHistory(const CString &ss) { if (ss.IsEmpty()) return; SetDecAddress(ss); // If recording macro indicate jump & save address jumped to // ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_address_tool, current_address_); if (dec_hist_.size() > 0 && dec_hist_.back() == ss) return; // Remove any duplicate entry from the list for (std::vector<CString>::iterator ps = dec_hist_.begin(); ps != dec_hist_.end(); ++ps) { if (*ps == ss) { dec_hist_.erase(ps); break; } } dec_hist_.push_back(ss); dec_hist_changed_ = clock(); } // Retrieve hex/dec jump histories from registry void CMainFrame::LoadJumpHistory(CHexEditApp *aa) { ::LoadHist(hex_hist_, "HexJump", theApp.max_hex_jump_hist_); ::LoadHist(dec_hist_, "DecJump", theApp.max_dec_jump_hist_); hex_hist_changed_ = dec_hist_changed_ = clock(); } // Save hex/dec histories to registry void CMainFrame::SaveJumpHistory(CHexEditApp *aa) { ::SaveHist(hex_hist_, "HexJump", theApp.max_hex_jump_hist_); ::SaveHist(dec_hist_, "DecJump", theApp.max_dec_jump_hist_); } // Add a search string to the list box of the search combo void CMainFrame::AddSearchHistory(const CString &ss) { // current_search_string_ = ss; ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_find_text, ss); // Keep track of bytes entered in macro // Don't add to the list if already at the top if (search_hist_.size() > 0 && ss == search_hist_.back()) return; // Remove any duplicate entry from the list for (std::vector<CString>::iterator ps = search_hist_.begin(); ps != search_hist_.end(); ++ps) { if (ss == *ps) { search_hist_.erase(ps); break; } else if (ss.GetLength() > 0 && ss[0] != CSearchEditControl::sflag_char && ss.CompareNoCase(*ps) == 0) { // Doing hex search or case-insensitive search and strings // are the same (except for case) - so remove old one search_hist_.erase(ps); break; } } search_hist_.push_back(ss); } // Add a replace string to the history list void CMainFrame::AddReplaceHistory(const CString &ss) { ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_replace_text, ss); // Keep track of bytes entered in macro // Don't add to the list if already at the top if (replace_hist_.size() > 0 && ss == replace_hist_.back()) return; // Remove any duplicate entry from the list for (std::vector<CString>::iterator ps = replace_hist_.begin(); ps != replace_hist_.end(); ++ps) { if (ss == *ps) { replace_hist_.erase(ps); break; } } replace_hist_.push_back(ss); } // xxx changes required here (3.4?): // 1. Make max_search_hist_ etc options the user can change // 1a. Add individual "Clear Now" buttons for all lists // 2. On load - load all entries (ignore max_search_hist_ etc) // 3. On Save - set size of list to max_search_hist_ etc, then save all entries in the list // 4. Get rid of clear_on_exit_ etc options as this can now be done by seeting a size of zero. // 5. Clear reg entries past last used (since user can change hist sizes and we don't weant to leave unused one behind) // Retrieve search/replace histories from registry void CMainFrame::LoadSearchHistory(CHexEditApp *aa) { ::LoadHist(search_hist_, "Search", theApp.max_search_hist_); ::LoadHist(replace_hist_, "Replace", theApp.max_replace_hist_); } // Save search/replace histories to registry void CMainFrame::SaveSearchHistory(CHexEditApp *aa) { ::SaveHist(search_hist_, "Search", theApp.max_search_hist_); ::SaveHist(replace_hist_, "Replace", theApp.max_replace_hist_); } void CMainFrame::OnFindNext() { AddSearchHistory(current_search_string_); if (DoFind() && theApp.recording_) theApp.SaveToMacro(km_find_next, m_wndFind.GetOptions()); } void CMainFrame::OnSearchForw() { m_wndFind.SetDirn(CFindSheet::DIRN_DOWN); CFindSheet::scope_t scope = m_wndFind.GetScope(); if (scope != CFindSheet::SCOPE_EOF && scope != CFindSheet::SCOPE_ALL) m_wndFind.SetScope(CFindSheet::SCOPE_EOF); AddSearchHistory(current_search_string_); if (DoFind() && theApp.recording_) theApp.SaveToMacro(km_find_forw, m_wndFind.GetOptions()); } void CMainFrame::OnSearchBack() { m_wndFind.SetDirn(CFindSheet::DIRN_UP); CFindSheet::scope_t scope = m_wndFind.GetScope(); if (scope != CFindSheet::SCOPE_EOF && scope != CFindSheet::SCOPE_ALL) m_wndFind.SetScope(CFindSheet::SCOPE_EOF); AddSearchHistory(current_search_string_); if (DoFind() && theApp.recording_) theApp.SaveToMacro(km_find_back, m_wndFind.GetOptions()); } void CMainFrame::OnUpdateSearch(CCmdUI* pCmdUI) { pCmdUI->Enable(GetView() != NULL && (current_search_string_.GetLength() > 1 && (current_search_string_[0] == CSearchEditControl::sflag_char || current_search_string_[0] == CSearchEditControl::iflag_char ) || current_search_string_.FindOneOf("0123456789ABCDEFabcdef") > -1) ); } void CMainFrame::OnSearchSel() { CHexEditView *pview = GetView(); if (pview == NULL) { AfxMessageBox("There is no file open to search."); theApp.mac_error_ = 10; return; } // Get selection FILE_ADDRESS start, end; pview->GetSelAddr(start, end); ASSERT(start >= 0 && start <= end && end <= pview->GetDocument()->length()); if (start == end) { // Nothing selected, presumably in macro playback ASSERT(theApp.playing_); AfxMessageBox("Nothing selected to search for!"); theApp.mac_error_ = 10; return; } // Load the current selection into buf. Allow for trailing '\0', but there may // be less bytes if non-EBCDIC chars are found (EBCDIC mode) or chars < 13 (ASCII mode) unsigned char *buf = new unsigned char[size_t(end - start) + 1]; VERIFY(pview->GetDocument()->GetData(buf, size_t(end - start), start) == end - start); boolean do_hex = true; if (pview->CharMode() && pview->EbcdicMode()) { unsigned char *pp; // Pointer into buf buf[end-start] = '\0'; // Check if all chars are valid EBCDIC and set search text if so for (pp = buf; pp < buf+end-start; ++pp) if (e2a_tab[*pp] == '\0') break; else *pp = e2a_tab[*pp]; // Convert EBCDIC to ASCII if (pp == buf+end-start) do_hex = false; // No invalid EBCDIC chars found ASSERT(buf[end-start] == '\0'); // Check for buffer overrun m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_EBCDIC); m_wndFind.NewText((char *)buf); } else if (pview->CharMode()) { buf[end-start] = '\0'; // Check if all chars are normal ASCII text and set search text unsigned char *pp; for (pp = buf; pp < buf+end-start; ++pp) if (*pp <= '\r') break; if (pp == buf+end-start) do_hex = false; // No invalid chars found so do text search ASSERT(buf[end-start] == '\0'); // Check for buffer overrun m_wndFind.SetCharSet(CFindSheet::RB_CHARSET_ASCII); m_wndFind.NewText((char *)buf); } delete[] buf; if (do_hex) { // Change buf so that there's room for 2 hex digits + space per byte char *tbuf = new char[size_t(end - start)*3]; unsigned char cc; // One character from document FILE_ADDRESS address; // Current byte address in document char *pp; // Current position in search string being built const char *hex; CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (theApp.hex_ucase_) hex = "0123456789ABCDEF?"; else hex = "0123456789abcdef?"; ASSERT(start < end); // Make sure we don't put '\0' at tbuf[-1] for (address = start, pp = tbuf; address < end; ++address) { pview->GetDocument()->GetData(&cc, 1, address); *pp++ = hex[(cc>>4)&0xF]; *pp++ = hex[cc&0xF]; *pp++ = ' '; } *(pp-1) = '\0'; // Terminate string (overwrite last space) ASSERT(pp == tbuf + (end-start)*3); ASSERT(address == end); m_wndFind.NewHex((char *)tbuf); delete[] tbuf; } // Must be a forward search and fix scope m_wndFind.SetDirn(CFindSheet::DIRN_DOWN); CFindSheet::scope_t scope = m_wndFind.GetScope(); if (scope != CFindSheet::SCOPE_EOF && scope != CFindSheet::SCOPE_ALL) m_wndFind.SetScope(CFindSheet::SCOPE_EOF); AddSearchHistory(current_search_string_); if (DoFind() && theApp.recording_) theApp.SaveToMacro(km_find_sel, m_wndFind.GetOptions()); pview->SetFocus(); // This is nec as focus gets set to Find dialog } void CMainFrame::OnUpdateSearchSel(CCmdUI* pCmdUI) { CHexEditView *pview = GetView(); if (pview == NULL) { pCmdUI->Enable(FALSE); } else { FILE_ADDRESS start, end; // Current selection pview->GetSelAddr(start, end); pCmdUI->Enable(start < end); } } // Gets the previous document in the apps list of docs. If the current doc is at the start // it returns the last doc in the list. If there is only one entry it returns it. // Note that ther must be at least one entry (the current doc). CHexEditDoc *CMainFrame::GetPrevDoc(CHexEditDoc *pdoc) { CHexEditDoc *retval, *pdoc_temp; POSITION posn = theApp.m_pDocTemplate->GetFirstDocPosition(); ASSERT(posn != NULL); // First find pdoc in the list retval = NULL; while ((pdoc_temp = dynamic_cast<CHexEditDoc *>(theApp.m_pDocTemplate->GetNextDoc(posn))) != pdoc) retval = pdoc_temp; if (retval == NULL) { retval = pdoc_temp; // Current doc is at top of the list so get the last in the list while (posn != NULL) retval = dynamic_cast<CHexEditDoc *>(theApp.m_pDocTemplate->GetNextDoc(posn)); } return retval; } BOOL CMainFrame::DoFind() { // Get current view thence document to search CHexEditView *pview = GetView(); if (pview == NULL) { AfxMessageBox("There is no file open to search."); theApp.mac_error_ = 10; return FALSE; } CHexEditDoc *pdoc = pview->GetDocument(); // Get current find options const unsigned char *ss; const unsigned char *mask = NULL; size_t length; m_wndFind.GetSearch(&ss, &mask, &length); CFindSheet::dirn_t dirn = m_wndFind.GetDirn(); CFindSheet::scope_t scope = m_wndFind.GetScope(); BOOL wholeword = m_wndFind.GetWholeWord(); BOOL icase = !m_wndFind.GetMatchCase(); int tt = int(m_wndFind.GetCharSet()) + 1; // 1 = ASCII, 2 = Unicode, 3 = EBCDIC ASSERT(tt == 1 || tt == 2 || tt == 3); int alignment = m_wndFind.GetAlignment(); int offset = m_wndFind.GetOffset(); bool align_rel = m_wndFind.AlignRel(); FILE_ADDRESS base_addr; if (align_rel) base_addr = pview->GetSearchBase(); else base_addr = 0; FILE_ADDRESS start, end; // Range of bytes in the current file to search FILE_ADDRESS found_addr; // The address where the search text was found (or -1, -2) if (dirn == CFindSheet::DIRN_UP) { switch (scope) { #if 0 case CFindSheet::SCOPE_SEL: pview->GetSelAddr(start, end); break; #endif case CFindSheet::SCOPE_TOMARK: pview->GetSelAddr(start, end); if (start < end) end--; start = pview->GetMark(); break; case CFindSheet::SCOPE_FILE: start = 0; end = pdoc->length(); break; case CFindSheet::SCOPE_EOF: case CFindSheet::SCOPE_ALL: // We will search other files later too if nec. pview->GetSelAddr(start, end); if (start < end) end--; start = 0;; break; default: ASSERT(0); } // Do the search if ((found_addr = search_back(pdoc, start, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { if (scope == CFindSheet::SCOPE_ALL) { // Search through all other open files starting at the one before the current CHexEditDoc *pdoc2 = pdoc; // Now loop backwards through all the other docs starting at the one before the current while ((pdoc2 = GetPrevDoc(pdoc2)) != pdoc) { CHexEditView *pv2 = pdoc2->GetBestView(); ASSERT(pv2 != NULL); if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; // Search this file if ((found_addr = search_back(pdoc2, 0, pdoc2->length(), ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr != -1) { // Found in this file CChildFrame *pf2 = pv2->GetFrame(); if (pf2->IsIconic()) pf2->MDIRestore(); MDIActivate(pf2); pv2->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } // else (not found) try the next open file } // Now go back and search the start of the active document if ((found_addr = search_back(pdoc, end - (length-1) < 0 ? 0 : end - (length-1), pdoc->length(), ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { // Display not found message pview->show_pos(); // Restore display of orig address AfxMessageBox(not_found_mess(FALSE, icase, tt, wholeword, alignment)); } else { pview->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } else if (scope == CFindSheet::SCOPE_EOF && end < pdoc->length()) { CString mess = CString("The start of file was reached.\r\n") + not_found_mess(FALSE, icase, tt, wholeword, alignment) + CString("\r\nDo you want to continue from the end of file?"); SetAddress(start); // start == 0 theApp.OnIdle(0); // Force display of updated address // Give the user the option to search the top bit of the file that has not been searched if (AfxMessageBox(mess, MB_YESNO) == IDYES) { if ((found_addr = search_back(pdoc, end - (length-1) < 0 ? 0 : end - (length-1), pdoc->length(), ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { // Display not found message pview->show_pos(); // Restore display of orig address AfxMessageBox(not_found_mess(FALSE, icase, tt, wholeword, alignment)); } else { pview->MoveToAddress(found_addr, found_addr + length); // xxx should this add to nav pts?? #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } else { pview->show_pos(); // Restore display of orig address } } else { // Display not found message SetAddress(start); theApp.OnIdle(0); // Force display of updated address AfxMessageBox(not_found_mess(FALSE, icase, tt, wholeword, alignment)); pview->show_pos(); // Restore display of orig address } } else { // Found pview->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt if (scope == CFindSheet::SCOPE_FILE) { // Change to SCOPE_EOF so that next search does not find the same thing m_wndFind.SetScope(CFindSheet::SCOPE_EOF); } #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } else { // Downwards search switch (scope) { #if 0 case CFindSheet::SCOPE_SEL: pview->GetSelAddr(start, end); break; #endif case CFindSheet::SCOPE_TOMARK: pview->GetSelAddr(start, end); if (start < end) ++start; // Change to start search at byte after start of selection end = pview->GetMark(); break; case CFindSheet::SCOPE_FILE: start = 0; end = pdoc->length(); break; case CFindSheet::SCOPE_EOF: case CFindSheet::SCOPE_ALL: pview->GetSelAddr(start, end); if (start < end) ++start; // Change to start search at byte after start of selection end = pdoc->length(); break; default: ASSERT(0); } // Do the search if ((found_addr = search_forw(pdoc, start, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { if (scope == CFindSheet::SCOPE_ALL) { // Search through all other open files starting at the one after current // Note: GetFirst/NextDoc returns docs in the order they are displayed in the Window menu CHexEditDoc *pdoc2; POSITION posn = theApp.m_pDocTemplate->GetFirstDocPosition(); ASSERT(posn != NULL); // First find the current doc in the list while ((pdoc2 = dynamic_cast<CHexEditDoc *>(theApp.m_pDocTemplate->GetNextDoc(posn))) != pdoc) ASSERT(posn != NULL); // We must be able to find the current doc? // Now loop through all the other docs starting at the one after the current for (;;) { // Get the next doc (looping back to the top of the list if nec.) if (posn == NULL) posn = theApp.m_pDocTemplate->GetFirstDocPosition(); pdoc2 = dynamic_cast<CHexEditDoc *>(theApp.m_pDocTemplate->GetNextDoc(posn)); if (pdoc2 == pdoc) break; // We have gone through the whole list of docs CHexEditView *pv2 = pdoc2->GetBestView(); ASSERT(pv2 != NULL); if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; // Search this file if ((found_addr = search_forw(pdoc2, 0, pdoc2->length(), ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr != -1) { // Found in this file CChildFrame *pf2 = pv2->GetFrame(); if (pf2->IsIconic()) pf2->MDIRestore(); MDIActivate(pf2); pv2->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } // else (not found) try the next open file } // Now go back and search the start of the active document if ((found_addr = search_forw(pdoc, 0, start+length-1 > pdoc->length() ? pdoc->length() : start+length-1, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { // Display not found message pview->show_pos(); // Restore display of orig address AfxMessageBox(not_found_mess(TRUE, icase, tt, wholeword, alignment)); } else { pview->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } else if (scope == CFindSheet::SCOPE_EOF && start > 0) { CString mess = CString("The end of file was reached.\r\n") + not_found_mess(TRUE, icase, tt, wholeword, alignment) + CString("\r\nDo you want to continue from the start of file?"); SetAddress(end); theApp.OnIdle(0); // Force display of updated address // Give the user the option to search the top bit of the file that has not been searched if (AfxMessageBox(mess, MB_YESNO) == IDYES) { if ((found_addr = search_forw(pdoc, 0, start+length-1 > pdoc->length() ? pdoc->length() : start+length-1, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // Restore original display pos pview->show_pos(); theApp.mac_error_ = 10; return FALSE; } else if (found_addr == -1) { // Display not found message pview->show_pos(); // Restore display of orig address AfxMessageBox(not_found_mess(TRUE, icase, tt, wholeword, alignment)); } else { pview->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } else { pview->show_pos(); // Restore display of orig address } } else { // Display not found message SetAddress(end); theApp.OnIdle(0); // Force display of updated address AfxMessageBox(not_found_mess(TRUE, icase, tt, wholeword, alignment)); pview->show_pos(); // Restore display of orig address } } else { // Found pview->MoveWithDesc("Search Text Found ", found_addr, found_addr + length); // space at end means significant nav pt if (scope == CFindSheet::SCOPE_FILE) { // Change to SCOPE_EOF so that next search does not find the same thing m_wndFind.SetScope(CFindSheet::SCOPE_EOF); } #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Found"); #endif return TRUE; } } theApp.mac_error_ = 10; return FALSE; } void CMainFrame::OnReplace() { // Get current view thence document to search CHexEditView *pview = GetView(); if (pview == NULL) { AfxMessageBox("There is no file open to replace in."); theApp.mac_error_ = 2; return; } CHexEditDoc *pdoc = pview->GetDocument(); // Get current find options const unsigned char *ss; const unsigned char *mask = NULL; size_t length; m_wndFind.GetSearch(&ss, &mask, &length); CFindSheet::dirn_t dirn = m_wndFind.GetDirn(); CFindSheet::scope_t scope = m_wndFind.GetScope(); BOOL wholeword = m_wndFind.GetWholeWord(); BOOL icase = !m_wndFind.GetMatchCase(); int tt = int(m_wndFind.GetCharSet()) + 1; // 1 = ASCII, 2 = Unicode, 3 = EBCDIC ASSERT(tt == 1 || tt == 2 || tt == 3); int alignment = m_wndFind.GetAlignment(); int offset = m_wndFind.GetOffset(); bool align_rel = m_wndFind.AlignRel(); FILE_ADDRESS base_addr; if (align_rel) base_addr = pview->GetSearchBase(); else base_addr = 0; FILE_ADDRESS start, end; // Range of bytes in the current file to search FILE_ADDRESS found_addr; // The address where the search text was found (or -1, -2) // Check that the selection is the same as the search length (+ at start of file for SCOPE_FILE) pview->GetSelAddr(start, end); // If the appropriate search bytes are already selected we replace them and search for the next // ones, otherwise we just search for them // For whole file searches we need to check if the current selection is actually the first // (or last for backward searches) occurrence of the search bytes in the file if (scope == CFindSheet::SCOPE_FILE && end-start == length) { found_addr = -2; if (dirn == CFindSheet::DIRN_DOWN && (found_addr = search_forw(pdoc, 0, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); return; } else if (dirn == CFindSheet::DIRN_UP && (found_addr = search_back(pdoc, start, pdoc->length(), ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); return; } else ASSERT(found_addr != -2); // Check that the found occurrence is actually the selection if (found_addr != start) { // Not found (-1) or earlier occurrence - don't replace yet start = 0; end = -1; } } if (end-start == length) { // First test OK (selection length == search length) - now check if there is a match // Note: this is direction insensitive (we could have used search_back instead) if ((found_addr = search_forw(pdoc, start, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); return; } else if (found_addr > -1) { // The current selection == search text - replace the text unsigned char *pp; size_t replen; m_wndFind.GetReplace(&pp, &replen); pview->do_replace(start, start+length, pp, replen); } } DoFind(); AddSearchHistory(current_search_string_); AddReplaceHistory(current_replace_string_); if (theApp.recording_) theApp.SaveToMacro(km_replace, m_wndFind.GetOptions()); } void CMainFrame::OnReplaceAll() { // Get current view thence (first) document to search CHexEditView *pview = GetView(); if (pview == NULL) { AfxMessageBox("There is no file open to search."); theApp.mac_error_ = 2; return; } #ifdef REFRESH_OFF bool bb = theApp.refresh_off_; if (!bb) { theApp.refresh_off_ = true; theApp.disable_carets(); } #endif CWaitCursor wc; CHexEditDoc *pdoc = pview->GetDocument(); // Init counts int replace_count = 0; int file_count = 1; // Get current find options const unsigned char *ss; const unsigned char * mask = NULL; size_t length; m_wndFind.GetSearch(&ss, &mask, &length); CFindSheet::dirn_t dirn = m_wndFind.GetDirn(); CFindSheet::scope_t scope = m_wndFind.GetScope(); BOOL wholeword = m_wndFind.GetWholeWord(); BOOL icase = !m_wndFind.GetMatchCase(); int tt = int(m_wndFind.GetCharSet()) + 1; // 1 = ASCII, 2 = Unicode, 3 = EBCDIC ASSERT(tt == 1 || tt == 2 || tt == 3); int alignment = m_wndFind.GetAlignment(); int offset = m_wndFind.GetOffset(); bool align_rel = m_wndFind.AlignRel(); FILE_ADDRESS start, end; // Range of bytes in the current file to search FILE_ADDRESS found_addr; // The address where the search text was found (or -1, -2) switch (scope) { case CFindSheet::SCOPE_TOMARK: pview->GetSelAddr(start, end); if (dirn == CFindSheet::DIRN_UP) { if (start < end) end--; // Change to start search at byte before end of selection start = pview->GetMark(); } else { if (start < end) ++start; // Change to start search at byte after start of selection end = pview->GetMark(); } break; case CFindSheet::SCOPE_FILE: start = 0; end = pdoc->length(); break; case CFindSheet::SCOPE_EOF: pview->GetSelAddr(start, end); if (dirn == CFindSheet::DIRN_UP) { if (start < end) end--; // Change to start search at byte before end of selection start = 0; } else { if (start < end) ++start; // Change to start search at byte after start of selection end = pdoc->length(); } break; case CFindSheet::SCOPE_ALL: start = 0; end = pdoc->length(); break; default: ASSERT(0); } FILE_ADDRESS byte_count = end-start;// Count of number of bytes searched // Get the replacement text unsigned char *pp; size_t replen; m_wndFind.GetReplace(&pp, &replen); // Init the loop FILE_ADDRESS curr = start; // Current search position in current file CHexEditDoc *pdoc2 = pdoc; // Current file we are searching CHexEditView *pv2 = pview; // View of current file FILE_ADDRESS base_addr; if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; for (;;) { // Do the search if ((found_addr = search_forw(pdoc2, curr, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error #ifdef REFRESH_OFF if (!bb) { theApp.refresh_display(true); theApp.refresh_off_ = false; theApp.enable_carets(); } #endif // Message already displayed so just restore original display pos pview->show_pos(); return; } else if (found_addr == -1) { if (scope == CFindSheet::SCOPE_ALL && (pdoc2=GetPrevDoc(pdoc2)) != pdoc) { ++file_count; curr = 0; end = pdoc2->length(); pv2 = pdoc2->GetBestView(); if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; byte_count += pdoc2->length(); } else if (scope == CFindSheet::SCOPE_EOF && start > 0) { CString mess = CString("The end of file was reached.\r\n") + not_found_mess(TRUE, icase, tt, wholeword, alignment) + CString("\r\nDo you want to continue from the start of file?"); // Give the user the option to search the top bit of the file that has not been searched SetAddress(end); theApp.OnIdle(0); // Force display of updated address if (AfxMessageBox(mess, MB_YESNO) == IDYES) { wc.Restore(); curr = 0; end = start + length - 1; byte_count = end; // Whole file will now be searched start = 0; // Stop asking of above question again } else { break; // EOF and user chose not to continue from other end } } else { break; // search finished } } else { // Found pv2->do_replace(found_addr, found_addr+length, pp, replen); ++replace_count; curr = found_addr + replen; // Don't do replacements within subst. text as we could get into infinite loop if (dirn == CFindSheet::DIRN_DOWN) end += int(replen) - int(length); } } pview->show_pos(); // Restore display of orig address AddSearchHistory(current_search_string_); AddReplaceHistory(current_replace_string_); #ifdef REFRESH_OFF if (!bb) { theApp.refresh_display(true); theApp.refresh_off_ = false; theApp.enable_carets(); } #endif if (theApp.recording_) theApp.SaveToMacro(km_replace_all, m_wndFind.GetOptions()); // Get a comma-separated version of bytes searched char buf[40]; sprintf(buf, "%I64u", __int64(byte_count)); CString temp(buf); ::AddCommas(temp); CString mess; if (file_count > 1) mess.Format("Searched %s bytes in %d files.\n", temp, file_count); if (replace_count == 0) mess += "No occurrences were found."; else if (replace_count == 1) mess += "One occurrence replaced."; else { CString ss; ss.Format("Replaced %d occurrences.", replace_count); mess += ss; } AfxMessageBox(mess); } void CMainFrame::OnBookmarkAll() { if (m_wndFind.bookmark_prefix_.IsEmpty()) { AfxMessageBox("Bookmark All requires a bookmark prefix."); theApp.mac_error_ = 2; return; } // Get current view thence (first) document to search CHexEditView *pview = GetView(); if (pview == NULL) { AfxMessageBox("There is no file open to search."); theApp.mac_error_ = 2; return; } CWaitCursor wc; CHexEditDoc *pdoc = pview->GetDocument(); // Check if any bookmarks already exist in the set we are going to create CBookmarkList *pbl = theApp.GetBookmarkList(); ASSERT(pbl != NULL); int count; // Number of bookmarks already in the set long next_number = 0; // Number to use for next bookmark in the set if ((next_number = pbl->GetSetLast(m_wndFind.bookmark_prefix_, count)) > 0) { CBookmarkFind dlg; dlg.mess_.Format("%d bookmarks with the prefix \"%s\"\r" "already exist. Do you want to overwrite or\r" "append to this set of bookmarks?", count, (const char *)m_wndFind.bookmark_prefix_); switch (dlg.DoModal()) { case IDC_BM_FIND_OVERWRITE: pbl->RemoveSet(m_wndFind.bookmark_prefix_); // xxx does not remove doc bookmarks or dlg entries next_number = 0; break; case IDC_BM_FIND_APPEND: // nothing required here (next_number points to the next bookmark set number to use) break; case IDCANCEL: return; default: ASSERT(0); return; } } long start_number = next_number; int file_count = 1; // Get current find options const unsigned char *ss; const unsigned char *mask = NULL; size_t length; m_wndFind.GetSearch(&ss, &mask, &length); CFindSheet::dirn_t dirn = m_wndFind.GetDirn(); CFindSheet::scope_t scope = m_wndFind.GetScope(); BOOL wholeword = m_wndFind.GetWholeWord(); BOOL icase = !m_wndFind.GetMatchCase(); int tt = int(m_wndFind.GetCharSet()) + 1; // 1 = ASCII, 2 = Unicode, 3 = EBCDIC ASSERT(tt == 1 || tt == 2 || tt == 3); int alignment = m_wndFind.GetAlignment(); int offset = m_wndFind.GetOffset(); bool align_rel = m_wndFind.AlignRel(); FILE_ADDRESS start, end; // Range of bytes in the current file to search FILE_ADDRESS found_addr; // The address where the search text was found (or -1, -2) switch (scope) { case CFindSheet::SCOPE_TOMARK: pview->GetSelAddr(start, end); if (dirn == CFindSheet::DIRN_UP) { if (start < end) end--; // Change to start search at byte before end of selection start = pview->GetMark(); } else { if (start < end) ++start; // Change to start search at byte after start of selection end = pview->GetMark(); } break; case CFindSheet::SCOPE_FILE: start = 0; end = pdoc->length(); break; case CFindSheet::SCOPE_EOF: pview->GetSelAddr(start, end); if (dirn == CFindSheet::DIRN_UP) { if (start < end) end--; // Change to start search at byte before end of selection start = 0; } else { if (start < end) ++start; // Change to start search at byte after start of selection end = pdoc->length(); } break; case CFindSheet::SCOPE_ALL: start = 0; end = pdoc->length(); break; default: ASSERT(0); } FILE_ADDRESS byte_count = end-start;// Count of number of bytes searched bool bmerror_reported = false; // Init the loop FILE_ADDRESS curr = start; // Current search position in current file CHexEditDoc *pdoc2 = pdoc; // Current file we are searching CHexEditView *pv2 = pview; // View of current file FILE_ADDRESS base_addr; if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; for (;;) { // Do the search if ((found_addr = search_forw(pdoc2, curr, end, ss, mask, length, icase, tt, wholeword, alignment, offset, align_rel, base_addr)) == -2) { // User abort or some error (message already displayed) - just restore original display pos pview->show_pos(); return; } else if (found_addr == -1) { if (scope == CFindSheet::SCOPE_ALL && (pdoc2=GetPrevDoc(pdoc2)) != pdoc) { ++file_count; curr = 0; end = pdoc2->length(); pv2 = pdoc2->GetBestView(); if (align_rel) base_addr = pv2->GetSearchBase(); else base_addr = 0; byte_count += pdoc2->length(); } else if (scope == CFindSheet::SCOPE_EOF && start > 0) { CString mess = CString("The end of file was reached.\r\n") + not_found_mess(TRUE, icase, tt, wholeword, alignment) + CString("\r\nDo you want to continue from the start of file?"); // Give the user the option to search the top bit of the file that has not been searched SetAddress(end); theApp.OnIdle(0); // Force display of updated address if (AfxMessageBox(mess, MB_YESNO) == IDYES) { wc.Restore(); curr = 0; end = start + length - 1; byte_count = end; // Use whole file as byte count now start = 0; // Prevent "EOF reached" message appearing again } else { break; // EOF and user chose not to continue from other end } } else { break; // search finished } } else { // Found so add the bookmark CString bm_name; bm_name.Format("%s%05ld", (const char *)m_wndFind.bookmark_prefix_, long(next_number)); ++next_number; if (pdoc2->pfile1_ == NULL) { if (!bmerror_reported) { bmerror_reported = true; AfxMessageBox("Bookmarks cannot be added to new files\r\n" "that have not yet been written to disk."); } } else { int ii = pbl->AddBookmark(bm_name, pdoc2->pfile1_->GetFilePath(), found_addr, NULL, pdoc2); } curr = found_addr + 1; // Continue the search from the next byte } } pview->show_pos(); // Restore display of orig address AddSearchHistory(current_search_string_); if (theApp.recording_) theApp.SaveToMacro(km_bookmark_all, m_wndFind.GetOptions()); // Get a comma-separated version of bytes searched char buf[40]; sprintf(buf, "%I64u", __int64(byte_count)); CString temp(buf); ::AddCommas(temp); CString mess; if (file_count > 1) mess.Format("Searched %s bytes in %d files.\n", temp, file_count); else mess.Format("Searched %s bytes.\n", temp); if (next_number == start_number) mess += "No occurrences were found"; else if (next_number == start_number+1) { CString ss; ss.Format("Set one bookmark: %s%05ld", (const char *)m_wndFind.bookmark_prefix_, long(start_number)); mess += ss; } else { CString ss; ss.Format("Set %d bookmarks.\n\nFirst bookmark: %s%05ld\nLast bookmark: %s%05ld", next_number - start_number, (const char *)m_wndFind.bookmark_prefix_, (long)start_number, (const char *)m_wndFind.bookmark_prefix_, (long)next_number-1); mess += ss; } AfxMessageBox(mess); } // search_forw returns the address if the search text was found or // -1 if it was not found, or -2 on some error (message already shown) FILE_ADDRESS CMainFrame::search_forw(CHexEditDoc *pdoc, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr, const unsigned char *ss, const unsigned char *mask, size_t length, BOOL icase, int tt, BOOL ww, int aa, int offset, bool align_rel, FILE_ADDRESS base_addr) { ASSERT(start_addr <= end_addr && end_addr <= pdoc->length()); FILE_ADDRESS bg_next = pdoc->GetNextFound(ss, mask, length, icase, tt, ww, aa, offset, align_rel, base_addr, start_addr); if (bg_next == -1 || bg_next > -1 && bg_next + length > end_addr) { return -1; } else if (bg_next > -1) { // Found if (AbortKeyPress() && AfxMessageBox("Abort search?", MB_YESNO) == IDYES) { StatusBarText("Search aborted"); theApp.mac_error_ = 10; // pview->show_pos(); return -2; } return bg_next; } size_t buf_len = size_t(min(end_addr-start_addr, FILE_ADDRESS(search_buf_len + length - 1))); // ASSERT(length > 0 && length <= buf_len); // Warn of simple problems if (length == 0) { AfxMessageBox("Empty search sequence"); return -2; } if (bg_next == -3) theApp.StopSearches(); // we must abort all bg searches here otherwise we'll later try to start on threads where bg search has not been stopped // We have to do our own search since either: // background searches are off (bg_next == -4) // or the background search doesn't match (bg_next == -3) - and was stopped above // or the background search is not finished (bg_next == -2) so we forget it and do our own unsigned char *buf = new unsigned char[buf_len]; boyer bb(ss, length, mask); // Boyer-Moore searcher FILE_ADDRESS addr_buf = start_addr; // Current location in doc of start of buf FILE_ADDRESS show_inc = 0x100000; // How far between showing addresses FILE_ADDRESS next_show; // Next address to show to user FILE_ADDRESS slow_show; // Slow show update rate when we get here size_t got; // How many bytes just read // Are there enough bytes for a search? if (addr_buf + length <= end_addr) { got = pdoc->GetData(buf, length - 1, addr_buf); ASSERT(got == length - 1); // xxx file length may change? next_show = (addr_buf/show_inc + 1)*show_inc; slow_show = ((addr_buf+0x1000000)/0x1000000 + 1)*0x1000000; while (1) { unsigned char *pp; // Where search string's found (or NULL if not) if (addr_buf > next_show) { if (AbortKeyPress() && AfxMessageBox("Abort search?", MB_YESNO) == IDYES) { delete[] buf; // Start bg search anyway theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { pdoc->base_addr_ = base_addr; pdoc->StartSearch(start_addr, addr_buf); theApp.StartSearches(pdoc); } Progress(-1); StatusBarText("Search aborted"); theApp.mac_error_ = 10; // pview->show_pos(); return -2; } // Show search progress SetAddress(next_show); if (next_show >= slow_show) { Progress(int(((next_show-start_addr)*100)/(end_addr-start_addr))); show_inc = 0x1000000; } theApp.OnIdle(0); // Force display of updated address next_show += show_inc; } bool alpha_before = false; bool alpha_after = false; // Get the next buffer full and search it got = pdoc->GetData(buf + length - 1, buf_len - (length - 1), addr_buf + length - 1); if (ww) { // Work out if byte before current buffer is alphabetic if (tt == 1 && addr_buf > 0) { // Check if alphabetic ASCII unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf-1) == 1); alpha_before = isalnum(cc) != 0; } else if (tt == 2 && addr_buf > 1) { // Check if alphabetic Unicode unsigned char cc[2]; VERIFY(pdoc->GetData(cc, 2, addr_buf-2) == 2); alpha_before = isalnum(cc[0]) != 0; // Check if low byte has ASCII alpha } else if (tt == 3 && addr_buf > 0) { // Check if alphabetic EBCDIC unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf-1) == 1); alpha_before = isalnum(e2a_tab[cc]) != 0; } // Work out if byte after current buffer is alphabetic if (addr_buf + buf_len < pdoc->length()) { unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf + buf_len) == 1); if (tt == 3) alpha_after = isalnum(e2a_tab[cc]) != 0; else alpha_after = isalnum(cc) != 0; // ASCII and Unicode } } if ((pp = bb.findforw(buf, length - 1 + got, icase, tt, ww, alpha_before, alpha_after, aa, offset, base_addr, addr_buf)) != NULL) { // If we find lots of occurrences then the Esc key check in // above is never done so do it here too. if (AbortKeyPress() && AfxMessageBox("Abort search?", MB_YESNO) == IDYES) { delete[] buf; // Start bg search anyway theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { pdoc->base_addr_ = base_addr; pdoc->StartSearch(start_addr, addr_buf); theApp.StartSearches(pdoc); } Progress(-1); StatusBarText("Search aborted"); theApp.mac_error_ = 10; // pview->show_pos(); return -2; } // Start bg search to search the rest of the file theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { // We know that there are no occurrences from the start up to where we found // this one but we must not exclude the found address (addr_buf + (pp - buf)) // so that background search finds it and it is displayed pdoc->base_addr_ = base_addr; pdoc->StartSearch(start_addr, addr_buf + (pp - buf)); theApp.StartSearches(pdoc); } // MoveToAddress(addr_buf + (pp - buf), addr_buf + (pp - buf) + length); FILE_ADDRESS retval = addr_buf + (pp - buf); Progress(-1); delete[] buf; if (retval + length > end_addr) return -1; // found but after end of search area else return retval; // found } addr_buf += got; // Check if we're at the end yet if (addr_buf + length - 1 >= end_addr) { break; } // Move a little bit from the end to the start of the buffer // so that we don't miss sequences that overlap the pieces read memmove(buf, buf + buf_len - (length - 1), length - 1); } } Progress(-1); delete[] buf; // Start bg search to search the rest of the file theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { pdoc->base_addr_ = base_addr; if (end_addr - (length-1) > start_addr) pdoc->StartSearch(start_addr, end_addr - (length-1)); else pdoc->StartSearch(); theApp.StartSearches(pdoc); } return -1; // not found } // search_back returns the address if the search text was found or // -1 if it was not found, or -2 on some error (message already shown) FILE_ADDRESS CMainFrame::search_back(CHexEditDoc *pdoc, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr, const unsigned char *ss, const unsigned char *mask, size_t length, BOOL icase, int tt, BOOL ww, int aa, int offset, bool align_rel, FILE_ADDRESS base_addr) { ASSERT(start_addr <= end_addr && end_addr <= pdoc->length()); FILE_ADDRESS bg_next = pdoc->GetPrevFound(ss, mask, length, icase, tt, ww, aa, offset, align_rel, base_addr, end_addr - length); if (bg_next == -1 || bg_next > -1 && bg_next < start_addr) { return -1; } else if (bg_next > -1) { return bg_next; } size_t buf_len = size_t(min(end_addr-start_addr, FILE_ADDRESS(search_buf_len + length - 1))); // ASSERT(length > 0 && length <= buf_len); // Warn of simple problems if (length == 0) { AfxMessageBox("Empty search sequence"); return -2; } if (bg_next == -3) theApp.StopSearches(); // we must abort all bg searches here otherwise we'll later try to start on threads where bg search has not been stopped unsigned char *buf = new unsigned char[buf_len]; boyer bb(ss, length, mask); // Boyer-Moore searcher FILE_ADDRESS addr_buf = end_addr; // Current location in doc of end of buf // FILE_ADDRESS show_inc = 0x20000; // How far between showing addresses FILE_ADDRESS show_inc = 0x200000; // How far between showing addresses FILE_ADDRESS next_show; // Next address to show to user // FILE_ADDRESS slow_show; // Slow show update rate when we get here size_t got; // How many bytes just read // Are there enough bytes for a search? if (addr_buf >= start_addr + length) { next_show = (addr_buf/show_inc)*show_inc; // slow_show = ((addr_buf+0x800000)/0x800000)*0x800000; while (1) { unsigned char *pp; // Where search string's found (or NULL if not) if (addr_buf < next_show) { if (AbortKeyPress() && AfxMessageBox("Abort search?", MB_YESNO) == IDYES) { delete[] buf; // Start bg search anyway theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { pdoc->base_addr_ = base_addr; pdoc->StartSearch(addr_buf, end_addr - (length-1)); theApp.StartSearches(pdoc); } StatusBarText("Search aborted"); theApp.mac_error_ = 10; // pview->show_pos(); return -2; } // Show search progress SetAddress(next_show); theApp.OnIdle(0); // Force display of updated address // if (next_show >= slow_show) // show_inc = 0x200000; next_show += show_inc; } // Note that search_back uses a slightly different algorithm to search_forw, // in that for search_forw the buffer overlap area (so that search strings // are not missed that overlap reads) is kept using memmove() whereas // search_back reads the same bit of the file twice. This is simpler // esp. for backward searches but may sometimes be slower. // Get the next buffer full and search it if (addr_buf - start_addr < buf_len) { got = pdoc->GetData(buf, size_t(addr_buf - start_addr), start_addr); ASSERT(got == addr_buf - start_addr); bool alpha_before = false; bool alpha_after = false; if (ww) { // Work out if byte before current buffer is alphabetic if (tt == 1 && start_addr > 0) { // Check if alphabetic ASCII unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, start_addr-1) == 1); alpha_before = isalnum(cc) != 0; } else if (tt == 2 && start_addr > 1) { // Check if alphabetic Unicode unsigned char cc[2]; VERIFY(pdoc->GetData(cc, 2, start_addr-2) == 2); alpha_before = isalnum(cc[0]) != 0; // Check if low byte has ASCII alpha } else if (tt == 3 && start_addr > 0) { // Check if alphabetic EBCDIC unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, start_addr-1) == 1); alpha_before = isalnum(e2a_tab[cc]) != 0; } // Work out if byte after current buffer is alphabetic if (addr_buf < pdoc->length()) { unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf) == 1); if (tt == 3) alpha_after = isalnum(e2a_tab[cc]) != 0; else alpha_after = isalnum(cc) != 0; // ASCII and Unicode } } pp = bb.findback(buf, got, icase, tt, ww, alpha_before, alpha_after, aa, offset, base_addr, start_addr); } else { got = pdoc->GetData(buf, buf_len, addr_buf - buf_len); ASSERT(got == buf_len); bool alpha_before = false; bool alpha_after = false; if (ww) { // Work out if byte before current buffer is alphabetic if (tt == 1 && addr_buf - buf_len > 0) { // Check if alphabetic ASCII unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf - buf_len - 1) == 1); alpha_before = isalnum(cc) != 0; } else if (tt == 2 && addr_buf - buf_len > 1) { // Check if alphabetic Unicode unsigned char cc[2]; VERIFY(pdoc->GetData(cc, 2, addr_buf - buf_len - 2) == 2); alpha_before = isalnum(cc[0]) != 0; // Check if low byte has ASCII alpha } else if (tt == 3 && addr_buf - buf_len > 0) { // Check if alphabetic EBCDIC unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf - buf_len - 1) == 1); alpha_before = isalnum(e2a_tab[cc]) != 0; } // Work out if byte after current buffer is alphabetic if (addr_buf < pdoc->length()) { unsigned char cc; VERIFY(pdoc->GetData(&cc, 1, addr_buf) == 1); if (tt == 3) alpha_after = isalnum(e2a_tab[cc]) != 0; else alpha_after = isalnum(cc) != 0; // ASCII and Unicode } } pp = bb.findback(buf, got, icase, tt, ww, alpha_before, alpha_after, aa, offset, base_addr, addr_buf - buf_len); } if (pp != NULL) { // MoveToAddress(addr_buf - got + (pp - buf), addr_buf - got + (pp - buf) + length); FILE_ADDRESS retval = addr_buf - got + (pp - buf); // Start bg search to search the rest of the file theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { // Search all the addresses that have not been searched, but make sure to // include retval so this occurrence is also found in background search and displayed pdoc->base_addr_ = base_addr; pdoc->StartSearch(retval + 1, end_addr - (length-1)); theApp.StartSearches(pdoc); } delete[] buf; if (retval < start_addr) // Never happens? return -1; else return retval; // found } addr_buf -= got - (length - 1); // Check if we're at start of search buf yet if (addr_buf - start_addr < length) { break; } } } delete[] buf; // Start bg search to search the rest of the file theApp.NewSearch(ss, mask, length, icase, tt, ww, aa, offset, align_rel); if (bg_next == -3) { pdoc->base_addr_ = base_addr; if (end_addr - (length-1) > start_addr) pdoc->StartSearch(start_addr, end_addr - (length-1)); // Start bg search (start_addr->EOF already done) else pdoc->StartSearch(); theApp.StartSearches(pdoc); } return -1; // not found } CString CMainFrame::not_found_mess(BOOL forward, BOOL icase, int tt, BOOL ww, int aa) { #ifdef SYS_SOUNDS CSystemSound::Play("Search Text Not Found"); #endif CString mess = "The search item was not found:\r\n"; // There are none if (icase && tt == 3) mess += "- case-insensitive EBCDIC "; else if (tt == 3) mess += "- EBCDIC"; else if (icase && tt == 2) mess += "- case-insensitive Unicode "; else if (tt == 2) mess += "- Unicode "; else if (icase) mess += "- case-insensitive "; else if (forward) mess += "- forward "; else mess += "- backward "; if (ww) mess += "whole-word "; mess += "search\r\n"; if (aa == 2) mess += "- with word alignment"; else if (aa == 3) mess += "- with alignment on every 3rd byte"; else if (aa == 4) mess += "- with double-word alignment"; else if (aa == 8) mess += "- with quad-word alignment"; else if (aa > 1) { CString ss; ss.Format("- with alignment on every %dth byte", aa); mess += ss; } return mess; } // Open first (simple search) page of Find dialog void CMainFrame::OnEditFind() { if (GetView() != NULL) { m_paneFind.ShowAndUnroll(); m_wndFind.ShowPage(0); } } // Open 2nd page of find dialog void CMainFrame::OnEditFind2() { if (GetView() != NULL) { m_paneFind.ShowAndUnroll(); m_wndFind.ShowPage(1); } } // Open 4th (replace) page of Find dialog void CMainFrame::OnEditReplace() { if (GetView() != NULL) { m_paneFind.ShowAndUnroll(); m_wndFind.ShowPage(4); } } // We can't do a search unless there is a document open void CMainFrame::OnUpdateEditFind(CCmdUI* pCmdUI) { pCmdUI->Enable(GetView() != NULL); } void CMainFrame::OnCalculator() { show_calc(); m_wndCalc.SetFocus(); } /* void CMainFrame::OnOptionsScheme() { theApp.display_options(COLOUR_OPTIONS_PAGE, TRUE); } */ void CMainFrame::OnBookmarks() { m_paneBookmarks.ShowAndUnroll(); } void CMainFrame::OnEditGotoDec() { OnEditGoto(1); } void CMainFrame::OnEditGotoHex() { OnEditGoto(2); } void CMainFrame::OnEditGoto(int base_mode /*= 0*/) { CHexEditView *pview = GetView(); if (pview != NULL) { ASSERT(m_wndCalc.m_hWnd != 0); m_wndCalc.change_bits(64); switch (base_mode) { case 1: // Use base 10 addresses m_wndCalc.change_base(10); break; case 2: // Use base 16 addresses m_wndCalc.change_base(16); break; default: ASSERT(0); /* fall through */ case 0: // Change base depending on how view is displaying addresses if (pview->DecAddresses()) m_wndCalc.change_base(10); else m_wndCalc.change_base(16); break; } m_wndCalc.SetWindowText("Go To"); //ShowControlBar(&m_wndCalc, TRUE, FALSE); // xxx fix for MFC9 m_paneCalc.ShowAndUnroll(); // Make sure controls are up to date and put current address into it //m_wndCalc.UpdateData(FALSE); FILE_ADDRESS start, end; pview->GetSelAddr(start, end); m_wndCalc.Set(start); m_wndCalc.update_controls(); m_wndCalc.ShowBinop(); //m_wndCalc.FixFileButtons(); m_wndCalc.SetFocus(); m_wndCalc.StartEdit(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_goto); } } void CMainFrame::OnCalcSel() { CHexEditView *pview = GetView(); if (pview != NULL) { __int64 sel_val = 0; // Value from file to add to the calc ASSERT(m_wndCalc.m_hWnd != 0); FILE_ADDRESS start_addr, end_addr; // Current selection pview->GetSelAddr(start_addr, end_addr); if (start_addr == end_addr) end_addr = start_addr + m_wndCalc.ByteSize(); unsigned char buf[8]; size_t got = pview->GetDocument()->GetData(buf, min(8, size_t(end_addr - start_addr)), start_addr); if (pview->BigEndian()) { for (int ii = 0; ii < (int)got; ++ii) sel_val = (sel_val<<8) + buf[ii]; } else { while (got > 0) sel_val = (sel_val<<8) + buf[--got]; } // Change calc bits depending on size of selection if (end_addr - start_addr > 8 || got < size_t()) { ASSERT(0); AfxMessageBox("Selection too big for calculator!"); theApp.mac_error_ = 10; } else if (end_addr - start_addr > 4) { m_wndCalc.change_bits(64); } else if (end_addr - start_addr > 2) { m_wndCalc.change_bits(32); } else if (end_addr - start_addr > 1) { m_wndCalc.change_bits(16); } else { m_wndCalc.change_bits(8); } // if (pview->DecAddresses()) // m_wndCalc.change_base(10); // else // m_wndCalc.change_base(16); m_wndCalc.SetWindowText("Calculator"); //ShowControlBar(&m_wndCalc, TRUE, FALSE); // xxx fix for MFC9 m_paneCalc.ShowAndUnroll(); // Make sure controls are up to date and put current address into it //m_wndCalc.UpdateData(FALSE); m_wndCalc.Set(sel_val); m_wndCalc.update_controls(); m_wndCalc.ShowBinop(); //m_wndCalc.FixFileButtons(); m_wndCalc.SetFocus(); ((CHexEditApp *)AfxGetApp())->SaveToMacro(km_calc_dlg, 1); } } #if 0 void CMainFrame::OnUpdateEditGoto(CCmdUI* pCmdUI) { pCmdUI->Enable(GetView() != NULL); } #endif // Display control bars context menu // Note: With BCG this is now only used for status bar - should probably move to CStatBar void CMainFrame::bar_context(CPoint point) { #if 0 // Get the top level menu that contains the submenus used as popup menus CMenu top; BOOL ok = top.LoadMenu(IDR_CONTEXT); ASSERT(ok); if (!ok) return; CMenu *ppop = top.GetSubMenu(0); ASSERT(ppop != NULL); if (ppop != NULL) VERIFY(ppop->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this)); top.DestroyMenu(); #else CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); CContextMenuManager *pCMM = aa->GetContextMenuManager(); pCMM->ShowPopupMenu(IDR_CONTEXT_STATBAR, point.x, point.y, this); #endif } void CMainFrame::OnInitMenu(CMenu* pMenu) { // Remove this? CMDIFrameWndEx::OnInitMenu(pMenu); } // Toggle display of status bar BOOL CMainFrame::OnPaneCheck(UINT nID) { CHexEditApp *aa = dynamic_cast<CHexEditApp *>(AfxGetApp()); if (CMDIFrameWndEx::OnPaneCheck(nID)) { aa->SaveToMacro(km_bar, nID); return TRUE; } else { aa->mac_error_ = 2; return FALSE; } } // The following were added for BCG void CMainFrame::OnCustomize() { CHexEditCustomize *pdlg = new CHexEditCustomize(this); pdlg->EnableUserDefinedToolbars(); // Allow user to select commands that don't appear on any menus // pdlg->AddMenu(IDR_MISC); CMenu menu; VERIFY(menu.LoadMenu(IDR_MISC)); pdlg->AddMenuCommands(menu.GetSubMenu(0), FALSE, "Format commands"); pdlg->AddMenuCommands(menu.GetSubMenu(1), FALSE, "Navigation commands"); pdlg->AddMenuCommands(menu.GetSubMenu(2), FALSE, "Find commands"); pdlg->AddMenuCommands(menu.GetSubMenu(3), FALSE, "Aerial view commands"); menu.DestroyMenu(); // Get macro cmd names std::vector<CString> mac = GetMacroCommands(); MENUITEMINFO mii; memset(&mii, '\0', sizeof(mii)); mii.cbSize = sizeof(mii); mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE; mii.fState = MFS_ENABLED; mii.fType = MFT_STRING; menu.CreatePopupMenu(); for (int ii = 0; ii < mac.size(); ++ii) if (!mac[ii].IsEmpty()) { mii.wID = ID_MACRO_FIRST + ii; CString ss = "Macro:" + mac[ii]; mii.dwTypeData = ss.GetBuffer(); menu.InsertMenuItem(ID_MACRO_FIRST + ii, &mii); } pdlg->AddMenuCommands(&menu, FALSE, "Macros"); menu.DestroyMenu(); pdlg->ReplaceButton(ID_JUMP_HEX, CHexComboButton ()); pdlg->ReplaceButton(ID_JUMP_DEC, CDecComboButton ()); pdlg->ReplaceButton(ID_SEARCH, CFindComboButton ()); pdlg->ReplaceButton(ID_SCHEME, CMFCToolBarComboBoxButton(::IsUs() ? ID_SCHEME_US : ID_SCHEME, -1, CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP, 120)); pdlg->ReplaceButton(ID_BOOKMARKS, CBookmarksComboButton ()); pdlg->ReplaceButton(IDC_FONTNAME, CHexEditFontCombo(IDC_FONTNAME, -1 /*CImageHash::GetImageOfCommand(IDC_FONTNAME, FALSE)*/, RASTER_FONTTYPE | TRUETYPE_FONTTYPE | DEVICE_FONTTYPE, ANSI_CHARSET, WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | CBS_HASSTRINGS | CBS_OWNERDRAWFIXED, 175) ); pdlg->ReplaceButton(IDC_FONTSIZE, CHexEditFontSizeCombo(IDC_FONTSIZE, -1 /*CImageHash::GetImageOfCommand(IDC_FONTSIZE, FALSE)*/, WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWN, 50) ); // pdlg->AddToolBar("Main", IDR_MAINFRAME); // pdlg->AddButton("User", CMFCToolbarButton(ID_MARK, 1, "User Tool 1", TRUE)); // pdlg->AddButton("User", CMFCToolbarButton(ID_GOTO_MARK, 2, "User Tool 2", TRUE)); // pdlg->SetUserCategory("User"); menu.LoadMenu(IDR_MENUBUTTON); pdlg->ReplaceButton(ID_DISPLAY_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(0), -1, _T("Show Area"))); pdlg->ReplaceButton(ID_CHARSET_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(1), -1, _T("Char Set"))); pdlg->ReplaceButton(ID_CONTROL_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(2), -1, _T("Ctrl Chars"))); pdlg->ReplaceButton(ID_HIGHLIGHT_MENU, CMFCToolBarMenuButton(ID_HIGHLIGHT, *menu.GetSubMenu(3), -1 /*CImageHash::GetImageOfCommand(ID_HIGHLIGHT)*/ )); pdlg->ReplaceButton(ID_MARK_MENU, CMFCToolBarMenuButton(ID_GOTO_MARK, *menu.GetSubMenu(4), -1 /*CImageHash::GetImageOfCommand(ID_GOTO_MARK)*/ )); pdlg->ReplaceButton(ID_BOOKMARKS_MENU, CMFCToolBarMenuButton(ID_BOOKMARKS_EDIT, *menu.GetSubMenu(5), -1 /*CImageHash::GetImageOfCommand(ID_BOOKMARKS_EDIT)*/ )); pdlg->ReplaceButton(ID_NAV_BACK, CMFCToolBarMenuButton (ID_NAV_BACK, *menu.GetSubMenu(6), -1, _T("Navigate Backward"))); pdlg->ReplaceButton(ID_NAV_FORW, CMFCToolBarMenuButton (ID_NAV_FORW, *menu.GetSubMenu(7), -1, _T("Navigate Forward"))); pdlg->Create(); } BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext) { if (!CMDIFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext)) { return FALSE; } // Add some tools for example.... CUserToolsManager* pUserToolsManager = theApp.GetUserToolsManager (); if (pUserToolsManager != NULL && pUserToolsManager->GetUserTools().IsEmpty ()) { CUserTool* pTool = pUserToolsManager->CreateNewTool(); pTool->m_strLabel = _T("Notepad"); pTool->m_strArguments = _T("$(FilePath)"); pTool->SetCommand(_T("notepad.exe")); pTool = pUserToolsManager->CreateNewTool(); pTool->m_strLabel = _T("Windows Calculator"); pTool->SetCommand(_T("calc.exe")); } return TRUE; } #if 0 // This is now done in MFC9 by CMDIFrameWndEx::EnablePaneMenu LRESULT CMainFrame::OnToolbarContextMenu(WPARAM,LPARAM lp) { CPoint point(LOWORD(lp), HIWORD(lp)); CMenu menu; VERIFY(menu.LoadMenu(IDR_CONTEXT_BARS)); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); SetupToolbarMenu(*pPopup, ID_VIEW_USER_TOOLBAR1, ID_VIEW_USER_TOOLBAR10); CMFCPopupMenu* pPopupMenu = new CMFCPopupMenu; pPopupMenu->SetAutoDestroy(FALSE); pPopupMenu->Create(this, point.x, point.y, pPopup->GetSafeHmenu()); return 0; } #endif #if 0 // This is now handled automatically in MFC9 BOOL CMainFrame::OnToolsViewUserToolbar(UINT uiId) { CMFCToolBar* pUserToolBar = GetUserBarByIndex(uiId - ID_VIEW_USER_TOOLBAR1); if (pUserToolBar == NULL) { ASSERT(0); return FALSE; } ShowControlBar(pUserToolBar, !(pUserToolBar->GetStyle() & WS_VISIBLE), FALSE); RecalcLayout(); return TRUE; } void CMainFrame::OnUpdateToolsViewUserToolbar(CCmdUI* pCmdUI) { CMFCToolBar* pUserToolBar = GetUserBarByIndex(pCmdUI->m_nID - ID_VIEW_USER_TOOLBAR1); if (pUserToolBar == NULL) { pCmdUI->Enable(FALSE); return; } pCmdUI->Enable(); pCmdUI->SetCheck(pUserToolBar->GetStyle() & WS_VISIBLE); } #endif afx_msg LRESULT CMainFrame::OnMenuReset(WPARAM wp, LPARAM) { return 0; } afx_msg LRESULT CMainFrame::OnToolbarReset(WPARAM wp, LPARAM) { switch ((UINT)wp) { case IDR_STDBAR: { CMenu menu; menu.LoadMenu(IDR_MENUBUTTON); m_wndStandardBar.ReplaceButton(ID_DISPLAY_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(0), afxCommandManager->GetCmdImage(ID_DISPLAY_DROPDOWN) /*CImageHash::GetImageOfCommand(ID_DISPLAY_DROPDOWN)*/, _T("Show Area"))); m_wndStandardBar.ReplaceButton(ID_CHARSET_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(1), afxCommandManager->GetCmdImage(ID_CHARSET_DROPDOWN) /*CImageHash::GetImageOfCommand(ID_CHARSET_DROPDOWN)*/, _T("Char Set"))); m_wndStandardBar.ReplaceButton(ID_CONTROL_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(2), afxCommandManager->GetCmdImage(ID_CONTROL_DROPDOWN) /*CImageHash::GetImageOfCommand(ID_CONTROL_DROPDOWN)*/, _T("Ctrl Chars"))); } m_wndStandardBar.ReplaceButton(ID_SCHEME, CMFCToolBarComboBoxButton(::IsUs() ? ID_SCHEME_US : ID_SCHEME, -1, CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP, 120)); break; case IDR_EDITBAR: // Only req. because they're on default edit bar (customisation handled by BCG) m_wndEditBar.ReplaceButton(ID_SEARCH, CFindComboButton()); m_wndEditBar.ReplaceButton(ID_JUMP_HEX, CHexComboButton()); m_wndEditBar.ReplaceButton(ID_JUMP_DEC, CDecComboButton()); break; case IDR_FORMATBAR: { m_wndFormatBar.ReplaceButton(IDC_FONTNAME, CHexEditFontCombo(IDC_FONTNAME, -1 /*CImageHash::GetImageOfCommand(IDC_FONTNAME, FALSE)*/, RASTER_FONTTYPE | TRUETYPE_FONTTYPE | DEVICE_FONTTYPE, DEFAULT_CHARSET, WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | CBS_HASSTRINGS | CBS_OWNERDRAWFIXED, 175) ); #if 0 // We need to call InsertButton else the size does not get updated properly for some reason m_wndFormatBar.ReplaceButton(IDC_FONTSIZE, CHexEditFontSizeCombo(IDC_FONTSIZE, CImageHash::GetImageOfCommand(IDC_FONTSIZE, FALSE), WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWN, 50) ); #else int index = m_wndFormatBar.CommandToIndex(IDC_FONTSIZE); if (index == -1 || index > m_wndFormatBar.GetCount()) index = m_wndFormatBar.GetCount(); m_wndFormatBar.RemoveButton(index); m_wndFormatBar.InsertButton( CHexEditFontSizeCombo(IDC_FONTSIZE, -1 /*CImageHash::GetImageOfCommand(IDC_FONTSIZE, FALSE)*/, WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWN, 50), index); #endif CMenu menu; menu.LoadMenu(IDR_MENUBUTTON); #if 0 // No longer there (as drop-menus) m_wndFormatBar.ReplaceButton(ID_DISPLAY_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(0), CImageHash::GetImageOfCommand(ID_DISPLAY_DROPDOWN), _T("Show Area"))); m_wndFormatBar.ReplaceButton(ID_CHARSET_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(1), CImageHash::GetImageOfCommand(ID_CHARSET_DROPDOWN), _T("Char Set"))); m_wndFormatBar.ReplaceButton(ID_CONTROL_DROPDOWN, CMFCToolBarMenuButton (-1, *menu.GetSubMenu(2), CImageHash::GetImageOfCommand(ID_CONTROL_DROPDOWN), _T("Ctrl Chars"))); #endif m_wndFormatBar.ReplaceButton(ID_HIGHLIGHT_MENU, CMFCToolBarMenuButton(ID_HIGHLIGHT, *menu.GetSubMenu(3), -1 /*CImageHash::GetImageOfCommand(ID_HIGHLIGHT)*/ )); } m_wndFormatBar.ReplaceButton(ID_SCHEME, CMFCToolBarComboBoxButton(::IsUs() ? ID_SCHEME_US : ID_SCHEME, -1, CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP, 120)); break; case IDR_NAVBAR: { m_wndNavBar.ReplaceButton(ID_JUMP_HEX, CHexComboButton()); m_wndNavBar.ReplaceButton(ID_JUMP_DEC, CDecComboButton()); m_wndNavBar.ReplaceButton(ID_BOOKMARKS, CBookmarksComboButton()); CMenu menu; menu.LoadMenu(IDR_MENUBUTTON); m_wndNavBar.ReplaceButton(ID_MARK_MENU, CMFCToolBarMenuButton(ID_GOTO_MARK, *menu.GetSubMenu(4), -1 /*CImageHash::GetImageOfCommand(ID_GOTO_MARK)*/ )); m_wndNavBar.ReplaceButton(ID_BOOKMARKS_MENU, CMFCToolBarMenuButton(ID_BOOKMARKS_EDIT, *menu.GetSubMenu(5), -1 /*CImageHash::GetImageOfCommand(ID_BOOKMARKS_EDIT)*/ )); m_wndNavBar.ReplaceButton(ID_NAV_BACK, CMFCToolBarMenuButton(ID_NAV_BACK, *menu.GetSubMenu(6), -1 /*CImageHash::GetImageOfCommand(ID_NAV_BACK)*/ )); m_wndNavBar.ReplaceButton(ID_NAV_FORW, CMFCToolBarMenuButton(ID_NAV_FORW, *menu.GetSubMenu(7), -1 /*CImageHash::GetImageOfCommand(ID_NAV_FORW)*/ )); } break; case IDR_MAINFRAME: /* nothing here */ break; default: ASSERT(0); } return 0; } LRESULT CMainFrame::OnHelpCustomizeToolbars(WPARAM wp, LPARAM lp) { // CMFCToolBarsCustomizeDialog* pDlg = (CMFCToolBarsCustomizeDialog*)lp; // ASSERT_VALID (pDlg); DWORD help_id[] = { HIDD_CUST_COMMANDS, HIDD_CUST_TOOLBARS, HIDD_CUST_TOOLS, HIDD_CUST_KEYBOARD, HIDD_CUST_MENU, HIDD_CUST_MOUSE, HIDD_CUST_OPTIONS }; if (!::HtmlHelp(m_hWnd, theApp.htmlhelp_file_, HH_HELP_CONTEXT, help_id[(int)wp])) AfxMessageBox(AFX_IDP_FAILED_TO_LAUNCH_HELP); return 0; } void CMainFrame::OnClosePopupMenu(CMFCPopupMenu *pMenuPopup) { bool found = false; while (!popup_menu_.empty() && !found) { found = popup_menu_.back() == pMenuPopup; popup_menu_.pop_back(); } CMDIFrameWndEx::OnClosePopupMenu(pMenuPopup); menu_tip_.Hide(); } BOOL CMainFrame::OnShowPopupMenu (CMFCPopupMenu *pMenuPopup) { CMDIFrameWndEx::OnShowPopupMenu(pMenuPopup); if (pMenuPopup == NULL) return TRUE; popup_menu_.push_back(pMenuPopup); // used for displaying menu item tips // Now we scan the menu for any "dummy" items that are placeholders for dynamic menu changes // Nav point lists forward/backward if (pMenuPopup->GetMenuBar()->CommandToIndex(ID_NAV_BACK_DUMMY) >= 0) { if (CMFCToolBar::IsCustomizeMode ()) return FALSE; pMenuPopup->RemoveAllItems (); theApp.navman_.AddItems(pMenuPopup, false, ID_NAV_BACK_FIRST, NAV_RESERVED); } if (pMenuPopup->GetMenuBar()->CommandToIndex(ID_NAV_FORW_DUMMY) >= 0) { if (CMFCToolBar::IsCustomizeMode ()) return FALSE; pMenuPopup->RemoveAllItems (); theApp.navman_.AddItems(pMenuPopup, true, ID_NAV_FORW_FIRST, NAV_RESERVED); } // Replace dummy entry (ID_MACRO_LAST) with list of macros if (pMenuPopup->GetMenuBar()->CommandToIndex(ID_MACRO_LAST) >= 0) { if (CMFCToolBar::IsCustomizeMode ()) return FALSE; pMenuPopup->RemoveAllItems (); std::vector<CString> mac = GetMacroCommands(); for (int ii = 0; ii < mac.size(); ++ii) if (!mac[ii].IsEmpty()) pMenuPopup->InsertItem(CMFCToolBarMenuButton(ID_MACRO_FIRST + ii, NULL, -1, "Macro:" + mac[ii])); } // We generate 2 lists of templates // 1. based on Windows file type - file name (preceded by underscore) is the extension [ID_DFFD_OPEN_TYPE_DUMMY] // 2. others (not starting with underscore) [ID_DFFD_OPEN_OTHER_DUMMY] if (pMenuPopup->GetMenuBar()->CommandToIndex(ID_DFFD_OPEN_TYPE_DUMMY) >= 0) { if (CMFCToolBar::IsCustomizeMode ()) return FALSE; pMenuPopup->RemoveAllItems (); int count = 0; for (int ii = 0; ii < theApp.xml_file_name_.size() && ii < DFFD_RESERVED; ++ii) { if (theApp.xml_file_name_[ii].CompareNoCase("default") != 0 && theApp.xml_file_name_[ii].CompareNoCase("_windows_types") != 0 && theApp.xml_file_name_[ii].CompareNoCase("_common_types") != 0 && theApp.xml_file_name_[ii].CompareNoCase("_custom_types") != 0 && theApp.xml_file_name_[ii].CompareNoCase("_standard_types") != 0 && theApp.xml_file_name_[ii][0] == '_') { // Get type name based on the file extension CString ss = "." + theApp.xml_file_name_[ii].Mid(1); SHFILEINFO sfi; VERIFY(SHGetFileInfo(ss, FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(sfi), SHGFI_USEFILEATTRIBUTES | SHGFI_TYPENAME )); CString sext = sfi.szTypeName + CString(" (") + ss + _T(")"); // Store file type (+ ext) for display in file page pMenuPopup->InsertItem(CMFCToolBarMenuButton(ID_DFFD_OPEN_FIRST + ii, NULL, -1, sext)); ++count; } } if (count == 0) { CMFCToolBarMenuButton mb(ID_DFFD_OPEN_TYPE_DUMMY, NULL, -1, "No File Type Templates Found"); mb.SetStyle(mb.m_nStyle | TBBS_DISABLED); pMenuPopup->InsertItem(mb); } } if (pMenuPopup->GetMenuBar()->CommandToIndex(ID_DFFD_OPEN_OTHER_DUMMY) >= 0) { if (CMFCToolBar::IsCustomizeMode ()) return FALSE; pMenuPopup->RemoveAllItems (); int count = 0; for (int ii = 0; ii < theApp.xml_file_name_.size() && ii < DFFD_RESERVED; ++ii) { if (theApp.xml_file_name_[ii].CompareNoCase("default") != 0 && theApp.xml_file_name_[ii][0] != '_') { pMenuPopup->InsertItem(CMFCToolBarMenuButton(ID_DFFD_OPEN_FIRST + ii, NULL, -1, theApp.xml_file_name_[ii])); ++count; } } if (count == 0) { CMFCToolBarMenuButton mb(ID_DFFD_OPEN_TYPE_DUMMY, NULL, -1, "No Other Templates Found"); mb.SetStyle(mb.m_nStyle | TBBS_DISABLED); pMenuPopup->InsertItem(mb); } } return TRUE; } // Return a list of macro file names and their corresponding cmd IDs. // It remembers (in registry) the ID<->file name association so that // customizations are retained between invocations std::vector<CString> CMainFrame::GetMacroCommands() { std::vector<CString> retval; retval.resize(ID_MACRO_LAST - ID_MACRO_FIRST); ASSERT(theApp.mac_dir_.Right(1) == "\\"); // Get cmd IDs for already seen macro files (so IDs don't change between invocations) CString ss, strMacro; for (int ii = 0; ii < ID_MACRO_LAST - ID_MACRO_FIRST; ++ii) { ss.Format("%d", ii); strMacro = theApp.GetProfileString("MacroCmdId", ss); // If the entry exists and the macro file i still there then add it if (!strMacro.IsEmpty() && _access(theApp.mac_dir_ + strMacro + ".hem", 0) != -1) { retval[ii] = strMacro; } } // Now check all the macro files and add them if not present CFileFind ff; BOOL bContinue = ff.FindFile(theApp.mac_dir_ + "*.hem"); while (bContinue) { bContinue = ff.FindNextFile(); strMacro = ff.GetFileTitle(); if (strMacro[0] == '_') continue; // ignore macro files starting with underscore for (int ii = 0; ii < ID_MACRO_LAST - ID_MACRO_FIRST; ++ii) { if (strMacro == retval[ii]) { // Already handled so signal to skip it strMacro.Empty(); break; } } if (!strMacro.IsEmpty()) { for (int ii = 0; ii < ID_MACRO_LAST - ID_MACRO_FIRST; ++ii) { if (retval[ii].IsEmpty()) { // Found an empty slot retval[ii] = strMacro; ss.Format("%d", ii); theApp.WriteProfileString("MacroCmdId", ss, strMacro); break; } } } } return retval; } void CMainFrame::OnSearchCombo() { // We can't search if there is no file open if (GetView() == NULL) return; // Find the search combo control that is being used CMFCToolBarComboBoxButton* pFindCombo = NULL; CObList listButtons; if (CMFCToolBar::GetCommandButtons(ID_SEARCH_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { CMFCToolBarComboBoxButton* pCombo = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); if (pCombo != NULL && pCombo->GetEditCtrl()->GetSafeHwnd() == ::GetFocus()) { pFindCombo = pCombo; break; } } } if (pFindCombo == NULL || !CMFCToolBar::IsLastCommandFromButton(pFindCombo)) return; CString strFindText = pFindCombo->GetText(); if (!strFindText.IsEmpty()) { // Add to (or move to top of) combo list CComboBox* pCombo = pFindCombo->GetComboBox(); const int nCount = pCombo->GetCount(); CString strCmpText; // Check if it's already there and remove it if so, since it is added again at top for (int ind = 0; ind < nCount; ++ind) { pCombo->GetLBText(ind, strCmpText); if (strCmpText.GetLength() == strFindText.GetLength() && strCmpText == strFindText) { pCombo->DeleteString(ind); break; } } pCombo->InsertString(0,strFindText); pCombo->SetCurSel(0); // Start the search SendMessage(WM_COMMAND, ID_FIND_NEXT); SetFocus(); } } void CMainFrame::OnUpdateSearchCombo(CCmdUI* pCmdUI) { if (GetView() == NULL || pCmdUI->m_pOther == NULL) { pCmdUI->Enable(FALSE); return; } CObList listButtons; // Find the search tool that is being updated if (CMFCToolBar::GetCommandButtons(ID_SEARCH_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { CFindComboButton* pCombo = DYNAMIC_DOWNCAST(CFindComboButton, listButtons.GetNext(posCombo)); ASSERT(pCombo != NULL); CFindComboBox *pfcb = DYNAMIC_DOWNCAST(CFindComboBox, pCombo->GetComboBox()); ASSERT(pfcb != NULL && ::IsWindow(pfcb->GetSafeHwnd())); if (pfcb != NULL && ::IsWindow(pfcb->GetSafeHwnd()) && pCmdUI->m_pOther->m_hWnd == pfcb->GetSafeHwnd()) { // If combo is not in drop down state and current combo strings are wrong then ... if (!pfcb->GetDroppedState() && ComboNeedsUpdate(search_hist_, pfcb)) { // ... fix up items in the drop down list //CString strCurr; //pfcb->GetWindowText(strCurr); //DWORD sel = pfcb->GetEditSel(); int max_str = 0; // Max width of all the strings added so far CClientDC dc(pfcb); int nSave = dc.SaveDC(); dc.SelectObject(pfcb->GetFont()); pfcb->ResetContent(); for (std::vector<CString>::iterator ps = search_hist_.begin(); ps != search_hist_.end(); ++ps) { max_str = __max(max_str, dc.GetTextExtent(*ps).cx); // Add the string to the list pfcb->InsertString(0, *ps); } //pfcb->SetWindowText(strCurr); //pfcb->SetEditSel(LOWORD(sel), HIWORD(sel)); // Add space for margin and possible scrollbar max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); pfcb->SetDroppedWidth(__min(max_str, 780)); dc.RestoreDC(nSave); } // Fix up the edit control CString strCurr; CEdit *pedit = pCombo->GetEditCtrl(); ASSERT(pedit != NULL); pedit->GetWindowText(strCurr); if (strCurr != current_search_string_) pedit->SetWindowText(current_search_string_); break; } } } pCmdUI->Enable(TRUE); } void CMainFrame::OnHexCombo() { // We can't search if there is no file open if (GetView() == NULL) return; // Find the hex jump tool that was just activated CMFCToolBarComboBoxButton* pHexCombo = NULL; CObList listButtons; if (CMFCToolBar::GetCommandButtons(ID_JUMP_HEX_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); pHexCombo == NULL && posCombo != NULL; ) { CMFCToolBarComboBoxButton* pCombo = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); if (pCombo != NULL && pCombo->GetEditCtrl()->GetSafeHwnd() == ::GetFocus()) { pHexCombo = pCombo; break; } } } if (pHexCombo == NULL || !CMFCToolBar::IsLastCommandFromButton(pHexCombo)) return; CString ss = pHexCombo->GetText(); if (!ss.IsEmpty()) { // Add to (or move to top of) combo list CComboBox* pCombo = pHexCombo->GetComboBox(); const int nCount = pCombo->GetCount(); CString strCmpText; for (int ind = 0; ind < nCount; ++ind) { pCombo->GetLBText(ind, strCmpText); if (strCmpText.GetLength() == ss.GetLength() && strCmpText == ss) { pCombo->DeleteString(ind); break; } } pCombo->InsertString(0, ss); pCombo->SetCurSel(0); // Force the jump AddHexHistory(ss); SendMessage(WM_COMMAND, ID_JUMP_HEX_START); SetFocus(); } } void CMainFrame::OnUpdateHexCombo(CCmdUI* pCmdUI) { // We can't do anything without a file open or a control if (GetView() == NULL || pCmdUI->m_pOther == NULL) { pCmdUI->Enable(FALSE); return; } CObList listButtons; // Find the hex jump tool that is being updated if (CMFCToolBar::GetCommandButtons(ID_JUMP_HEX_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { CHexComboButton* pbut = DYNAMIC_DOWNCAST(CHexComboButton, listButtons.GetNext(posCombo)); ASSERT(pbut != NULL); CHexComboBox *phcb = DYNAMIC_DOWNCAST(CHexComboBox, pbut->GetComboBox()); ASSERT(phcb != NULL && ::IsWindow(phcb->GetSafeHwnd())); if (phcb != NULL && pCmdUI->m_pOther->m_hWnd == phcb->GetSafeHwnd()) { // If combo is not in drop down state and current combo strings are wrong then ... if (!phcb->GetDroppedState() && ComboNeedsUpdate(hex_hist_, phcb)) { // ... fix up items in the drop down list (including setting drop list width from longest string) int max_str = 0; // Max width of all the strings added so far CClientDC dc(phcb); int nSave = dc.SaveDC(); dc.SelectObject(phcb->GetFont()); phcb->ResetContent(); for (std::vector<CString>::iterator ps = hex_hist_.begin(); ps != hex_hist_.end(); ++ps) { max_str = __max(max_str, dc.GetTextExtent(*ps).cx); // Add the string to the list phcb->InsertString(0, *ps); } // Add space for margin and possible scrollbar max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); phcb->SetDroppedWidth(__min(max_str, 780)); dc.RestoreDC(nSave); } // Fix up the edit control text (if needs it) CString strCurr; CHexEditControl * pedit = DYNAMIC_DOWNCAST(CHexEditControl, pbut->GetEditCtrl()); ASSERT(pedit != NULL && pedit->IsKindOf(RUNTIME_CLASS(CHexEditControl))); pedit->GetWindowText(strCurr); int ac; CJumpExpr::value_t vv(-1); if (!strCurr.IsEmpty()) vv = expr_.evaluate(strCurr, 0 /*unused*/, ac /*unused*/, 16 /*hex int*/); if (strCurr != current_hex_address_ && vv.typ == CJumpExpr::TYPE_INT && vv.int64 != current_address_) { char buf[22]; if (theApp.hex_ucase_) sprintf(buf, "%I64X", __int64(current_address_)); else sprintf(buf, "%I64x", __int64(current_address_)); pedit->SetWindowText(buf); pedit->add_spaces(); } break; } } // for } pCmdUI->Enable(TRUE); } void CMainFrame::OnDecCombo() { // We can't search if there is no file open if (GetView() == NULL) return; // Find the dec jump combo control that was just activated CMFCToolBarComboBoxButton* pDecCombo = NULL; CObList listButtons; if (CMFCToolBar::GetCommandButtons(ID_JUMP_DEC_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { CMFCToolBarComboBoxButton* pCombo = DYNAMIC_DOWNCAST(CMFCToolBarComboBoxButton, listButtons.GetNext(posCombo)); if (pCombo != NULL && pCombo->GetEditCtrl()->GetSafeHwnd() == ::GetFocus()) { pDecCombo = pCombo; break; } } } if (pDecCombo == NULL || !CMFCToolBar::IsLastCommandFromButton(pDecCombo)) return; CString ss = pDecCombo->GetText(); if (!ss.IsEmpty()) { // Add to (or move to top of) combo list CComboBox* pCombo = pDecCombo->GetComboBox(); const int nCount = pCombo->GetCount(); CString strCmpText; // Check if already there and remove it if so for (int ind = 0; ind < nCount; ++ind) { pCombo->GetLBText(ind, strCmpText); if (strCmpText.GetLength() == ss.GetLength() && strCmpText == ss) { pCombo->DeleteString(ind); break; } } pCombo->InsertString(0, ss); pCombo->SetCurSel(0); // Force the jump AddDecHistory(ss); SendMessage(WM_COMMAND, ID_JUMP_DEC_START); SetFocus(); } } void CMainFrame::OnUpdateDecCombo(CCmdUI* pCmdUI) { // We can't do anything without a file open or a control if (GetView() == NULL || pCmdUI->m_pOther == NULL) { pCmdUI->Enable(FALSE); return; } CObList listButtons; // Find the hex jump tool that is being updated if (CMFCToolBar::GetCommandButtons(ID_JUMP_DEC_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { CDecComboButton* pbut = DYNAMIC_DOWNCAST(CDecComboButton, listButtons.GetNext(posCombo)); ASSERT(pbut != NULL); CDecComboBox *pdcb = DYNAMIC_DOWNCAST(CDecComboBox, pbut->GetComboBox()); ASSERT(pdcb != NULL && ::IsWindow(pdcb->GetSafeHwnd())); if (pdcb != NULL && pCmdUI->m_pOther->m_hWnd == pdcb->GetSafeHwnd()) { // If combo is not in drop down state and current combo strings are wrong then ... if (!pdcb->GetDroppedState() && ComboNeedsUpdate(dec_hist_, pdcb)) { // ... fix up items in the drop down list (including setting drop list width from longest string) int max_str = 0; // Max width of all the strings added so far CClientDC dc(pdcb); int nSave = dc.SaveDC(); dc.SelectObject(pdcb->GetFont()); pdcb->ResetContent(); for (std::vector<CString>::iterator ps = dec_hist_.begin(); ps != dec_hist_.end(); ++ps) { max_str = __max(max_str, dc.GetTextExtent(*ps).cx); // Add the string to the list pdcb->InsertString(0, *ps); } // Add space for margin and possible scrollbar max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); pdcb->SetDroppedWidth(__min(max_str, 780)); dc.RestoreDC(nSave); } // Fix up the edit control text (if needs it) CString strCurr; CDecEditControl * pedit = DYNAMIC_DOWNCAST(CDecEditControl, pbut->GetEditCtrl()); ASSERT(pedit != NULL && pedit->IsKindOf(RUNTIME_CLASS(CDecEditControl))); pedit->GetWindowText(strCurr); int ac; CJumpExpr::value_t vv(-1); if (!strCurr.IsEmpty()) vv = expr_.evaluate(strCurr, 0 /*unused*/, ac /*unused*/, 10 /*decimal int*/); if (strCurr != current_dec_address_ && vv.typ == CJumpExpr::TYPE_INT && vv.int64 != current_address_) { char buf[22]; sprintf(buf, "%I64d", __int64(current_address_)); pedit->SetWindowText(buf); pedit->add_commas(); } break; } } // for } pCmdUI->Enable(TRUE); } // We need a case-insensitive search that works the same as CBS_SORT struct case_insensitive_greater : binary_function<CString, CString, bool> { bool operator()(const CString &s1, const CString &s2) const { return s1.CompareNoCase(s2) > 0; } }; void CMainFrame::OnUpdateBookmarksCombo(CCmdUI* pCmdUI) { CHexEditView *pview = GetView(); if (pview == NULL || pCmdUI->m_pOther == NULL) { // If there is no file open or we don't know the control that we are updating we can't do anything pCmdUI->Enable(FALSE); return; } CHexEditDoc *pdoc = (CHexEditDoc *)pview->GetDocument(); // we need the current doc later to get its list of bookmarks CObList listButtons; // Find the bookmarks tool that is being updated if (CMFCToolBar::GetCommandButtons(ID_BOOKMARKS_COMBO, listButtons) > 0) { for (POSITION posCombo = listButtons.GetHeadPosition(); posCombo != NULL; ) { // Get the toolbar "control" CBookmarksComboButton * pCombo = DYNAMIC_DOWNCAST(CBookmarksComboButton, listButtons.GetNext(posCombo)); ASSERT(pCombo != NULL); // Get the associated combo box CBookmarksComboBox * pbcb = DYNAMIC_DOWNCAST(CBookmarksComboBox, pCombo->GetComboBox()); ASSERT(pbcb != NULL && ::IsWindow(pbcb->GetSafeHwnd())); // Check that the combo box is the one that is being updated if (pbcb != NULL && ::IsWindow(pbcb->GetSafeHwnd()) && pCmdUI->m_pOther->m_hWnd == pbcb->GetSafeHwnd()) { // Handle special case of file with no bookmarks ASSERT(pview != NULL && pdoc != NULL); if (pdoc->bm_index_.empty()) { CString ss; //if (pbcb->GetCount() > 0) pbcb->GetLBText(0, ss); if (pCombo->GetCount() > 0) ss = pCombo->GetText(); if (pCombo->GetCount() != 1 || ss != CString("No bookmarks")) { pCombo->RemoveAllItems(); pCombo->AddItem("No bookmarks"); pCombo->SelectItem(0, FALSE); pCombo->NotifyCommand(CBN_SELENDOK); // this is needed so text is updated } pCmdUI->Enable(FALSE); return; } CBookmarkList *pbl = theApp.GetBookmarkList(); // Get index of the closest bookmark above the current position in the view FILE_ADDRESS diff; // unused int current_bm = pview->ClosestBookmark(diff); // closest bookmark or -1 CString strCurrent; // name of closest bookmark if (current_bm > -1) strCurrent = pbl->name_[current_bm]; // Get vector of names of all bookmarks in the current file std::vector<CString> bm_names; for (int ii = 0; ii < (int)pdoc->bm_index_.size(); ++ii) { ASSERT(pdoc->bm_index_[ii] < (int)pbl->name_.size()); bm_names.push_back(pbl->name_[pdoc->bm_index_[ii]]); } // We must sort since the combo box sorts the bookmarks alphabetically (CBS_SORT) sort(bm_names.begin(), bm_names.end(), case_insensitive_greater()); // Fix up the drop down list if (!pbcb->GetDroppedState() && ComboNeedsUpdate(bm_names, pbcb)) { int max_str = 0; // Max width of all the strings added so far CClientDC dc(pbcb); int nSave = dc.SaveDC(); dc.SelectObject(pbcb->GetFont()); // Add all the bookmarks in this document to the list pCombo->RemoveAllItems(); for (int ii = 0; ii < (int)pdoc->bm_index_.size(); ++ii) { ASSERT(pdoc->bm_index_[ii] < (int)pbl->name_.size()); max_str = __max(max_str, dc.GetTextExtent(pbl->name_[pdoc->bm_index_[ii]]).cx); pCombo->AddItem(pbl->name_[pdoc->bm_index_[ii]] /*, pdoc->bm_index_[ii] */); } // Add space for margin and possible scrollbar max_str += dc.GetTextExtent("0").cx + ::GetSystemMetrics(SM_CXVSCROLL); pbcb->SetDroppedWidth(__min(max_str, 640)); dc.RestoreDC(nSave); // Set the current text to an invalid bookmark name (a space) - this is necessary as // the current text will be the last name added above but is not displayed in the // toolbar (only in the hidden combo box). We need to do this so pCombo->GetText() // does not compare equal with strCurrent below and the toolbar text is updated. pCombo->SetText(" "); } // If the closest bookmark is wrong (and combo is not in dropped state) ... if (!pbcb->GetDroppedState() && pCombo->GetText() != strCurrent) { // Update the text with the closest bookmark if (current_bm == -1) { // Deselect any combo box item (shows blank in toolbar) pCombo->SelectItem(-1, FALSE); pCombo->NotifyCommand(CBN_SELENDOK); // this is needed so the previous text is removed } else { // Search through the sorted combo list to find the associated entry for (int ii = 0; ii < pbcb->GetCount(); ++ii) { CString ss; pbcb->GetLBText(ii, ss); if (ss == strCurrent) { // Found it so show it and that's all we need to do pCombo->SelectItem(ii, FALSE); pCombo->NotifyCommand(CBN_SELENDOK); // needed to make sure the text is displayed break; } } } } } } } pCmdUI->Enable(TRUE); } BOOL CMainFrame::ComboNeedsUpdate(const std::vector<CString> &vs, CComboBox *pp) { int num_elts = pp->GetCount(); if (num_elts != vs.size()) return TRUE; CString ss; int ii; for (ii = 0; ii < num_elts; ++ii) { pp->GetLBText(ii, ss); if (vs[num_elts-ii-1] != ss) break; } // Check if list box is different in any way return ii != num_elts; } void CMainFrame::OnApplicationLook(UINT id) { CWaitCursor wait; theApp.m_nAppLook = id; switch (theApp.m_nAppLook) { case ID_VIEW_APPLOOK_WIN_2000: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager)); break; case ID_VIEW_APPLOOK_OFF_XP: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP)); break; case ID_VIEW_APPLOOK_WIN_XP: CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE; CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); break; case ID_VIEW_APPLOOK_OFF_2003: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003)); CDockingManager::SetDockingMode(DT_SMART); break; case ID_VIEW_APPLOOK_VS_2005: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005)); CDockingManager::SetDockingMode(DT_SMART); break; default: switch (theApp.m_nAppLook) { case ID_VIEW_APPLOOK_OFF_2007_BLUE: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue); break; case ID_VIEW_APPLOOK_OFF_2007_BLACK: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack); break; case ID_VIEW_APPLOOK_OFF_2007_SILVER: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver); break; case ID_VIEW_APPLOOK_OFF_2007_AQUA: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua); break; } CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007)); CDockingManager::SetDockingMode(DT_SMART); } RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE); theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook); } void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI) { pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID); } // Pass -1 to turn off progress, or a value from 0 to 100 to update the progress. void CMainFrame::Progress(int value) { if (value < 0) { if (progress_on_) { // Turn of progress m_wndStatusBar.EnablePaneProgressBar(0, -1); // disable progress bar (pane 0) progress_on_ = false; } } else { if (!progress_on_) { // Turn on progress m_wndStatusBar.EnablePaneProgressBar(0); // Turn on progress in left pane (pane 0) progress_on_ = true; } // Update progress m_wndStatusBar.SetPaneProgress(0, value < 100 ? value : 100); } } // Just for testing things (invoked with Ctrl+Shift+T) void CMainFrame::OnTest() { // m_wndSplitter.Flip(); } ///////////////////////////////////////////////////////////////////////////// // CJumpExpr - override of expr_eval that stores values for whole program // find_symbol just looks up a bookmark and returns the value as TYPE_INT. // Most of the parameters are not relevant (used for template expressions): // sym is the name of the bookmark. All other params are ignored. CJumpExpr::value_t CJumpExpr::find_symbol(const char *sym, value_t parent, size_t index, int *pac, __int64 &sym_size, __int64 &sym_address, CString &sym_str) { value_t retval; CHexEditView *pview; retval.typ = TYPE_NONE; // Default to symbol not found retval.error = false; retval.int64 = 0; sym_address = 0; // Put something here sym_size = 8; // bookmark = address, so why not 8 bytes if (parent.typ == TYPE_NONE && (pview = GetView()) != NULL) { ASSERT(pview->IsKindOf(RUNTIME_CLASS(CHexEditView))); CHexEditDoc *pdoc = pview->GetDocument(); ASSERT(pdoc != NULL && pdoc->IsKindOf(RUNTIME_CLASS(CHexEditDoc))); // Get the global bookmark list and check all the docs bookmarks CBookmarkList *pbl = theApp.GetBookmarkList(); for (int ii = 0; ii < (int)pdoc->bm_index_.size(); ++ii) { if (sym == pbl->name_[pdoc->bm_index_[ii]]) { retval.typ = TYPE_INT; retval.int64 = pdoc->bm_posn_[ii]; break; } } } return retval; } bool CJumpExpr::LoadVars() { bool retval = true; CString vars = theApp.GetProfileString("Calculator", "Vars"); CString ss; for (const char *pp = vars; *pp != '\0'; ++pp) { const char *pp2; // Get next var name pp2 = strchr(pp, '='); if (pp2 == NULL) { retval = false; if ((pp = strchr(pp, ';')) != NULL) continue; else return false; } CString name(pp, pp2 - pp); if (pp2 - pp > strspn(name, "abcdefghijklmonpqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789_$[]")) // [] are used in "array element" names { // Invalid var name retval = false; if ((pp = strchr(pp, ';')) != NULL) continue; else return false; } name.MakeUpper(); pp = pp2 + 1; // Move pp after '=' // Get the value value_t tmp; switch (*pp) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': tmp.typ = TYPE_INT; tmp.int64 = ::strtoi64(pp, 10, &pp2); break; case 'R': ++pp; tmp = value_t(strtod(pp, (char **)&pp2)); break; case 'D': ++pp; tmp.typ = TYPE_DATE; tmp.date = strtod(pp, (char **)&pp2); break; case '\"': // Find end of string (unescaped double quote) ss.Empty(); for (;;) { pp2 = pp + 1; pp = strchr(pp2, '"'); if (pp == NULL) return false; // there should be a terminating double-quote character if (*(pp-1) == '\\') ss += CString(pp2, pp - pp2 - 1) + "\""; // Escaped double-quote else { ss += CString(pp2, pp - pp2); // End of string break; } } pp2 = pp + 1; tmp = value_t(ss); break; case 'T': if (strncmp(pp, "TRUE", 4) != 0) { retval = false; if ((pp = strchr(pp, ';')) != NULL) continue; else return false; } tmp = value_t(true); pp2 = pp + 4; break; case 'F': if (strncmp(pp, "FALSE", 5) != 0) { retval = false; if ((pp = strchr(pp, ';')) != NULL) continue; else return false; } tmp = value_t(false); pp2 = pp + 5; break; default: retval = false; if ((pp = strchr(pp, ';')) != NULL) continue; else return false; } var_[name] = tmp; var_changed_ = clock(); // Make sure we see terminator (;) if (*pp2 != ';') { retval = false; if ((pp2 = strchr(pp2, ';')) == NULL) return false; } pp = pp2; } return retval; } // TBD: TODO save in a Unicode string since a string var is Unicode (if UNICODE_TYPE_STRING defined) void CJumpExpr::SaveVars() { CString vars; // All vars as text, separated by semicolon char buf[22]; // For formating values as text CString ss; for (std::map<CString, value_t>::const_iterator pp = var_.begin(); pp != var_.end(); ++pp) { if (pp->second.typ > TYPE_NONE && pp->second.typ <= TYPE_STRING) vars += pp->first + CString("="); switch (pp->second.typ) { case TYPE_NONE: // Just ignore these break; case TYPE_BOOLEAN: vars += pp->second.boolean ? "TRUE;" : "FALSE;"; break; case TYPE_INT: sprintf(buf, "%I64d;", __int64(pp->second.int64)); vars += buf; break; case TYPE_REAL: sprintf(buf, "R%.14g;", double(pp->second.real64)); vars += buf; break; case TYPE_DATE: sprintf(buf, "D%g;", double(pp->second.date)); vars += buf; break; case TYPE_STRING: ss = *pp->second.pstr; // get copy of string ss.Replace("\"", "\\\""); // escape double quotes vars += "\"" + ss + "\";"; break; default: ASSERT(0); } } theApp.WriteProfileString("Calculator", "Vars", vars); } // Get the names of all variables of a certain type vector<CString> CJumpExpr::GetVarNames(CJumpExpr::type_t typ) { vector<CString> retval; for (std::map<CString, value_t>::const_iterator pp = var_.begin(); pp != var_.end(); ++pp) { if (typ == TYPE_NONE || typ == pp->second.typ) retval.push_back(pp->first); } return retval; }
69acdb7b9a9cd7ca8bb2ce0f54d0f43b4d6d0b70
f290a5a8ca8d4270ff3532bfd618734799de7dc3
/Object-Oriented-Programming(C++)/lab_02/mathvector/iterator/Iterator.h
649f3a380b0a7c67a3ca296112ed1630caef0bd8
[]
no_license
Sakerini/BMSTU-4th-Sem
a96e7ec4bb8a6dff077a29a303d421a67a066822
cd4c06101a74b9962d1ec540062a885bbb3840cf
refs/heads/master
2022-11-05T11:58:04.888557
2020-06-18T17:32:58
2020-06-18T17:32:58
243,088,714
1
1
null
null
null
null
UTF-8
C++
false
false
771
h
Iterator.h
#ifndef LAB_02_ITERATOR_H #define LAB_02_ITERATOR_H #include <cstddef> #include "BaseIterator.h" namespace mathvector { template <typename T> class Iterator : public BaseIterator<T> { public: Iterator(const Iterator<T> &iter); Iterator(std::shared_ptr<T> p, size_t pos = 0); T &operator*(); const T operator*() const; T *operator->(); const T *operator->() const; }; template <typename T> class IteratorConst : public BaseIterator<T> { public: IteratorConst(const Iterator<T> &iter); IteratorConst(std::shared_ptr<T> p, size_t pos = 0); const T& operator*() const; const T *operator->() const; }; }; #include "Iterator.hpp" #endif //LAB_02_ITERATOR_H
ad88f81a245eca0d688b9cbd49f8e955139efd29
49a6b689080f73a545a36a2b78c4d19f5aa0dc27
/Huysmans_Marnick_TheLegendOfZelda/Heart.h
bc46a4f697e01536adf58e7d449027ce663d72a4
[]
no_license
MarnickHuysmans/TheLegendOfZelda
97da3a83a8c10d7fe08f833241e1b3fa157e2396
42de7c18ce84df5e8ee34ce21ee2ab3229ae0a3a
refs/heads/master
2023-08-29T05:47:43.391276
2021-10-11T20:04:12
2021-10-11T20:04:12
416,044,840
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
Heart.h
#pragma once #include "PickUp.h" #include "StaticPickUp.h" class Heart final : public PickUp, public StaticPickUp<Heart> { public: Heart(const Point2f& location); ~Heart() = default; Heart(const Heart& other) = delete; Heart(Heart&& other) noexcept = delete; Heart& operator=(const Heart& other) = delete; Heart& operator=(Heart&& other) noexcept = delete; void Draw() const override; bool Update(const float elapsedSec, Player& player) override; Heart* Copy() override; bool Overlap(Player& player) override; private: int GetValue() const override; const int m_Value{ 2 }; };
1d0c9ad938b91bfb10553ba84a0ee747844203ff
9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d
/tc/testprograms/BusSeating.cpp
8c435e748d18017fa002ad1541b3c6ea0087e6eb
[]
no_license
rodolfo15625/algorithms
7034f856487c69553205198700211d7afb885d4c
9e198ff0c117512373ca2d9d706015009dac1d65
refs/heads/master
2021-01-18T08:30:19.777193
2014-10-20T13:15:09
2014-10-20T13:15:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,462
cpp
BusSeating.cpp
#include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #define all(v) (v).begin(),(v).end() #define sz size() #define REP(i,a,b) for(int i=int(a);i<int(b);i++) #define fill(x,i) memset(x,i,sizeof(x)) #define foreach(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++) using namespace std; struct point{ int x, y; point(){} point(int _x, int _y){ x=_x; y=_y; } }; class BusSeating { public:double getArrangement(string leftRow, string rightRow) { double ans=1e+30; REP(a,0,1<<10) if(__builtin_popcount(a)<=3) REP(b,0,1<<10) if(__builtin_popcount(a)+__builtin_popcount(b)==3){ vector<point>v; REP(i,0,10) if((a&(1<<i)) && leftRow[i]=='-') v.push_back(point(i,0)); REP(i,0,10) if((b&(1<<i)) && rightRow[i]=='-') v.push_back(point(i,2)); if(v.sz==3){ double aux=0; REP(i,0,2) aux+=hypot(v[i].x-v[i+1].x,v[i].y-v[i+1].y); aux+=hypot(v[0].x-v[2].x,v[0].y-v[2].y); ans=min(ans,aux); } } return ans; } //Powered by [Ziklon] }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, string p0, string p1, bool hasAnswer, double p2) { cout << "Test " << testNum << ": [" << "\"" << p0 << "\"" << "," << "\"" << p1 << "\""; cout << "]" << endl; BusSeating *obj; double answer; obj = new BusSeating(); clock_t startTime = clock(); answer = obj->getArrangement(p0, p1); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p2 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = fabs(p2 - answer) <= 1e-9 * max(1.0, fabs(p2)); } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; string p0; string p1; double p2; { // ----- test 0 ----- p0 = "----------"; p1 = "----------"; p2 = 4.0; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 1 ----- p0 = "XXX-X-XX-X"; p1 = "-XXXX---XX"; p2 = 4.0; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 2 ----- p0 = "XXXXXXXXXX"; p1 = "-XX-XX-X--"; p2 = 6.0; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 3 ----- p0 = "XXX-X-XX-X"; p1 = "XXX-X-XX-X"; p2 = 6.82842712474619; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
0d4520f5cbed3a950eff405c89ea95188a5e40a4
ecb3f3c056c3c030444d09e5207617bacddffe3f
/Source/HarmonyFrameWork/Graphics/Shader/DirectX/ver.11/Private/SimplePolygon3DShader.cpp
9ca7b325d142cac5c3efb1f438b8f23d7ce6a61a
[]
no_license
Hondy000/Reso
b5949b16f7803f1bb636d36f792316ef57495063
fae9ed9041fca671de108d7689b873f581e3dbaf
refs/heads/master
2020-04-16T23:42:55.168299
2016-11-24T02:55:01
2016-11-24T02:55:01
48,768,394
0
0
null
null
null
null
UTF-8
C++
false
false
5,502
cpp
SimplePolygon3DShader.cpp
 #include "../Public/SimplePolygon3DShader.h" #include "../../../../RenderDevice/Basic/Public/RendererManager.h" #include "../../../../VertexLayout/Public/BaseVertexLayout.h" #include "../../../../RenderObject/Public/BaseRenderMeshObject.h" #include "../../../../Texture/Public/BaseTexture2D.h" #include "../../../../RenderDevice/Basic/Public/BaseRenderDeviceManager.h" #include "../../../../RenderDevice/DirectX/ver.11/Public/DirectX11RenderDeviceManager.h" #include "..\..\..\..\Matetial\Public\Material.h" #include "..\..\..\..\RenderObject\Public\SubMesh.h" #include "..\..\..\..\Public\BaseGraphicsCommand.h" #include "..\..\..\..\..\Core\Task\Public\TaskSystem.h" using namespace std; bool SimplePolygon3DShader::Setup() { HRESULT hr; m_spVertexLayout = std::shared_ptr<BaseVertexLayout>(new BaseVertexLayout); D3D11_INPUT_ELEMENT_DESC layput[2]; layput[0].SemanticName = "POSITION"; layput[0].SemanticIndex = 0; layput[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; layput[0].InputSlot = 0; layput[0].AlignedByteOffset = 0; layput[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; layput[0].InstanceDataStepRate = 0; layput[1].SemanticName = "TEXCOORD"; layput[1].SemanticIndex = 0; layput[1].Format = DXGI_FORMAT_R32G32_FLOAT; layput[1].InputSlot = 0; layput[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; layput[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; layput[1].InstanceDataStepRate = 0; // 使う固定バッファは1 m_constantBuffers.resize(1); m_constantBuffers[0] = std::shared_ptr<ConstantBuffer>(new ConstantBuffer); hr = sRENDER_DEVICE_MANAGER->CreatePixelShaderFromFile(m_cpPixelShader, m_cpPSClassLinkage, _T("Resource/Shader/HLSL/SimplePolygon3D.hlsl"), "PS_Main", "ps_4_0_level_9_1",false); hr = sRENDER_DEVICE_MANAGER->CreateVertexShaderFromFile(m_cpVertexShader, _T("Resource/Shader/HLSL/SimplePolygon3D.hlsl"), "VS_Main", "vs_4_0_level_9_1", m_spVertexLayout->GetMain(), layput, 2); // 空で固定バッファを用意 HFMATRIX mat[3]; hr = m_constantBuffers[0]->SetData(mat, sizeof(HFMATRIX), 3, BaseBuffer::ACCESS_FLAG::WRITEONLY); return hr; } void SimplePolygon3DShader::Destroy() { } bool SimplePolygon3DShader::PreProcessOfRender(std::shared_ptr<SubMesh> shape, std::shared_ptr<Material>materials) { bool result; D3D11_MAPPED_SUBRESOURCE mappedResource; UINT bufferNumber; HFMATRIX world, view, proj; sRENDER_DEVICE_MANAGER->GetTransform(&world, HFTS_WORLD); sRENDER_DEVICE_MANAGER->GetTransform(&view, HFTS_VIEW); sRENDER_DEVICE_MANAGER->GetTransform(&proj, HFTS_PERSPECTIVE ); // Lock the constant buffer so it can be written to. result = sRENDER_DEVICE_MANAGER->GetImmediateContext()->Map(m_constantBuffers[0]->Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. HFMATRIX* wvp = (HFMATRIX*)(mappedResource.pData); *wvp = world*view*proj; *wvp = HFMatrixTranspose( *wvp); // Unlock the constant buffer. sRENDER_DEVICE_MANAGER->GetImmediateContext()->Unmap(m_constantBuffers[0]->Get(), 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // テクスチャをセット std::shared_ptr<BaseTexture2D> spTexture; ////GeneralFactory<BaseTexture2D>::GetInstance().Get(index.searchID, index.pMaterialIndex[0], spTexture); sRENDER_DEVICE_MANAGER->GetImmediateContext()->PSSetShaderResources(0, 1, materials->GetDiffuseTexture()->GetSharderResorceView().GetAddressOf()); // マトリクスをセット sRENDER_DEVICE_MANAGER->GetImmediateContext()->VSSetConstantBuffers(bufferNumber, 1, m_constantBuffers[0]->GetAddressOf()); const UINT stride = shape->GetStride(); const UINT offset = 0; // 頂点バッファのセット sRENDER_DEVICE_MANAGER->GetImmediateContext()->IASetVertexBuffers(0, 1, shape->GetVertexBuffers()[0]->GetAddressOf(), &stride, &offset); // インデックスバッファのセット sRENDER_DEVICE_MANAGER->GetImmediateContext()->IASetIndexBuffer(shape->GetIndexBuffer()->Get(), DXGI_FORMAT_R32_UINT, 0); // プリミティブ タイプおよびデータの順序に関する情報を設定 sRENDER_DEVICE_MANAGER->GetImmediateContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); return 0; } bool SimplePolygon3DShader::Render() { bool result = E_FAIL; // Set the vertex input layout. sRENDER_DEVICE_MANAGER->GetImmediateContext()->IASetInputLayout(m_spVertexLayout->GetMain().Get()); // Set the vertex and pixel shaders that will be used to render. sRENDER_DEVICE_MANAGER->GetImmediateContext()->VSSetShader(m_cpVertexShader.Get(), NULL, 0); sRENDER_DEVICE_MANAGER->GetImmediateContext()->PSSetShader(m_cpPixelShader.Get(), NULL, 0); // Set the sampler states in the pixel shader. sRENDER_DEVICE_MANAGER->GetImmediateContext()->PSSetSamplers(0, 1, m_cpSamplerState.GetAddressOf()); // Render the geometry. sRENDER_DEVICE_MANAGER->GetImmediateContext()->DrawIndexed(6, 0, 0); return result; } bool SimplePolygon3DShader::PostProcessOfRender() { return bool(); } void SimplePolygon3DShader::CreateAndRegisterGraphicsCommand(std::shared_ptr<BaseRenderMeshObject> renderObject, UINT element) { std::shared_ptr<RenderMeshCommmand> rmCommand = std::make_shared<RenderMeshCommmand>(); rmCommand->SetRenderMeshElement(element); rmCommand->SetRenderObject(renderObject); rmCommand->SetGraphicsPriority(m_graphicsPriority); sTASK_SYSTEM->RegisterGraphicsCommand(rmCommand); }
ddce18e37977ade2d69b2203326d3f058de27720
1e60818de59b0b4be8ce5587f911f5244a23096a
/include/dataset.hpp
9c57ac5269a0d7a32151d4d0d0e65fc6f7cfb711
[ "MIT" ]
permissive
hantaolii/ClosedMDCOP-Miner
694363f90569eb100df57316fc09b2c148519359
d165e70a086a66d5fd6bc3deacabc1d4411e373c
refs/heads/master
2020-04-08T01:44:50.305495
2016-11-15T11:07:28
2016-11-15T11:07:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
511
hpp
dataset.hpp
#ifndef DATASET_HPP #define DATASET_HPP #include <fstream> #include <map> #include <memory> #include <set> #include "object.hpp" struct Dataset { std::set<EventType> event_types; std::set<std::shared_ptr<Object>> objects; std::map<EventType, std::set<std::shared_ptr<Object>>> objects_by_event_type; std::map<TimeSlot, std::set<std::shared_ptr<Object>>> objects_by_time_slot; }; Dataset construct_dataset(std::ifstream&); void print_dataset_info(const Dataset&); #endif // DATASET_HPP
104e798a236ba3231b67b38bee098e24de6c47f5
b517d05dadbeba3365beb1f1365938b421548a85
/cpp/sum/sum.hpp
2f5c83c17e20732afd8afa61c18432ce9c6cc998
[]
no_license
shayne-fletcher/zen
d893219bf95e562c2a8f7234adc08598086f6498
5fefe328e223cf650d39e7d9dc14030544bd621b
refs/heads/master
2023-07-05T21:36:35.241768
2023-06-25T18:15:38
2023-06-25T18:15:38
4,950,943
12
6
null
2021-07-24T17:59:17
2012-07-08T23:30:29
OCaml
UTF-8
C++
false
false
2,688
hpp
sum.hpp
#if !defined (SUM_81D195F4_819A_4E24_A6BF_E9630B3495E8_H) # define SUM_81D195F4_819A_4E24_A6BF_E9630B3495E8_H # include "recursive_union.hpp" namespace foo { namespace detail { template <std::size_t I, class T, class... Ts> struct index_of_impl; template <std::size_t I, class T, class... Ts> struct index_of_impl<I, T, T, Ts...> { static auto const value = I; }; template <std::size_t I, class T, class... Ts> struct index_of_impl<I, T, recursive_wrapper<T>, Ts...> { static auto const value = I; }; template <std::size_t I, class X, class T, class... Ts> struct index_of_impl<I, X, T, Ts...>{ static auto const value = index_of_impl<I + 1, X, Ts...>::value; }; }//namespace<detail> template <class T, class... Ts> struct index_of { static auto const value = detail::index_of_impl<0u, T, Ts...>::value; }; #if defined(_MSC_VER) # pragma warning(pop) #endif//defined (_MSC_VER) template <class... Ts> class sum_type { private: std::size_t cons; recursive_union<Ts...> data; public: sum_type () = delete; sum_type (sum_type const& other) : cons (other.cons) { data.copy (cons, other.data); } sum_type (sum_type&& other) : cons (other.cons) { data.move (cons, std::move (other.data)); } template <class T, class... Args> explicit sum_type (constructor<T> t, Args&&... args) : data (t, std::forward<Args>(args)...), cons (index_of<T, Ts...>::value) {} ~sum_type() { data.destruct (cons); } sum_type& operator= (sum_type const& other) { if (std::addressof (other) == this) return *this; data.destruct (const); cons = s.cons; data.copy (cons, s.data); return *this; } template <class R, class... Fs> R match(Fs&&... fs) const { using indicies = mk_range<0, sizeof... (Ts) - 1>; return union_visitor<R, indicies, Ts...>::visit ( data, cons, std::forward<Fs>(fs)...); } template <class R, class... Fs> R match(Fs&&... fs) { using indicies = mk_range<0, sizeof... (Ts) - 1>; return union_visitor<R, indicies, Ts...>::visit ( data, cons, std::forward<Fs>(fs)...); } template <class... Fs> void match(Fs&&... fs) const { using indicies = mk_range<0, sizeof... (Ts) - 1>; union_visitor<void, indicies, Ts...>::visit ( data, cons, std::forward<Fs>(fs)...); } template <class... Fs> void match(Fs&&... fs) { using indicies = mk_range<0, sizeof... (Ts) - 1>; union_visitor<void, indicies, Ts...>::visit ( data, cons, std::forward<Fs>(fs)...); } }; }//namespace foo #endif //!defined (SUM_81D195F4_819A_4E24_A6BF_E9630B3495E8_H)
4dcd2196aa7495a747f03f60a743d3c9f6f7543d
a492a87d24dbaaa9b239e98c43b7a70fe6cd95aa
/Graph/Edmond Karp.cpp
c40f594cc8a64c3d1221eaa494de7bcc2df99405
[]
no_license
nhatlonggunz/Algorithm-And-Data-Structure
58260e5650b4ffe5d4d16b67642e37ac2b656473
65d950ed1f883e3ec0f48a5a92924a4f6c4b718a
refs/heads/master
2020-04-30T00:31:32.506070
2019-04-17T20:06:35
2019-04-17T20:06:35
176,504,868
2
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
Edmond Karp.cpp
#include <vector> #include <queue> #include <iostream> using namespace std; #define maxN long(1e3) + 3 int n, s, t, mf, c[maxN][maxN], f[maxN][maxN]; vector<int> g[maxN], p; bool findPath() { int u, v; queue<int> q; q.push(s); p.assign(n + 1, 0); p[s] = -1; while(!q.empty()) { u = q.front(); q.pop(); if(u == t) return true; for(unsigned i = 0; i < g[u].size(); i++) { v = g[u][i]; if(!p[v] && f[u][v] < c[u][v]) { p[v] = u; if(v == t) return true; q.push(v); } } } return false; } void augment() { int u, v, flow = long(1e9); for(v = t; (u = p[v]) != -1; v = u) flow = min(flow, c[u][v] - f[u][v]); for(v = t; (u = p[v]) != -1; v = u) f[u][v] += flow, f[v][u] -= flow; mf += flow; } void input() { int m, a, b, d; cin >> n >> m >> s >> t; while(m--) { cin >> a >> b >> d; g[a].push_back(b); g[b].push_back(a); c[a][b] = d; } } int main() { ios::sync_with_stdio(false); cin.tie(0); input(); while(findPath()) augment(); cout << mf; return 0; }
959556067b85359ea5f1afe19e6c1387e9c5c1ac
1b3d6d58c08af7a7da22f5a1d712deb7fedc74f0
/Classes/BombOther.h
dc0d4d079e176b41b304556c9d6b65140e104df8
[]
no_license
Mike430/TGP_Second_Semester
0f3260d1e5659e99537742e4e55ba66e3e3bd3d1
5c9ae305b3601f93566c2afac3190360e8a166fe
refs/heads/master
2016-08-12T17:00:09.932635
2016-04-22T12:16:00
2016-04-22T12:16:00
49,950,763
0
0
null
null
null
null
UTF-8
C++
false
false
234
h
BombOther.h
#pragma once #include "Ball.h" class BombOther : public Ball { public: static const int type = 8; static BombOther* create(); virtual bool init() override; virtual ~BombOther(); virtual int getType() override { return type; } };
c1c4778cddf93fb316ab253bbe19de33975faa82
82b43d49b95d1f934fe901b88fdbf36d4c474412
/src/graph/A-star.cpp
d9e953820e35d65d473f442ba9acb640b5897a3e
[]
no_license
isabella232/lib-cpp
977074fbf5e9692ee14f0555258fbdc38b2bb806
eb360cde5ad3e86a380de5745c7c741cfa165c37
refs/heads/master
2022-04-09T06:52:13.549878
2020-03-31T04:57:25
2020-03-31T04:57:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
A-star.cpp
// @import header // #include <bits/stdc++.h> using namespace std; using ll = long long; // @@ // @ A-star // @snippet a_star const ll inf = 1e18; // A* {{{ { using P = tuple< ll, ll, int >; priority_queue< P, vector< P >, greater< P > > pq; vector< ll > dist(n, inf); pq.emplace(0, 0, s); ll res = inf; dist[i] = 0; while(pq.size()) { ll di, rdi; int i; tie(di, rdi, i) = pq.top(); pq.pop(); if(i == t) { res = rdi; break; } if(dist[i] < di) continue; for(auto to : g[i]) { int j, co; tie(j, co) = to; if(hstar(j) == inf) continue; ll nrdi = rdi + co; if(dist[i] > nrdi) pq.emplace(nrdi + hstar(j), nrdi, j); } } } // }}}
e52f2ab4ff7e4357046e8d2611c5ffb0a033c8a3
1588f7002ebfaceb9c382c73fce67ab435d0e840
/utils/src/Predictor/CvSVMPredictor.cpp
d212c0d8fcda1966f0c93f3f658a4d96d48b5174
[]
no_license
akosiorek/Tagger3D
ff04ac94a7f3bc9c0a189cc972e7cd3dcdb900ae
6459f41517710168080badbfc09e3ea1625c6a09
refs/heads/master
2016-09-05T19:47:32.612709
2014-10-14T18:46:44
2014-10-14T18:46:44
12,671,025
4
0
null
null
null
null
UTF-8
C++
false
false
2,298
cpp
CvSVMPredictor.cpp
/* * CvSVMPredictor.cpp * * Created on: Aug 22, 2013 * Author: Adam Kosiorek * Description: svm predictor implementation */ #include "CvSVMPredictor.h" #include <stdio.h> #include <assert.h> #include <algorithm> #include <iostream> #include <vector> #include <cmath> #include <iostream> #include <fstream> #include <iterator> namespace Tagger3D { CvSVMPredictor::CvSVMPredictor(const std::map<std::string, std::string> &_configMap, const std::string &predictorType) : Predictor(_configMap, predictorType) { svmPath = directory + "/" + getParam<std::string>( svmPathKey ); createSVM(); } CvSVMPredictor::~CvSVMPredictor() { } void CvSVMPredictor::createSVM() { params.svm_type = getParam<int>( svmType ); params.kernel_type = getParam<int>( kernelType ); params.term_crit = cvTermCriteria(getParam<int>(termCrit), getParam<int>(maxIter), getParam<double>(epsilon)); params.gamma = getParam<double>( gamma ); params.C = getParam<double>( C ); params.degree = getParam<int>( degree ); std::cout <<params.C << " " << params.gamma<< std::endl; } void CvSVMPredictor::train(cv::Mat& data, const std::vector<int>& labels) { TRACE(logger, "SVM train: Starting"); if( data.rows == 0 ) { throw std::logic_error("Empty mat has been submitted"); } computeMaxValues(data); normaliseData(data); INFO(logger, "Training SVM.") SVM.train(data, cv::Mat(1, labels.size(), CV_32SC1, const_cast<int*>(&labels[0])), cv::Mat(), cv::Mat(), params); TRACE(logger, "SVM train: Finished"); } std::vector<float> CvSVMPredictor::predict(const cv::Mat& histogram) { assert(histogram.rows == 1); INFO(logger, "Classifying") TRACE(logger, "predict: Starting"); cv::Mat data = histogram.clone(); normaliseData(data); std::vector<float> predictions(class_number); predictions[SVM.predict(histogram)] = 1; TRACE(logger, "predict: Finished"); return predictions; } void CvSVMPredictor::load() { TRACE(logger, "load: Starting"); SVM.load(svmPath.c_str()); loadVMax(); TRACE(logger, "load: Finished"); } void CvSVMPredictor::save() { TRACE(logger, "load: Starting"); SVM.save(svmPath.c_str()); INFO(logger, "SVM model saved: " + svmPath); saveVMax(); TRACE(logger, "load: Finished"); } } /* namespace semantic_tagger */
61df6b20e8708f87b842053cd520c7e6b141fc8f
399aa1e6ea4b4f356d0bdf4dd97214fe6d8e0a40
/SomeProblemsOfCpp/defaultParameterInDerived.h
91cb60baa5c65a6badbe0a7353ed9145d431a61d
[]
no_license
JianNL/cppstudy
73d9740b04b8bce0e27eb885d60e8ba146763548
6fe878a796570f4b01f7ab9943beb3abf5b6e65d
refs/heads/master
2016-09-06T09:09:27.816614
2014-11-12T05:34:33
2014-11-12T05:34:33
null
0
0
null
null
null
null
GB18030
C++
false
false
864
h
defaultParameterInDerived.h
#include <iostream> using namespace std; class Base { public: Base() {} Base(bool arg) { foo(); } virtual void foo(int i = 42) { cout << "base" << i << endl; } }; class Derived :public Base { public: Derived(){} Derived(bool arg) :Base(arg) { foo(); } virtual void foo(int i = 12) { cout << "derived" << i << endl; } }; void test1() { Derived d; Base &b1 = d; Base b2 = d;//这个程序的问题是重新定义了继承而来的默认参数。 b1.foo();//调用b1的动态绑定的foo(),但在C++中,虚函数是动态绑定而在动态绑定中的默认参数是静态绑定的也就是说是基类的默认参数42. b2.foo();//调用b2的静态绑定的foo(),默认参数是42 所以输出是base42 } void test2() { Base *b = new Derived(true);//问题是不要在构造函数中中调用虚函数析构函数 delete b; }
cf5f4edce0ac08926d70645b4547ab4eb70e0df7
5b6dccde35aaff457a863bc9a528db97e376058d
/src/cpp/SDLDriver.cpp
cd6bc9bfdc24e10940298ada44c1327d2d187e80
[]
no_license
bigbrett/ENGS65_final_project
22210d2a2d153310e67a71e43671e19de0b6f929
2cbd3003c1bb4a1083e5e06f55dd9f6c4193aa10
refs/heads/master
2021-01-22T09:54:51.991976
2017-04-08T18:34:57
2017-04-08T18:34:57
31,999,880
0
0
null
2015-03-12T18:12:45
2015-03-11T05:23:08
C++
UTF-8
C++
false
false
483
cpp
SDLDriver.cpp
// // SDLDriver.cpp // // A wrapper class that encapsulates an SDL Graphics Application // #include "SDLDriver.h" using namespace std; SDLDriver::SDLDriver() { // should this be SDL_INIT_VIDEO ? if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; } } SDLDriver::~SDLDriver() { SDL_Quit(); } bool SDLDriver::isRunning() { return running; } void SDLDriver::exit() { running = false; }
87870a3f2531195bc1916e90557caee7b9c0f74e
ca17bdf7cf1fc1216701b15fbf070ae2991e91f4
/3D_Animation_Native/OpenCLInfo.h
e0c127fc34b7ae363f032f34713039aab85a6da1
[ "BSD-2-Clause" ]
permissive
bene51/3Dscript
f04c0de7288cd2970ad93db7801d968fa2a6d3e6
7633b956bfbed07af72eaae23f1fc5834e318089
refs/heads/master
2023-03-17T18:19:07.467098
2023-03-15T20:38:54
2023-03-15T20:38:54
151,570,665
61
11
BSD-2-Clause
2019-08-10T07:56:48
2018-10-04T12:49:06
Java
UTF-8
C++
false
false
281
h
OpenCLInfo.h
#ifndef OPENCL_INFO_H #define OPENCL_INFO_H #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif class OpenCLInfo { private: int w_max; public: OpenCLInfo() {}; ~OpenCLInfo() {}; void printInfo(cl_context context, cl_device_id device); }; #endif
b800bc47bc708e3a9f4fab2eb84b1a471750e9a3
59a2182bef1463e6807c6df774fea8ee61b8aaa2
/Forth/3.cpp
01ca80754ee8212a9a0199a6deb29c64c592aa1f
[]
no_license
Flaoting/Data_Structure
b67c15b36a1ea8f21973118b8baa0db8b0f82205
04c38dd33c0ad1844d2f851e1051229b282fed24
refs/heads/main
2023-02-13T07:44:08.178711
2021-01-07T17:05:35
2021-01-07T17:05:35
314,995,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
3.cpp
#include <iostream> #include <fstream> using namespace std; int n,k,t,xl,yd,xr,yu; int x = 0, y = 0; int main() { ifstream file("3.txt", ios::in); file >> n >> k >> t; file >> xl >> yd >> xr >> yu; int passby = 0, stay = 0, time = 0; bool in = false; bool candle = false; for(int i = 1; i <= n; i++) { in = false; candle = false; time = 0; for (int j = 1; j <= t; j++) { file >> x >> y; if(x >= xl && x <= xr && y >= yd && y <= yu) { in = true; time++; } else { time = 0; } if(time >= k) { candle = true; } } if(time >= k) { candle = true; } if(candle) { stay++; } if(in) { passby ++; } } cout << passby <<endl; cout << stay; return 0; }
78f50fd01579b6d5c2e8324c2b7f45060ac39947
509455953fee1ed25ffbca8b5a00616378e14a5e
/Game/Game.h
d1c3b59d167969ff1c715b11ebd091b3614e6a80
[]
no_license
Supetorus/GAT150
0b3f2111d094c482168c64c0a9ed9553a5694237
87f3490ed2518697da2afce3437e5fa4596a8a2a
refs/heads/master
2023-07-27T03:08:27.651633
2021-08-16T23:46:15
2021-08-16T23:46:15
392,109,969
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
Game.h
#pragma once #include "Engine.h" #include "Actors/Player.h" #include "Actors/Asteroid.h" #include "Actors/Enemy.h" #include "Actors/Projectile.h" #include "Math/Transform.h" #include "Math/Random.h" #include <fstream> class Game { public: enum class eState { Title, Instructions, StartGame, StartLevel, Game, GameOver }; public: void Initialize(); void Shutdown(); void Update(); void Draw(); bool isQuit() { return quit; } private: void UpdateTitle(float dt); void StartLevel(); void OnAddPoints(const nc::Event& event); void OnPlayerDead(const nc::Event& event); void SpawnPlayer(); public: std::unique_ptr<nc::Engine> engine; std::unique_ptr<nc::Scene> scene; private: bool quit = false; eState state = eState::Title; float stateTimer = 0.0f; size_t score = 0; size_t lives = 3; size_t level = 0; size_t highscore = 0; //title toy float fireTimer{ 0 }; float fireRate{ 0.1f }; // time between shots float screenTimer = 0; nc::AudioChannel musicChannel; std::shared_ptr<nc::Texture> particleTexture; std::shared_ptr<nc::Texture> textTexture; };
97875c1950927773dc7ad38b243257ca2c41642a
55143c088d1cdf0ea934c85828ef71f1eb94a87e
/GUI/LoadingDialog.cpp
b9985db1947a1171c0907f685b05deba05a85a6a
[]
no_license
maferland/FTB
124afed4c08be7b607817fb8401009bcc01bb8cc
e96268e242f6546a8ba4272752f3d25ccd83c68a
refs/heads/master
2021-05-16T02:50:10.658923
2017-02-27T03:53:41
2017-02-27T03:53:41
30,243,608
0
2
null
null
null
null
UTF-8
C++
false
false
709
cpp
LoadingDialog.cpp
#include "LoadingDialog.h" #include "ui_gui.h" LoadingDialog::LoadingDialog(int size) { this->setMinimumDuration(0); this->setLabelText("Chargement..."); this->setValue(0); this->setMaximum(size); this->setCancelButton(0); this->setWindowModality(Qt::WindowModality::WindowModal); this->setWindowFlags(Qt:: Dialog | Qt:: FramelessWindowHint | Qt:: WindowTitleHint | Qt:: CustomizeWindowHint); } LoadingDialog::~LoadingDialog(void) { } void LoadingDialog::Update(int it, string songName) { this->setValue(it); string text = songName + "... " + std::to_string(it) + "/" + std::to_string(this->maximum()); this->setLabelText(QString::fromStdString(text)); QCoreApplication::processEvents(); }
9c77b57de880ca7966186fcc1703ba5bb98502f9
6f157d27ee466d5600e4f6af8ee38f168a8d0e8c
/asmodean/asmodean tools/exuni2/exuni2.cpp
39057093847112324035cc281c7190cad8f21120
[]
no_license
chrisdevchroma/galgametools
bd85333e440e10d6cf704167bbcd540e1cddf0d5
d3fa44bf13e48757c57720ad6070e0e660e17f45
refs/heads/master
2023-08-21T13:45:02.524512
2020-08-12T03:21:21
2020-08-12T03:21:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,847
cpp
exuni2.cpp
// exuni2.cpp, v1.0 2010/11/01 // coded by asmodean // contact: // web: http://asmodean.reverse.net // email: asmodean [at] hush.com // irc: asmodean on efnet (irc.efnet.net) // This tool extracts UNI2 (*.uni) archives. #include <windows.h> #include <Xcompress.h> #include "as-util.h" struct UNIHDR { unsigned char signature[4]; // "UNI2" unsigned long unknown1; unsigned long entry_count; unsigned long toc_offset; unsigned long data_offset; void flip_endian(void) { unknown1 = as::flip_endian(unknown1); entry_count = as::flip_endian(entry_count); toc_offset = as::flip_endian(toc_offset); data_offset = as::flip_endian(data_offset); } }; struct UNIENTRY { unsigned long unknown1; unsigned long offset; unsigned long length_blocks; unsigned long length; void flip_endian(void) { unknown1 = as::flip_endian(unknown1); offset = as::flip_endian(offset); length_blocks = as::flip_endian(length_blocks); length = as::flip_endian(length); } }; struct CWABHDR { unsigned char signature[4]; // "CWAB" unsigned long entry_count; void flip_endian(void) { entry_count = as::flip_endian(entry_count); } }; struct CWABENTRY { unsigned long length; char filename[60]; void flip_endian(void) { length = as::flip_endian(length); } }; int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "exuni2 v1.0 by asmodean\n\n"); fprintf(stderr, "usage: %s <input.uni>\n\n", argv[0]); return -1; } string in_filename(argv[1]); string prefix = as::get_file_prefix(in_filename, true); int fd = as::open_or_die(in_filename, O_RDWR| O_BINARY); UNIHDR hdr; read(fd, &hdr, sizeof(hdr)); hdr.flip_endian(); UNIENTRY* entries = new UNIENTRY[hdr.entry_count]; lseek(fd, hdr.toc_offset * 2048, SEEK_SET); read(fd, entries, sizeof(UNIENTRY) * hdr.entry_count); for (unsigned long i = 0; i < hdr.entry_count; i++) { entries[i].flip_endian(); unsigned long len = entries[i].length; unsigned char* buff = new unsigned char[len]; lseek(fd, (hdr.data_offset + entries[i].offset) * 2048, SEEK_SET); read(fd, buff, len); string out_prefix = prefix + as::stringf("+%05d", i); if (*(unsigned long*)buff == 0xEE12F50F) { XCOMPRESS_FILE_HEADER_LZXNATIVE* xhdr = (XCOMPRESS_FILE_HEADER_LZXNATIVE*) buff; unsigned char* p = (unsigned char*) (xhdr + 1); xhdr->ContextFlags = as::flip_endian(xhdr->ContextFlags); xhdr->CodecParams.Flags = as::flip_endian(xhdr->CodecParams.Flags); xhdr->CodecParams.WindowSize = as::flip_endian(xhdr->CodecParams.WindowSize); xhdr->CodecParams.CompressionPartitionSize = as::flip_endian(xhdr->CodecParams.CompressionPartitionSize); xhdr->UncompressedSizeLow = as::flip_endian(xhdr->UncompressedSizeLow); xhdr->CompressedSizeLow = as::flip_endian(xhdr->CompressedSizeLow); xhdr->UncompressedBlockSize = as::flip_endian(xhdr->UncompressedBlockSize); xhdr->CompressedBlockSizeMax = as::flip_endian(xhdr->CompressedBlockSizeMax); unsigned long out_len = 0; unsigned char* out_buff = new unsigned char[xhdr->UncompressedSizeLow]; XMEMDECOMPRESSION_CONTEXT context = NULL; XMemCreateDecompressionContext(XMEMCODEC_LZX, &xhdr->CodecParams, xhdr->ContextFlags, &context); while (out_len != xhdr->UncompressedSizeLow) { unsigned long block_len = as::flip_endian(*(unsigned long*) p); p += 4; SIZE_T decomp_len = xhdr->UncompressedSizeLow; XMemDecompress(context, out_buff + out_len, &decomp_len, p, block_len); p += block_len; out_len += decomp_len; } XMemDestroyDecompressionContext(context); delete [] buff; len = out_len; buff = out_buff; } if (!memcmp(buff, "CWAB", 4)) { CWABHDR* cwabhdr = (CWABHDR*) buff; cwabhdr->flip_endian(); CWABENTRY* cwabentries = (CWABENTRY*) (cwabhdr + 1); unsigned char* p = (unsigned char*) (cwabentries + cwabhdr->entry_count); for (unsigned long i = 0; i < cwabhdr->entry_count; i++) { cwabentries[i].flip_endian(); as::write_file(out_prefix + "+" + cwabentries[i].filename, p, cwabentries[i].length); p += cwabentries[i].length; } } else { as::write_file(out_prefix + as::guess_file_extension(buff, len), buff, len); } delete [] buff; } delete [] entries; close(fd); return 0; }
aa5becc47344023266b00ae7816d9fb7b58d9c83
16c2ab0383e8daf4ebbda9c215e1c230be9f7c15
/Testing/H5FDdsmSender_cwrite_cread.cxx
ed02f59a2cdb09a6c4f55d20d8c552a2f45faa1c
[]
no_license
soumagne/h5fddsm
efcb44e4d01d63c1fb240fa488e059a55a8409a2
63d6b18d2f85ff383c7ee39552849e582360aad0
refs/heads/master
2021-07-23T23:17:39.765941
2014-10-23T09:25:58
2014-10-23T09:25:58
109,051,657
1
0
null
null
null
null
UTF-8
C++
false
false
2,158
cxx
H5FDdsmSender_cwrite_cread.cxx
#include "H5FDdsmTest.h" #include "H5FDdsm.h" // #include <hdf5.h> #include <cstdlib> //---------------------------------------------------------------------------- int main(int argc, char * argv[]) { MPI_Comm comm = MPI_COMM_WORLD; H5FDdsmManager *dsmManager = new H5FDdsmManager(); senderInit(argc, argv, dsmManager, &comm); // Create Array int array[3] = { 1, 2, 3 }; int read_array[3]; hsize_t arraySize = 3; // Set file access property list for DSM hid_t fapl = H5Pcreate(H5P_FILE_ACCESS); // Use DSM driver H5Pset_fapl_dsm(fapl, comm, NULL, 0); // Create DSM hid_t hdf5Handle = H5Fcreate("dsm", H5F_ACC_TRUNC, H5P_DEFAULT, fapl); // Close file access property list H5Pclose(fapl); hid_t memspace = H5Screate_simple(1, &arraySize, NULL); hid_t dataset = H5Dcreate(hdf5Handle, "Data0", H5T_NATIVE_INT, memspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); hid_t dataspace = H5S_ALL; H5Dwrite(dataset, H5T_NATIVE_INT, memspace, dataspace, H5P_DEFAULT, array); if (dataspace != H5S_ALL) { H5Sclose(dataspace); } if (memspace != H5S_ALL) { H5Sclose(memspace); } H5Dclose(dataset); H5Fclose(hdf5Handle); std::cout << "Attempt to Read Data" << std::endl; // Set up file access property list with parallel I/O fapl = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_dsm(fapl, comm, NULL, 0); hdf5Handle = H5Fopen("dsm", H5F_ACC_RDONLY, fapl); // Close property list H5Pclose(fapl); dataset = H5Dopen(hdf5Handle, "Data0", H5P_DEFAULT); dataspace = H5Dget_space(dataset); hssize_t numVals = H5Sget_simple_extent_npoints(dataspace); hid_t datatype = H5Dget_type(dataset); std::cout << "Number of Values Read: " << numVals << std::endl; H5Dread(dataset, datatype, H5S_ALL, dataspace, H5P_DEFAULT, &read_array); for(unsigned int i = 0; i < numVals; ++i) { if (array[i] != read_array[i]) { fprintf(stderr," read_array[%d] is %d, should be %d\n", i, read_array[i], array[i]); } } H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); H5Fclose(hdf5Handle); senderFinalize(dsmManager, &comm); delete dsmManager; return(EXIT_SUCCESS); }
160d082a9e4173cce68aff8bd141f1073b22feb0
5677db59ac729652f4019bd7259d35ac2ff1a960
/main.cpp
fc814c03bd9059c610989995e07403f45d2e9669
[]
no_license
coffeine-009/MarioIsReturning
39124476e3a76725ba69688e055f2636742a71ce
6ac569c24e4e7670a032a259f65c6a3a2896fce6
refs/heads/master
2020-06-07T07:42:50.974448
2014-03-24T21:40:59
2014-03-24T21:40:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,941
cpp
main.cpp
/// *** Main file(Point of entry) *** *** *** *** *** *** *** *** *** *** /// /** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** * * * * @copyright (c), 2013 by Vitaliy Tsutsman * * @author Vitaliy Tsutsman <vitaliyacm@gmail.com> * * @date 2013-11-20 14:58:00 :: 2014-02-12 17:49:12 * * @address /Ukraine/Ivano-Frankivsk/Tychyny/7a (Softjourn) * * *///*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** * /// *** Dependencies *** *** *** *** *** *** *** *** *** *** *** *** *** /// #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include "src/Library/Coffeine/Configuration/ReaderInterface.h" #include "src/Library/Coffeine/Configuration/Ini/Reader.h" #include "src/Module/Application/Bootstrap.h" /// *** Code *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** /// /** *** *** *** *** *** *** *** *** *** *** *** *** * * main * --- --- --- --- --- --- --- --- --- --- --- --- * * Entry point * * @param int argc * @param char ** argv * @return int *///*** *** *** *** *** *** *** *** *** *** *** *** * int main( int argc, char ** argv ) { //- Read configuration -// Configuration :: ReaderInterface * config = new Configuration :: Ini :: Reader( "src/Module/Application/Configuration/application.ini", L"production", L"development" ); //- Read configuration from file and parse -// config -> Read(); //- Create new application -// Application :: Bootstrap * app = Application :: Bootstrap :: GetInstance( config ); //- Initialization application -// app -> Init( argc, argv ); //- Free memory for confuguration -// delete config; //- Run application -// app -> Run(); return 0; }
055d1c33bbb63ac080dc63cb2b2e26df853494b7
146698dcc3a2cbc9bdbf855add3fd7d6a1934c50
/SampleCodes/Function/Lab9.cc
fb06d919a24474bf860ec86fae5f72710ed63a6a
[]
no_license
geunkim/CPPLectures
1e0d80a6f7348d5abae6ea4fe7b0b0be3de3afee
a402e912777c2d280a2103fa968e6c91dab63435
refs/heads/master
2023-07-20T14:57:25.165971
2023-07-17T01:28:40
2023-07-17T01:28:40
210,631,519
32
104
null
2023-03-21T23:52:22
2019-09-24T15:05:32
C++
UTF-8
C++
false
false
346
cc
Lab9.cc
/* File: Lab9.cc Author: Geun-Hyung Kim */ #include <iostream> using namespace std; double div_eq(double x = 10, double y = 20) { return x / y; } int main(int argc, char const *argv[]) { cout << "출력(1): " << div_eq() << endl; cout << "출력(2): " << div_eq(5) << endl; cout << "출력(3): " << div_eq(50, 10) << endl; return 0; }
db303235b778cfaaeb8abde5053d379cba077c13
954377c3bb9f75826c959249c7f1f505366e9388
/src/backdrop.h
87b8ecf62717401ebea19c05de7ecb25f95384a2
[]
no_license
bentglasstube/ld32
6dbd3b3cda7040113ce473d929da9c2be365674a
e7286ecddc239bff2c16379b6ef00c3ea72ae736
refs/heads/master
2021-01-17T15:23:24.761021
2016-05-02T15:58:43
2016-05-02T15:58:43
41,442,604
0
0
null
null
null
null
UTF-8
C++
false
false
268
h
backdrop.h
#pragma once #include <SDL2/SDL.h> #include <string> class Graphics; class Backdrop { public: Backdrop(Graphics& graphics, const std::string& file); void draw(Graphics& graphics); virtual void update() {} private: SDL_Texture* texture; };
8d4960d698fb9cde5cfd9e3a23392bcb5e05a46a
8a48bd1c0480698f5d8d7289f22e851ac6534fe2
/BOJ11660.cpp
ec04fbbfcec3e92762c91ce89349b98ea4dd3309
[]
no_license
luceinaltis/Algorithms
9da76f7e712d3beb4309cd9023e565a77bc92bc7
383be527c2b412963c0422d5cb844a7e29ad07e4
refs/heads/master
2021-11-26T18:08:19.404362
2021-10-06T05:57:30
2021-10-06T05:57:30
240,202,816
0
0
null
null
null
null
UTF-8
C++
false
false
998
cpp
BOJ11660.cpp
#include <iostream> #include <cstring> using namespace std; typedef long long ll; int n, m; int board[1025][1025]; int cumSum[1025][1025]; void calculateCumulativeSum() { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cumSum[i][j] = board[i][j] + cumSum[i][j - 1] + cumSum[i - 1][j] - cumSum[i - 1][j - 1]; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); memset(board, 0, sizeof(board)); memset(cumSum, 0, sizeof(cumSum)); cin >> n >> m; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> board[i][j]; } } calculateCumulativeSum(); for (int i = 0; i < m; ++i) { int x1, y1, x2, y2; ll result = 0; cin >> x1 >> y1 >> x2 >> y2; result = cumSum[x2][y2] - cumSum[x1 - 1][y2] - cumSum[x2][y1 - 1] + cumSum[x1 - 1][y1 - 1]; cout << result << '\n'; } return 0; }
553046089f309b16d5e28b1fefccf1bf058e65b5
34a5d9d2bd56d826e67d81d9943949d47d8e38fa
/ocl/PosixSlurp.cc
e2816d4dc500b55f01add76c761b39440f8d16f9
[]
no_license
JensMunkHansen/dsp
44443c20d9c3693d43d900653126a9dc8eecc77a
caf44ff30ebd245fff7e633c3f12ca55af6fbe61
refs/heads/master
2020-04-22T12:59:09.951339
2019-02-19T09:04:23
2019-02-19T09:04:23
170,393,062
0
0
null
null
null
null
UTF-8
C++
false
false
2,163
cc
PosixSlurp.cc
#ifndef SLURP_H #define SLURP_H class Slurp { void *begin_{ nullptr }; void *end_; public: Slurp() = delete; Slurp(const Slurp &) = delete; Slurp &operator=(Slurp) = delete; Slurp(Slurp &&other) noexcept = default; Slurp &operator=(Slurp &&other) noexcept = default; [[gnu::nonnull]] Slurp(const char *path); ~Slurp(); [[gnu::const, gnu::returns_nonnull]] const char *begin() const noexcept; [[gnu::const, gnu::returns_nonnull]] const char *end() const noexcept; }; #endif //SLURP_H // Slurp.cc #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <cstdlib> #include <system_error> using namespace std; #define ERROR_IF(CONDITION) do {\ if (__builtin_expect(CONDITION, false))\ throw system_error(errno, system_category());\ } while (false) #define ERROR_IF_POSIX(POSIX_PREFIXED_FUNCTION_CALL) do {\ const int error_number{ posix_##POSIX_PREFIXED_FUNCTION_CALL };\ if (__builtin_expect(error_number, false))\ throw system_error(error_number, system_category());\ } while (false) Slurp::Slurp(const char *path) { class FileDescriptor { const int fd_; public: FileDescriptor(int fd) : fd_{ fd } {ERROR_IF(fd_ == -1);} ~FileDescriptor() {close(fd_);} [[gnu::const]] operator int() const noexcept {return fd_;} }; FileDescriptor fd{ open(path, O_RDONLY) }; ERROR_IF_POSIX(fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)); struct stat file_statistics; ERROR_IF(fstat(fd, &file_statistics)); const size_t blksize{ static_cast<size_t>(file_statistics.st_blksize) }; const size_t bufsize{ static_cast<size_t>(file_statistics.st_size) + sizeof(char32_t) }; ERROR_IF_POSIX(memalign(&begin_, blksize, bufsize)); end_ = static_cast<char*>(begin_) + file_statistics.st_size; ERROR_IF_POSIX(madvise(begin_, bufsize, POSIX_MADV_SEQUENTIAL)); ERROR_IF(read(fd, begin_, file_statistics.st_size) == -1); *static_cast<char32_t*>(end_) = U'\0'; // Ensure null termination } Slurp::~Slurp() {free(begin_);} const char *Slurp::begin() const noexcept {return static_cast<char*>(begin_);} const char *Slurp::end() const noexcept {return static_cast<char*>(end_);}
7041e92dec392a6891e77216adba7a469345c52f
90f4fcb8f687fd885e64500dbbed980d292c123d
/include/meshloader.h
e6a3dd4e70ec29df527963ad923ca2f5f379c667
[ "MIT" ]
permissive
smarchevsky/VisualEngine
21738333745f5ddac2c8ced60aefeafe7a0a5937
47e1c8a018855fe27b90827ab66177ff73eae405
refs/heads/master
2022-01-09T21:50:00.645247
2019-06-25T18:45:04
2019-06-25T18:45:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
221
h
meshloader.h
#ifndef MESHLOADER_H #define MESHLOADER_H #include <vector> namespace Visual { class Model; class MeshData; class MeshLoader { public: static std::vector<MeshData> load(const char* path); }; } #endif // MESHLOADER_H
965e7dab930bb5fdedfae60fba3b4d031f727daa
ce1d9f8cf8e21cf5da20553b2460e43923c134e9
/Times-fatec/Times.cpp
279f414e8441cab4dc5c6be5fd7427e61115f58d
[]
no_license
devjaum/Fatec-exercicios
dce4d5a766b31439451a26744bc835c60c688b4b
2067191ad3debdd323d42d1d562416a8669cda6a
refs/heads/master
2022-11-16T21:08:35.125188
2020-07-10T01:39:04
2020-07-10T01:39:04
262,870,645
1
0
null
null
null
null
UTF-8
C++
false
false
2,029
cpp
Times.cpp
/* Name: sistemadelogin.cpp Author:Joao Carlos Date: 10/05/2020 17:00 Description: Função para fazer um sistema de login */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> char ExibirLPontuacao(char[]); char Resultado(char []); void ExibirTimes(char[12][50]); //Variavel global; char TodososTimes [12] [50] = {"1 - Corinthians", "2 - Palmeiras", " 3 - Sao Paulo", "4 - Santos", "5 - Portuguesa", "6 - Guarani", "7 - Juventus", "8 - Barueri", "9 - Sao Caetano", "10 - Oeste", "11 - XV de Piracicaba"}; int main(){ char resultado[25]; char resultados2[25]; int i, j; ExibirTimes(TodososTimes); printf("\n Digite o numero do time e seu adversario:"); gets(resultado); Resultado(resultado); printf("\n Digite o numero de seu adversario:"); gets(resultados2); Resultado(resultados2); } void ExibirTimes(char times[12][50]){ int i; puts("Os times sao:"); for(i = 0; i < 12; i++){ printf((i < 10)?"%s, ":"%s", times[i], times[i]); } } char Resultado(char resultado[25]){ int i, j, decisao; decisao = i = 0; for(j = 0; j < 12; j++){ for(i = 0; i < 25; i++){ if(resultado[i] == TodososTimes[i][j]){ decisao=1; } } if(decisao==1){ ExibirLPontuacao(resultado); } } } char ExibirLPontuacao(char exibir[25]){ int vitoria, derrota, empate, porc, total, i, j; vitoria = derrota = empate = total = 0; porc = 100; printf("Digite a quantidade de vitorias:"); scanf("%d", &vitoria); printf("Digite a quantidade de empate:"); scanf("%d", &empate); printf("Digite a quantidade de derrota:"); scanf("%d", &derrota); total = vitoria + derrota + empate; vitoria = vitoria / total * porc; derrota = derrota / total * porc; empate = empate / total * porc; }
e1d65e281d537e4e2ed346ee0910716afb69f6ca
cd57c848fcf53ba3c3ec38b90c1d29d7462cf717
/FibonacciType/Staircase123.cpp
1a20cfd5df2d030659a66619b4e1def3b38a7eb0
[]
no_license
abhilasha007/Dynamic-Programming
a9a2267b7aa200ca169335ca2ed32e91758ebe91
f03141ec7675f0ff9d2f68a9e456f331cdcb7635
refs/heads/main
2023-06-25T06:51:50.312865
2021-07-29T14:08:14
2021-07-29T14:13:04
341,320,089
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
Staircase123.cpp
/** * A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. * Implement a method to count how many possible ways the child can run up the stairs. Examples: Input : 4 Output : 7 Explantion: Below are the four ways 1 step + 1 step + 1 step + 1 step 1 step + 2 step + 1 step 2 step + 1 step + 1 step 1 step + 1 step + 2 step 2 step + 2 step 3 step + 1 step 1 step + 3 step Input : 3 Output : 4 Explantion: Below are the four ways 1 step + 1 step + 1 step 1 step + 2 step 2 step + 1 step 3 step **/ /** * Crux * f(n) = f(n-1) + f(n-2) + f(n-3); **/ #include<bits/stdc++.h> using namespace std; // Dynamic Programming int getTotalWaysDP(int n) { int* dp = new int[n+1]; dp[0] = 1; dp[1] = 1; dp[2] = 2; for(int i=3; i<=n; ++i) { dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; } return dp[n]; } int getTotalWays(int n) { if(n==0) return 1; if(n==1) return 1; if(n==2) return 2; return getTotalWays(n-1) + getTotalWays(n-2) + getTotalWays(n-3); } int main() { int n; cin >> n; cout << getTotalWays(n); return 0; }
584bebf30c4ddc423883b393a3d69841535749ad
a6d42343368589c7e7d83584959718a2bc360f79
/Resource Robbers/physics/PhysicsEngine.cpp
5a97a0be4597a5c002ffc371a6ba4790ad3cd81a
[]
no_license
wtacquard/resource-robbers
6973077c0cdffa9012d67488fc2c031ed6b82182
b150519979ce13eced8f0128ea228c026308ed62
refs/heads/master
2021-01-19T08:14:24.742120
2014-07-18T13:29:21
2014-07-18T13:29:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,035
cpp
PhysicsEngine.cpp
#include "PhysicsEngine.h" #include <boost/exception/exception.hpp> #include <sstream> #include <log.hpp> #include "PhysicsMovableObject.h" #include "common/MoreMath.h" using RR::Log; using boost::exception; PhysicsEngine::PhysicsEngine() : gravity(0, 0.000000000f, 0.0f), _pobjects(), onCollideFunction(NULL), timeStep(0) { Log &log = Log::instance(); setTimeStep(1.0 / 30.0); if(!QueryPerformanceCounter((LARGE_INTEGER*)(&lastUpdate))) log << "Physics Engine could not get high resolution timer"; } PhysicsEngine::~PhysicsEngine() { } const D3DXVECTOR3& PhysicsEngine::getGravity() const { return gravity; } PhysicsEngine::PhysicsObjects& PhysicsEngine::getPhysicsObjects() { return (_pobjects); } float PhysicsEngine::getTimeStep() const { __int64 frequency; Log& log = Log::instance(); if(!QueryPerformanceFrequency((LARGE_INTEGER*)&frequency)) log << "Physics Engine could not get high resolution timer"; return (float)((double)timeStep / frequency); } bool PhysicsEngine::isReadyToUpdate() { __int64 currentTime; QueryPerformanceCounter((LARGE_INTEGER*)&currentTime); return lastUpdate + timeStep < currentTime; } void PhysicsEngine::onCollide(shared_ptr<PhysicsObject> first, shared_ptr<PhysicsObject> second) { PhysicsMovableObject* movable1; PhysicsMovableObject* movable2; movable1 = dynamic_cast<PhysicsMovableObject*>(first.get()); movable2 = dynamic_cast<PhysicsMovableObject*>(second.get()); if (!movable1 && !movable2) return; if (!movable1 && movable2) { onCollide(second, first); return; } D3DXVECTOR3 zero(0.0f, 0.0f, 0.0f); D3DXVECTOR3 firstNormal; D3DXVECTOR3 secondNormal; D3DXVec3Subtract(&firstNormal, second->getPosition(), first->getPosition()); D3DXVec3Subtract(&secondNormal, first->getPosition(), second->getPosition()); D3DXVec3Normalize(&firstNormal, &firstNormal); D3DXVec3Normalize(&secondNormal, &secondNormal); D3DXVECTOR3 forceMagnitudeVector; if (movable1 && !movable2) { D3DXVECTOR3 firstForce; D3DXVec3Scale(&firstForce, &firstNormal, D3DXVec3Dot(&firstNormal, movable1->getVelocity()) * movable1->getMass()); forceMagnitudeVector = firstForce; firstForce *= -2; movable1->applyForce(&zero, &firstForce); } if (movable1 && movable2) { D3DXVECTOR3 firstForce; D3DXVECTOR3 secondForce; D3DXVec3Scale(&firstForce, &firstNormal, D3DXVec3Dot(&firstNormal, movable1->getVelocity()) * movable1->getMass()); D3DXVec3Scale(&secondForce, &secondNormal, D3DXVec3Dot(&secondNormal, movable2->getVelocity()) * movable2->getMass()); movable1->applyForce(&zero, &secondForce); movable2->applyForce(&zero, &firstForce); firstForce *= -1; forceMagnitudeVector = firstForce + secondForce; secondForce *= -1; movable1->applyForce(&zero, &firstForce); movable2->applyForce(&zero, &secondForce); } float forceMagnitude = D3DXVec3Length(&forceMagnitudeVector); if (onCollideFunction) onCollideFunction(first, second, forceMagnitude); } bool PhysicsEngine::registerPhysicsObject(boost::shared_ptr<PhysicsObject> obj) { _pobjects.insert(obj); return (true); } bool PhysicsEngine::remove(boost::shared_ptr<PhysicsObject> obj) { _pobjects.erase(_pobjects.find(obj)); return (true); } void PhysicsEngine::reset() { } void PhysicsEngine::setOnCollide(boost::function<void(shared_ptr<PhysicsObject>, shared_ptr<PhysicsObject>, float forceMagnitude)> callback) { onCollideFunction = callback; } void PhysicsEngine::setTimeStep(double time) { __int64 frequency; Log& log = Log::instance(); if(!QueryPerformanceFrequency((LARGE_INTEGER*)&frequency)) log << "Physics Engine could not get high resolution timer"; timeStep = (__int64)(time * frequency); } /** * @return true if the objects status was actually updated. */ bool PhysicsEngine::update() { __int64 currentTime; QueryPerformanceCounter((LARGE_INTEGER*)&currentTime); if(lastUpdate + timeStep >= currentTime) return (false); for(PhysicsObjectsIterator it = _pobjects.begin(); it != _pobjects.end(); ++it) { (*it)->update(); } lastUpdate += timeStep; detectCollision(); return (true); } void PhysicsEngine::detectCollision() { PhysicsObjectsIterator it2; for (PhysicsObjectsIterator it1 = _pobjects.begin(); it1 != _pobjects.end(); ++it1) { it2 = it1; for (++it2; it2 != _pobjects.end(); ++it2) { if (detectCollisionBasic(**it1, **it2)) onCollide(*it1, *it2); } } } bool PhysicsEngine::detectCollisionBasic(PhysicsObject& a, PhysicsObject& b) { D3DXVECTOR3 abs_center[2]; abs_center[0] = a.getBoundingSphere().center + *a.getPosition(); abs_center[1] = b.getBoundingSphere().center + *b.getPosition(); if (distance(abs_center[0], abs_center[1]) <= a.getBoundingSphere().radius + b.getBoundingSphere().radius) return (true); return (false); } bool PhysicsEngine::detectCollisionAdvanced(PhysicsObject& a, PhysicsObject& b) { return (true); }
a53bfbce85c4ddac2f031fe7d60df72b6c982d71
0a55aa9f81d38d10681a793d55b6831f0f5fed7f
/Application_tree.cpp
6d69fd754a43eebb97b1c1e6cdca0617deddc997
[]
no_license
DShcherbak/Module_test_2
d3416031dd28bae9ad1f53d0337921830fab0920
ed7fae43c89953ba909593cb1026fd63e645740f
refs/heads/master
2020-05-24T08:14:09.954670
2019-05-23T12:46:34
2019-05-23T12:46:34
187,178,119
0
0
null
null
null
null
UTF-8
C++
false
false
6,525
cpp
Application_tree.cpp
#include <iostream> #include <vector> #include <cmath> #include <random> #include <algorithm> #include <queue> #include "Application.h" const double probability = 0.1; struct Node{ Application *app; Node *parent; int height, cnt_child, cnt_tree; double min_mark, max_mark, sum; std::vector <Node*> children; Node(Application * _a){ app = _a; height = 1; cnt_child = 0; cnt_tree = 1; min_mark = app->mark; max_mark = app->mark; sum = app->mark; } double average(){ return 1.0*sum/cnt_tree; } }; bool add_node_to_root(Node* root, Node* new_node){ bool result = false; if(root == nullptr) return false; // std::cout << root->app->mark << " * " << new_node->parent->app->mark << std::endl; if(root->app == new_node->app->prototype){ new_node->parent = root; root->children.push_back(new_node); root->height = std::max(root->height,1+new_node->height); root->cnt_child++; root->min_mark = std::min(root->min_mark,new_node->min_mark); root->max_mark = std::max(root->max_mark,new_node->max_mark); root->sum += new_node->sum; root->cnt_tree++; return true; } else{ for(auto ch : root->children){ root->sum -= ch->sum; if(add_node_to_root(ch,new_node)){ result = true; root->sum += ch->sum; root->height = std::max(root->height,1+ch->height); root->min_mark = std::min(root->min_mark,ch->min_mark); root->max_mark = std::max(root->max_mark,ch->max_mark); root->cnt_tree++; return true; } root->sum += ch->sum; } } return false; } std::vector <Node*> build_tree(std::vector <Application*> apps){ std::vector <Node*> roots; int n = apps.size(); for(int i = 0; i <n; i++){ Node* new_node = new Node(apps[i]); if(apps[i]->prototype == nullptr) roots.push_back(new_node); else{ for(int i = 0, k = roots.size(); i < k; i++){ if(add_node_to_root(roots[i],new_node)) break; } } } return roots; } void add_app_to_tree(std::vector <Node*> &roots, Application* app){ Node* new_node = new Node(app); if(new_node->parent == nullptr){ roots.push_back(new_node); return; } for(auto root : roots) if(add_node_to_root(root,new_node)) return; } Node* find_min_tree(Node* root, int level){ // std::cout << root->max_mark << " with " << level << std::endl; Node* res = nullptr; Node* temp; if(level == 0) return root; for(auto ch : root->children){ temp = find_min_tree(ch,level-1); if(temp == nullptr) continue; if(res == nullptr || temp->max_mark < res->max_mark) res = temp; } return res; } Node* find_max_tree(Node* root, int level){ Node* res = nullptr; Node* temp; if(level == 0) return root; for(auto ch : root->children){ temp = find_max_tree(ch,level-1); if(temp == nullptr) continue; if(res == nullptr || temp->min_mark > res->min_mark) res = temp; } return res; } void global_recount(Node* root){ for(auto ch : root->children) global_recount(ch); root->sum = root->app->mark; root->cnt_tree = 1; root->min_mark = root->sum; root->max_mark = root->sum; root->height = 1; for(auto ch : root->children){ root->sum += ch->sum; root->cnt_tree += ch->cnt_tree; root->min_mark = std::min(root->min_mark,ch->min_mark); root->max_mark = std::max(root->max_mark,ch->max_mark); root->height = std::max(root->height,ch->height+1); } } void swap_trees(Node* a, Node* b){ if(!a->parent && !b->parent){ std::swap(a,b); return; } Node* pa = a->parent; Node* pb = b->parent; pa->sum -= a->sum; pb->sum -= b->sum; for(int i = 0; i < pa->cnt_child; i++) if (pa->children[i] == a) { pa->children[i] = b; break; } for(int i = 0; i < pb->cnt_child; i++) if (pb->children[i] == b) { pb->children[i] = a; break; } a->parent = pb; b->parent = pa; } void swap_min_max_trees(Node* root, int level){ Node* min_tree = find_min_tree(root,level); Node* max_tree = find_max_tree(root,level); //std::cout << "Hello!" << std::endl; if(min_tree == max_tree){ std::cout << "The min-max tree and max-min tree are the same tree for this level.\n Try again later or try another level.\n"; return; } std::cout << "Min-max tree: " << min_tree->app->mark << "\n"; std::cout << "Max-min tree: " << max_tree->app->mark << "\n"; swap_trees(min_tree, max_tree); global_recount(root); std::cout << "Swaping done!\n"; } void print_node_right(Node* root){ std::cout << root->app->mark << " "; for(auto ch:root->children) print_node_right(ch); } void print_tree_right(std::vector <Node*> roots){ int n = roots.size(); for(int i = 0; i < n; i++){ print_node_right(roots[i]); } } void print_node(Node* root, int type){ switch(type){ case 0: std::cout << root->app->mark << std::endl; return; case 1: std::cout << root->min_mark << std::endl; return; case 2: std::cout << root->max_mark << std::endl; return; case 3: std::cout << root->height << std::endl; return; case 4: std::cout << root->cnt_tree << std::endl; return; case 5: std::cout << (1.0*root->sum)/(1.0*root->cnt_tree) << std::endl; return; } } void print_tree(Node *root,int type = 0, int depth = 0) { if (!root) return; std::cout << '|'; for (int i = 0; i < depth; i++) std::cout << '\t' << '|'; print_node(root,type); for(auto ch : root->children) print_tree(ch,type,depth+1); } int depth(Node* root){ if(root == nullptr) return 0; if(root->children.size() == 0){ return 1; } int maxDep = -1; for(auto ch : root->children) maxDep = std::max(maxDep,depth(ch)); return 1+maxDep; }
7e07d4febefcf588df5e7da33475d93e80c6674d
64cf9ab2677095c37b6924c55c36d00a519197bd
/creational_pattern/builder/builder.h
004d48b41d9e7d62be47e899d47d324c022083db
[ "MIT" ]
permissive
heLi0x/design_pattern
9346b7d94663d451617b1754a4df97c920c0c9e8
91ef376056e90e5de4deb0e6f08573716dc18a19
refs/heads/master
2023-01-22T12:56:28.837755
2020-11-25T12:03:24
2020-11-25T12:03:24
315,539,503
1
0
null
null
null
null
UTF-8
C++
false
false
533
h
builder.h
#ifndef _BUILDER_BUILDER_H #define _BUILDER_BUILDER_H #include "product.h" #include <string> class Builder{ public: virtual void buildPartA(std::string s)=0; virtual void buildPartB(std::string s)=0; virtual void buildPartC(std::string s)=0; virtual Product* getProduct()=0; }; class ConcreteBuilder:public Builder{ private: Product* p; public: ConcreteBuilder(); void buildPartA(std::string s); void buildPartB(std::string s); void buildPartC(std::string s); Product* getProduct(); }; #endif
a7a162609fb048284655c299554f879354bf7852
54a29cf19d0962b9e5d9c535918a1c56bcfebdd3
/test/snippet/core/algorithm/deferred_config_element_base.cpp
6e993735021a4d64f0850805a0789f7c0e7ba599
[]
permissive
giesselmann/seqan3
c027ae539e92460371d0b354a9cf768d380a573b
3a26b42b7066ac424b6e604115fe516607c308c0
refs/heads/master
2021-04-26T22:17:41.710001
2018-09-19T07:09:28
2018-09-19T07:09:28
124,063,820
0
0
BSD-3-Clause
2018-03-06T10:45:41
2018-03-06T10:45:41
null
UTF-8
C++
false
false
786
cpp
deferred_config_element_base.cpp
#include <seqan3/core/algorithm/deferred_config_element_base.hpp> using namespace seqan3; int main() {} //! [usage] template <size_t I> struct my_config { size_t value{I}; // Has to be named `value`. }; struct my_deferred_config { template <typename fn_t, typename configuration_t> constexpr auto invoke(fn_t && fn, configuration_t && config) const requires detail::is_algorithm_configuration_v<remove_cvref_t<configuration_t>> { if (value == 0) return fn(std::forward<configuration_t>(config).replace_with(my_deferred_config{}, my_config<0>{})); else return fn(std::forward<configuration_t>(config).replace_with(my_deferred_config{}, my_config<1>{})); } int value{0}; // Has to be named `value`. }; //! [usage]
e60a84b3deb3ca0d07e1af2f4ce551c7aa6e8e1c
2f38d24a58c50bf6b192e32313cc993e0a54f660
/pytest/extend/vector2/RoadGenerateSDK/GRoadLinkModifierRoadSmooth.h
c48d897d8873766ce5b89f7dd1e16865d14f5514
[]
no_license
lezasantaizi/stray_file
c0a9606eb8552b28034cef565d0e5385a60924ff
0fd63963575f156dafc23563ee0ff35e788cf727
refs/heads/master
2021-01-20T01:17:47.538730
2017-12-26T06:30:47
2017-12-26T06:30:47
101,283,335
0
2
null
null
null
null
WINDOWS-1252
C++
false
false
830
h
GRoadLinkModifierRoadSmooth.h
/*----------------------------------------------------------------------------- ×÷Õߣº¹ùÄþ 2016/06/22 ±¸×¢£º ÉóºË£º -----------------------------------------------------------------------------*/ #pragma once #include "GRoadLinkModifier.h" #include "SDKInterface.h" /** * @brief * @author ningning.gn * @remark **/ class GRoadLinkModifierRoadSmooth : public GRoadLinkModifier { private: GShapeRoadPtr m_Road; public: GRoadLinkModifierRoadSmooth(Utility_In GShapeRoadPtr A_Road) : GRoadLinkModifier(), m_Road(A_Road) {} virtual void DoModify(); };//end GRoadLinkModifierRoadSmooth /** * @brief * @author ningning.gn * @remark **/ class GRoadLinkModifierRoadSmoothAll : public GRoadLinkModifier { public: virtual void DoModify(); };//end GRoadLinkModifierRoadSmoothAll
7050fb73a0dc49744163d8cd643c7342de11d0b1
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/multimedia/dshow/filters/tsdvr/dvrfilters/shared/dvrpins.h
45def8bf154dd6324ac1df73a0a1249cc98a5b1e
[]
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
19,665
h
dvrpins.h
/*++ Copyright (c) 2001 Microsoft Corporation Module Name: dvrpins.h Abstract: This module contains the DVR filters' pin-related declarations. Author: Matthijs Gates (mgates) Revision History: 01-Feb-2001 created --*/ #ifndef __tsdvr__shared__dvrpins_h #define __tsdvr__shared__dvrpins_h // ============================================================================ // ============================================================================ TCHAR * CreateOutputPinName ( IN int iPinIndex, IN int iBufferLen, OUT TCHAR * pchBuffer ) ; TCHAR * CreateInputPinName ( IN int iPinIndex, IN int iBufferLen, OUT TCHAR * pchBuffer ) ; // ============================================================================ // ============================================================================ class CIDVRPinConnectionEvents { public : virtual HRESULT OnInputCompleteConnect ( IN int iPinIndex, IN AM_MEDIA_TYPE * pmt ) = 0 ; virtual HRESULT OnQueryAccept ( IN const AM_MEDIA_TYPE * pmt ) = 0 ; } ; // ============================================================================ // ============================================================================ class CIDVRDShowStream { public : virtual HRESULT OnReceive ( IN int iPinIndex, IN CDVRAttributeTranslator * pTranslator, IN IMediaSample * pIMediaSample ) = 0 ; virtual HRESULT OnBeginFlush ( IN int iPinIndex ) = 0 ; virtual HRESULT OnEndFlush ( IN int iPinIndex ) = 0 ; virtual HRESULT OnEndOfStream ( IN int iPinIndex ) = 0 ; } ; // ============================================================================ // ============================================================================ class CDVRPin { int m_iBankStoreIndex ; // index into the holding bank CCritSec * m_pFilterLock ; CMediaType m_mtDVRPin ; // if connected : == m_mt protected : CDVRAttributeTranslator * m_pTranslator ; CDVRPolicy * m_pPolicy ; CMediaType * GetMediaType_ () { return & m_mtDVRPin ; } BOOL IsEqual_ (IN const AM_MEDIA_TYPE * pmt) { CMediaType mt ; mt = (* pmt) ; return (mt == m_mtDVRPin ? TRUE : FALSE) ; } BOOL NeverConnected_ () { return IsBlankMediaType (& m_mtDVRPin) ; } public : CDVRPin ( IN CCritSec * pFilterLock, IN CDVRPolicy * pPolicy ) : m_iBankStoreIndex (UNDEFINED), m_pFilterLock (pFilterLock), m_pTranslator (NULL), m_pPolicy (pPolicy) { ASSERT (m_pFilterLock) ; ASSERT (m_pPolicy) ; m_pPolicy -> AddRef () ; m_mtDVRPin.InitMediaType () ; m_mtDVRPin.majortype = GUID_NULL ; m_mtDVRPin.subtype = GUID_NULL ; m_mtDVRPin.formattype = GUID_NULL ; } virtual ~CDVRPin () { m_pPolicy -> Release () ; } // -------------------------------------------------------------------- // class methods void SetBankStoreIndex (IN int iIndex) { m_iBankStoreIndex = iIndex ; } int GetBankStoreIndex () { return m_iBankStoreIndex ; } HRESULT SetPinMediaType ( IN AM_MEDIA_TYPE * pmt ) ; HRESULT GetPinMediaType ( OUT AM_MEDIA_TYPE * pmt ) ; HRESULT GetPinMediaTypeCopy ( OUT CMediaType ** ppmt ) ; } ; // ============================================================================ // ============================================================================ template <class T> class CTDVRPinBank { enum { // this our allocation unit i.e. pin pointers are allocated 1 block // at a time and this is the block size PIN_BLOCK_SIZE = 5 } ; TCNonDenseVector <CBasePin *> m_Pins ; public : CTDVRPinBank ( ) : m_Pins (NULL, PIN_BLOCK_SIZE ) {} virtual ~CTDVRPinBank ( ) {} int PinCount () { return m_Pins.ValCount () ; } T * GetPin ( IN int iIndex ) { DWORD dw ; CBasePin * pPin ; dw = m_Pins.GetVal ( iIndex, & pPin ) ; if (dw != NOERROR) { // most likely out of range pPin = NULL ; } return reinterpret_cast <T *> (pPin) ; } HRESULT AddPin ( IN CBasePin * pPin, IN int iPinIndex ) { HRESULT hr ; DWORD dw ; dw = m_Pins.SetVal ( pPin, iPinIndex ) ; hr = HRESULT_FROM_WIN32 (dw) ; return hr ; } HRESULT AddPin ( IN CBasePin * pPin, OUT int * piPinIndex ) { DWORD dw ; dw = m_Pins.AppendVal ( pPin, piPinIndex ) ; return HRESULT_FROM_WIN32 (dw) ; ; } virtual HRESULT OnCompleteConnect ( IN int iPinIndex, IN AM_MEDIA_TYPE * pmt ) { return S_OK ; } } ; // ============================================================================ // ============================================================================ class CDVRInputPin : public CBaseInputPin, public CDVRPin { CIDVRPinConnectionEvents * m_pIPinConnectEvent ; CIDVRDShowStream * m_pIDShowStream ; CCritSec * m_pRecvLock ; void LockFilter_ () { CBaseInputPin::m_pLock -> Lock () ; } void UnlockFilter_ () { CBaseInputPin::m_pLock -> Unlock () ; } void LockRecv_ () { m_pRecvLock -> Lock () ; } void UnlockRecv_ () { m_pRecvLock -> Unlock () ; } public : CDVRInputPin ( IN TCHAR * pszPinName, IN CBaseFilter * pOwningFilter, IN CIDVRPinConnectionEvents * pIPinConnectEvent, IN CIDVRDShowStream * pIDShowStream, IN CCritSec * pFilterLock, IN CCritSec * pRecvLock, IN CDVRPolicy * pPolicy, OUT HRESULT * phr ) ; ~CDVRInputPin ( ) ; void SetPinConnectEvent (CIDVRPinConnectionEvents * pIPinConnectEvent) { m_pIPinConnectEvent = pIPinConnectEvent ; } void SetDShowStreamEvent (CIDVRDShowStream * pIDShowStream) { m_pIDShowStream = pIDShowStream ; } // -------------------------------------------------------------------- // CBasePin methods HRESULT GetMediaType ( IN int iPosition, OUT CMediaType * pmt ) ; HRESULT CheckMediaType ( IN const CMediaType * ) ; virtual HRESULT CompleteConnect ( IN IPin * pReceivePin ) ; STDMETHODIMP QueryAccept ( IN const AM_MEDIA_TYPE * pmt ) ; STDMETHODIMP Receive ( IN IMediaSample * pIMS ) ; HRESULT Active ( IN BOOL fInlineProps ) ; } ; // ============================================================================ // ============================================================================ class CDVROutputPin : public CBaseOutputPin, public CDVRPin, public IMemAllocator, public IAMPushSource { enum DVR_SEG_OUTPUT_PIN_STATE { STATE_SEG_NEW_SEGMENT, STATE_SEG_IN_SEGMENT, } ; enum DVR_MEDIA_OUTPUT_PIN_STATE { STATE_MEDIA_COMPATIBLE, STATE_MEDIA_INCOMPATIBLE, } ; COutputQueue * m_pOutputQueue ; long m_cbBuffer ; long m_cBuffers ; long m_cbAlign ; long m_cbPrefix ; CMediaSampleWrapperPool m_MSWrappers ; CDVRDIMediaSeeking m_IMediaSeeking ; BOOL m_fTimestampedMedia ; DVR_SEG_OUTPUT_PIN_STATE m_DVRSegOutputPinState ; DVR_MEDIA_OUTPUT_PIN_STATE m_DVRMediaOutputPinState ; CDVRDShowSeekingCore * m_pSeekingCore ; CDVRSourcePinManager * m_pOwningPinBank ; void LockFilter_ () { CBaseOutputPin::m_pLock -> Lock () ; } void UnlockFilter_ () { CBaseOutputPin::m_pLock -> Unlock () ; } public : CDVROutputPin ( IN CDVRPolicy * pPolicy, IN TCHAR * pszPinName, IN CBaseFilter * pOwningFilter, IN CCritSec * pFilterLock, IN CDVRDShowSeekingCore * pSeekingCore, IN CDVRSendStatsWriter * pDVRSendStatsWriter, IN CDVRSourcePinManager * pOwningPinBank, OUT HRESULT * phr ) ; ~CDVROutputPin ( ) ; DECLARE_IUNKNOWN ; // for IMemAllocator, IAMPushSource, IMediaSeeking STDMETHODIMP NonDelegatingQueryInterface ( IN REFIID riid, OUT void ** ppv ) ; HRESULT SendSample ( IN IMediaSample2 * pIMS2, IN AM_MEDIA_TYPE * pmtNew ) ; CMediaSampleWrapper * WaitGetMSWrapper () { return m_MSWrappers.Get () ; } CMediaSampleWrapper * TryGetMSWrapper () { return m_MSWrappers.TryGet () ; } CDVRAttributeTranslator * GetTranslator () { return m_pTranslator ; } // -------------------------------------------------------------------- // CBasePin methods HRESULT SetPinMediaType ( IN AM_MEDIA_TYPE * pmt ) ; HRESULT Active ( ) ; HRESULT Inactive ( ) ; HRESULT DecideAllocator ( IN IMemInputPin * pPin, IN IMemAllocator ** ppAlloc ) ; HRESULT DecideBufferSize ( IN IMemAllocator * pAlloc, IN ALLOCATOR_PROPERTIES * ppropInputRequest ) ; HRESULT GetMediaType ( IN int iPosition, OUT CMediaType * pmt ) ; HRESULT CheckMediaType ( IN const CMediaType * ) ; HRESULT DeliverEndOfStream ( ) ; HRESULT DeliverBeginFlush ( ) ; HRESULT DeliverEndFlush ( ) ; HRESULT NotifyNewSegment ( ) ; // ==================================================================== // IMemAllocator STDMETHODIMP SetProperties( IN ALLOCATOR_PROPERTIES * pRequest, OUT ALLOCATOR_PROPERTIES * pActual ) ; STDMETHODIMP GetProperties( OUT ALLOCATOR_PROPERTIES * pProps ) ; STDMETHODIMP Commit ( ) ; STDMETHODIMP Decommit ( ) ; STDMETHODIMP GetBuffer ( OUT IMediaSample ** ppBuffer, OUT REFERENCE_TIME * pStartTime, OUT REFERENCE_TIME * pEndTime, IN DWORD dwFlags ) ; STDMETHODIMP ReleaseBuffer ( IN IMediaSample * pBuffer ) ; // ==================================================================== // IAMPushSource STDMETHODIMP GetPushSourceFlags ( OUT ULONG * pFlags ) { // set this purely to get around an ASSERT in quartz if (pFlags == NULL) { return E_POINTER ; } // we're not live in the strict sense; strict sense is that we are // received stored content i.e. non-live content is being pushed // (broadcast) to us. (* pFlags) = AM_PUSHSOURCECAPS_NOT_LIVE ; return S_OK ; } STDMETHODIMP SetPushSourceFlags ( IN ULONG Flags ) { return E_NOTIMPL ; } STDMETHODIMP SetStreamOffset ( IN REFERENCE_TIME rtOffset ) { return E_NOTIMPL ; } STDMETHODIMP GetStreamOffset ( OUT REFERENCE_TIME * prtOffset ) { return E_NOTIMPL ; } STDMETHODIMP GetMaxStreamOffset ( OUT REFERENCE_TIME * prtMaxOffset ) { return E_NOTIMPL ; } STDMETHODIMP SetMaxStreamOffset ( IN REFERENCE_TIME rtMaxOffset ) { return E_NOTIMPL ; } STDMETHODIMP GetLatency( IN REFERENCE_TIME * prtLatency ) { return E_NOTIMPL ; } } ; // ============================================================================ // ============================================================================ class CDVRSinkPinManager : public CTDVRPinBank <CDVRInputPin>, public CIDVRPinConnectionEvents { BOOL InlineDShowProps_ ( ) ; protected : CIDVRDShowStream * m_pIDVRDShowStream ; // set on pins we create CBaseFilter * m_pOwningFilter ; // owning filter CCritSec * m_pFilterLock ; // owning filter lock CCritSec * m_pRecvLock ; CDVRWriterProfile m_DVRWriterProfile ; // WM profile int m_cMaxInputPins ; CDVRPolicy * m_pPolicy ; void FilterLock_ () { m_pFilterLock -> Lock () ; } void FilterUnlock_ () { m_pFilterLock -> Unlock () ; } HRESULT CreateNextInputPin_ ( ) ; public : CDVRSinkPinManager ( IN CDVRPolicy * pPolicy, IN CBaseFilter * pOwningFilter, IN CCritSec * pFilterLock, IN CCritSec * pRecvLock, IN CIDVRDShowStream * pIDVRDShowStream, OUT HRESULT * phr ) ; ~CDVRSinkPinManager ( ) ; HRESULT Active ( ) ; HRESULT Inactive ( ) ; virtual HRESULT OnInputCompleteConnect ( IN int iPinIndex, IN AM_MEDIA_TYPE * pmt ) ; virtual HRESULT OnQueryAccept ( IN const AM_MEDIA_TYPE * pmt ) ; HRESULT GetRefdWMProfile (OUT IWMProfile ** ppIWMProfile) { return m_DVRWriterProfile.GetRefdWMProfile (ppIWMProfile) ; } DWORD GetProfileStreamCount () { return m_DVRWriterProfile.GetStreamCount () ; } } ; class CDVRThroughSinkPinManager : public CDVRSinkPinManager { CIDVRPinConnectionEvents * m_pIDVRInputPinConnectEvents ; public : CDVRThroughSinkPinManager ( IN CDVRPolicy * pPolicy, IN CBaseFilter * pOwningFilter, IN CCritSec * pFilterLock, IN CCritSec * pRecvLock, IN CIDVRDShowStream * pIDVRDShowStream, IN CIDVRPinConnectionEvents * pIDVRInputPinConnectEvents, OUT HRESULT * phr ) : CDVRSinkPinManager (pPolicy, pOwningFilter, pFilterLock, pRecvLock, pIDVRDShowStream, phr ), m_pIDVRInputPinConnectEvents (pIDVRInputPinConnectEvents) { ASSERT (m_pIDVRInputPinConnectEvents) ; } virtual HRESULT OnInputCompleteConnect ( IN int iPinIndex, IN AM_MEDIA_TYPE * pmt ) ; } ; class CDVRSourcePinManager : public CTDVRPinBank <CDVROutputPin> { CBaseFilter * m_pOwningFilter ; CCritSec * m_pFilterLock ; CDVRReaderProfile * m_pWMReaderProfile ; CTSmallMap <WORD, int> m_StreamNumToPinIndex ; CDVRPolicy * m_pPolicy ; CDVRDShowSeekingCore * m_pSeekingCore ; int m_iVideoPinIndex ; CDVRSendStatsWriter * m_pDVRSendStatsWriter ; BOOL m_fIsLiveSource ; void FilterLock_ () { m_pFilterLock -> Lock () ; } void FilterUnlock_ () { m_pFilterLock -> Unlock () ; } public : CDVRSourcePinManager ( IN CDVRPolicy * pPolicy, IN CBaseFilter * pOwningFilter, IN CCritSec * pFilterLock, IN CDVRDShowSeekingCore * pSeekingCore, IN BOOL fIsLiveSource = FALSE ) ; virtual ~CDVRSourcePinManager ( ) ; BOOL IsSeekingPin (CDVROutputPin *) ; void SetLiveSource (IN BOOL f) { m_fIsLiveSource = f ; } BOOL IsLiveSource () { return m_fIsLiveSource ; } HRESULT SetReaderProfile ( IN CDVRReaderProfile * pWMReaderProfile ) ; void SetStatsWriter (CDVRSendStatsWriter * pDVRSendStatsWriter) { m_pDVRSendStatsWriter = pDVRSendStatsWriter ; } HRESULT CreateOutputPin ( IN int iPinIndex, IN AM_MEDIA_TYPE * pmt ) ; HRESULT Active ( ) ; HRESULT Inactive ( ) ; CDVROutputPin * GetNonRefdOutputPin ( IN WORD wStreamNum ) ; HRESULT DeliverBeginFlush ( ) ; HRESULT DeliverEndFlush ( ) ; HRESULT DeliverEndOfStream ( ) ; HRESULT NotifyNewSegment ( ) ; } ; #endif // __tsdvr__shared__dvrpins_h