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
cc0609b0698a15fc1aa82fe9f9c4e550e191a6c2
9e02c151f257584592d7374b0045196a3fd2cf53
/AtCoder/AGC/009/A.cpp
a49aa2c3ff283ae7c58b6ed37078f7ebb8ca2ce1
[]
no_license
robertcal/cpp_competitive_programming
891c97f315714a6b1fc811f65f6be361eb642ef2
0bf5302f1fb2aa8f8ec352d83fa6281f73dec9b5
refs/heads/master
2021-12-13T18:12:31.930186
2021-09-29T00:24:09
2021-09-29T00:24:09
173,748,291
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
A.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1e9; const int MOD = 1e9 + 7; const ll LINF = 1e18; int main() { ll n; cin >> n; vector<ll> a(n); vector<ll> b(n); for (ll i = 0; i < n; ++i) { cin >> a[i] >> b[i]; } ll ans = 0; for (int i = n - 1; i >= 0; --i) { if (a[i] == 0 && ans == 0) continue; if (a[i] == 0 && ans > 0 && b[i] == 1) continue; if (a[i] > 0 && b[i] == 1) continue; if ((a[i] + ans) % b[i] == 0) continue; ll t = (a[i] + ans) / b[i]; ans += (t + 1) * b[i] - (a[i] + ans); } cout << ans << endl; }
bd2c0a359fdb78a2fd854ca356def5c64b13a9e8
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-9/java/util/PriorityQueue.hpp
0667be45c33523c475bf214acef6c5188133260b
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
10,645
hpp
PriorityQueue.hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.util.PriorityQueue ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_DECL #define J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Iterable; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace util { class SortedSet; } } } namespace j2cpp { namespace java { namespace util { class Iterator; } } } namespace j2cpp { namespace java { namespace util { class Queue; } } } namespace j2cpp { namespace java { namespace util { class AbstractQueue; } } } namespace j2cpp { namespace java { namespace util { class Collection; } } } namespace j2cpp { namespace java { namespace util { class Comparator; } } } namespace j2cpp { namespace java { namespace util { class AbstractCollection; } } } namespace j2cpp { namespace java { namespace io { class Serializable; } } } #include <java/io/Serializable.hpp> #include <java/lang/Iterable.hpp> #include <java/lang/Object.hpp> #include <java/util/AbstractCollection.hpp> #include <java/util/AbstractQueue.hpp> #include <java/util/Collection.hpp> #include <java/util/Comparator.hpp> #include <java/util/Iterator.hpp> #include <java/util/Queue.hpp> #include <java/util/SortedSet.hpp> namespace j2cpp { namespace java { namespace util { class PriorityQueue; class PriorityQueue : public object<PriorityQueue> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) explicit PriorityQueue(jobject jobj) : object<PriorityQueue>(jobj) { } operator local_ref<java::lang::Iterable>() const; operator local_ref<java::lang::Object>() const; operator local_ref<java::util::Queue>() const; operator local_ref<java::util::AbstractQueue>() const; operator local_ref<java::util::Collection>() const; operator local_ref<java::util::AbstractCollection>() const; operator local_ref<java::io::Serializable>() const; PriorityQueue(); PriorityQueue(jint); PriorityQueue(jint, local_ref< java::util::Comparator > const&); PriorityQueue(local_ref< java::util::Collection > const&); PriorityQueue(local_ref< java::util::PriorityQueue > const&); PriorityQueue(local_ref< java::util::SortedSet > const&); local_ref< java::util::Iterator > iterator(); jint size(); void clear(); jboolean offer(local_ref< java::lang::Object > const&); local_ref< java::lang::Object > poll(); local_ref< java::lang::Object > peek(); local_ref< java::util::Comparator > comparator(); jboolean remove(local_ref< java::lang::Object > const&); jboolean add(local_ref< java::lang::Object > const&); }; //class PriorityQueue } //namespace util } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_IMPL #define J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_IMPL namespace j2cpp { java::util::PriorityQueue::operator local_ref<java::lang::Iterable>() const { return local_ref<java::lang::Iterable>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::util::Queue>() const { return local_ref<java::util::Queue>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::util::AbstractQueue>() const { return local_ref<java::util::AbstractQueue>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::util::Collection>() const { return local_ref<java::util::Collection>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::util::AbstractCollection>() const { return local_ref<java::util::AbstractCollection>(get_jobject()); } java::util::PriorityQueue::operator local_ref<java::io::Serializable>() const { return local_ref<java::io::Serializable>(get_jobject()); } java::util::PriorityQueue::PriorityQueue() : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(0), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(0) >() ) { } java::util::PriorityQueue::PriorityQueue(jint a0) : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(1), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } java::util::PriorityQueue::PriorityQueue(jint a0, local_ref< java::util::Comparator > const &a1) : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(2), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(2) >(a0, a1) ) { } java::util::PriorityQueue::PriorityQueue(local_ref< java::util::Collection > const &a0) : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(3), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(3) >(a0) ) { } java::util::PriorityQueue::PriorityQueue(local_ref< java::util::PriorityQueue > const &a0) : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(4), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(4) >(a0) ) { } java::util::PriorityQueue::PriorityQueue(local_ref< java::util::SortedSet > const &a0) : object<java::util::PriorityQueue>( call_new_object< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(5), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(5) >(a0) ) { } local_ref< java::util::Iterator > java::util::PriorityQueue::iterator() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(6), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(6), local_ref< java::util::Iterator > >(get_jobject()); } jint java::util::PriorityQueue::size() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(7), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject()); } void java::util::PriorityQueue::clear() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(8), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject()); } jboolean java::util::PriorityQueue::offer(local_ref< java::lang::Object > const &a0) { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(9), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(9), jboolean >(get_jobject(), a0); } local_ref< java::lang::Object > java::util::PriorityQueue::poll() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(10), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(10), local_ref< java::lang::Object > >(get_jobject()); } local_ref< java::lang::Object > java::util::PriorityQueue::peek() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(11), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(11), local_ref< java::lang::Object > >(get_jobject()); } local_ref< java::util::Comparator > java::util::PriorityQueue::comparator() { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(12), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(12), local_ref< java::util::Comparator > >(get_jobject()); } jboolean java::util::PriorityQueue::remove(local_ref< java::lang::Object > const &a0) { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(13), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(13), jboolean >(get_jobject(), a0); } jboolean java::util::PriorityQueue::add(local_ref< java::lang::Object > const &a0) { return call_method< java::util::PriorityQueue::J2CPP_CLASS_NAME, java::util::PriorityQueue::J2CPP_METHOD_NAME(14), java::util::PriorityQueue::J2CPP_METHOD_SIGNATURE(14), jboolean >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::util::PriorityQueue,"java/util/PriorityQueue") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,1,"<init>","(I)V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,2,"<init>","(ILjava/util/Comparator;)V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,3,"<init>","(Ljava/util/Collection;)V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,4,"<init>","(Ljava/util/PriorityQueue;)V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,5,"<init>","(Ljava/util/SortedSet;)V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,6,"iterator","()Ljava/util/Iterator;") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,7,"size","()I") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,8,"clear","()V") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,9,"offer","(Ljava/lang/Object;)Z") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,10,"poll","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,11,"peek","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,12,"comparator","()Ljava/util/Comparator;") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,13,"remove","(Ljava/lang/Object;)Z") J2CPP_DEFINE_METHOD(java::util::PriorityQueue,14,"add","(Ljava/lang/Object;)Z") } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_PRIORITYQUEUE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
9b56c63c1442ac590c1c7c5744b7b12b5e0e4a62
64595cf9a39bb9289013add25710889264845328
/virtualkeyboard/lipiinputmethod.cpp
4f832573616d8835f2bb37ed881ac461c36868e8
[]
no_license
dorinbotan/QtJapanese
7bff5a2a5cca19671e377cde9555542ff3926933
81010b5d928afb8ac2dadc8f452ce14aad9bb12f
refs/heads/master
2021-06-20T00:08:40.558868
2017-07-06T08:35:48
2017-07-06T08:35:48
96,406,812
1
0
null
null
null
null
UTF-8
C++
false
false
28,929
cpp
lipiinputmethod.cpp
/****************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Virtual Keyboard module. ** ** $QT_BEGIN_LICENSE:COMM$ ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** $QT_END_LICENSE$ ** ******************************************************************************/ #include "lipiinputmethod.h" #include "lipisharedrecognizer.h" #include "inputengine.h" #include "inputcontext.h" #include "shifthandler.h" #include "virtualkeyboarddebug.h" #include "trace.h" #ifdef HAVE_HUNSPELL #include "hunspellinputmethod_p.h" #endif #include "LTKCaptureDevice.h" #include "LTKScreenContext.h" #include "LTKTraceGroup.h" #include "LTKChannel.h" #include "LTKTraceFormat.h" #include "LTKTrace.h" #include "LTKShapeRecoResult.h" #include <QCryptographicHash> #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT #include <QStandardPaths> #include <QFileInfo> #include <QDir> #endif #include <QtCore/qmath.h> #ifdef HAVE_HUNSPELL #define LipiInputMethodPrivateBase HunspellInputMethodPrivate #else #define LipiInputMethodPrivateBase AbstractInputMethodPrivate #endif namespace QtVirtualKeyboard { class LipiInputMethodPrivate : public LipiInputMethodPrivateBase { Q_DECLARE_PUBLIC(LipiInputMethod) public: LipiInputMethodPrivate(LipiInputMethod *q_ptr) : #ifdef HAVE_HUNSPELL LipiInputMethodPrivateBase(static_cast<HunspellInputMethod *>(q_ptr)), #else LipiInputMethodPrivateBase(), #endif q_ptr(q_ptr), recognizeTimer(0), textCase(InputEngine::Lower) { } ~LipiInputMethodPrivate() { cancelRecognition(); } QByteArray getContext(InputEngine::PatternRecognitionMode patternRecognitionMode, const QVariantMap &traceCaptureDeviceInfo, const QVariantMap &traceScreenInfo) const { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)&patternRecognitionMode, sizeof(patternRecognitionMode)); QByteArray mapData; QDataStream ds(&mapData, QIODevice::WriteOnly); ds << traceCaptureDeviceInfo; ds << traceScreenInfo; hash.addData(mapData); return hash.result(); } void setContext(InputEngine::PatternRecognitionMode patternRecognitionMode, const QVariantMap &traceCaptureDeviceInfo, const QVariantMap &traceScreenInfo) { QByteArray context = getContext(patternRecognitionMode, traceCaptureDeviceInfo, traceScreenInfo); if (context == currentContext) return; VIRTUALKEYBOARD_DEBUG() << "LipiInputMethodPrivate::setContext():" << QString(context.toHex()); clearTraces(); deviceInfo.reset(new LTKCaptureDevice()); deviceInfo->setSamplingRate(traceCaptureDeviceInfo.value("sampleRate", 60).toInt()); deviceInfo->setXDPI(traceCaptureDeviceInfo.value("dpi", 96).toInt()); deviceInfo->setYDPI(deviceInfo->getXDPI()); deviceInfo->setLatency(traceCaptureDeviceInfo.value("latency", 0.0).toFloat()); deviceInfo->setUniformSampling(traceCaptureDeviceInfo.value("uniform", false).toBool()); screenContext.reset(new LTKScreenContext()); QRectF boundingBox(traceScreenInfo.value("boundingBox").toRectF()); if (!boundingBox.isEmpty()) { screenContext->setBboxLeft(boundingBox.left()); screenContext->setBboxTop(boundingBox.top()); screenContext->setBboxRight(boundingBox.right()); screenContext->setBboxBottom(boundingBox.bottom()); } QVariantList horizontalRulers(traceScreenInfo.value("horizontalRulers", QVariantList()).toList()); if (!horizontalRulers.isEmpty()) { for (QVariantList::ConstIterator i = horizontalRulers.constBegin(); i != horizontalRulers.constEnd(); i++) { screenContext->addHLine(i->toFloat()); } } QVariantList verticalRulers(traceScreenInfo.value("verticalRulers", QVariantList()).toList()); if (!horizontalRulers.isEmpty()) { for (QVariantList::ConstIterator i = verticalRulers.constBegin(); i != verticalRulers.constEnd(); i++) { screenContext->addVLine(i->toFloat()); } } currentContext = context; } Trace *traceBegin(int traceId, InputEngine::PatternRecognitionMode patternRecognitionMode, const QVariantMap &traceCaptureDeviceInfo, const QVariantMap &traceScreenInfo) { Q_UNUSED(traceId) stopRecognizeTimer(); setContext(patternRecognitionMode, traceCaptureDeviceInfo, traceScreenInfo); if (recognitionTask) { recognizer.cancelRecognitionTask(recognitionTask); recognitionTask.reset(); delayedResult.clear(); } Trace *trace = new Trace(); trace->setChannels(QStringList("t")); traceList.append(trace); return trace; } void traceEnd(Trace *trace) { if (trace->isCanceled()) { VIRTUALKEYBOARD_DEBUG() << "LipiInputMethodPrivate::traceEnd(): discarded" << trace; traceList.removeOne(trace); delete trace; } else { addPointsToTraceGroup(trace); } handleGesture(); if (!traceList.isEmpty() && countActiveTraces() == 0) restartRecognition(); } int countActiveTraces() const { int count = 0; foreach (Trace *trace, traceList) { if (!trace->isFinal()) count++; } return count; } void handleGesture() { if (countActiveTraces() > 0) return; QVariantMap gesture = detectGesture(); if (gesture.isEmpty()) return; VIRTUALKEYBOARD_DEBUG() << "LipiInputMethodPrivate::handleGesture():" << gesture; if (gesture[QLatin1String("type")].toString() == QLatin1String("swipe")) { static const int SWIPE_MIN_LENGTH = 25; // mm static const int SWIPE_ANGLE_THRESHOLD = 15; // degrees +- qreal swipeLength = gesture[QLatin1String("length_mm")].toReal(); if (swipeLength >= SWIPE_MIN_LENGTH) { Q_Q(LipiInputMethod); InputContext *ic = q->inputContext(); if (!ic) return; qreal swipeAngle = gesture[QLatin1String("angle_degrees")].toReal(); int swipeTouchCount = gesture[QLatin1String("touch_count")].toInt(); // Swipe left if (swipeAngle <= 180 + SWIPE_ANGLE_THRESHOLD && swipeAngle >= 180 - SWIPE_ANGLE_THRESHOLD) { if (swipeTouchCount == 1) { // Single swipe: backspace #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT dumpTraces(); saveTraces(Qt::Key_Backspace, 100); #endif cancelRecognition(); ic->inputEngine()->virtualKeyClick(Qt::Key_Backspace, QString(), Qt::NoModifier); } else if (swipeTouchCount == 2) { // Double swipe: reset word, or backspace cancelRecognition(); if (!ic->preeditText().isEmpty()) { q->reset(); ic->setPreeditText(QString()); } else { ic->inputEngine()->virtualKeyClick(Qt::Key_Backspace, QString(), Qt::NoModifier); } } return; } // Swipe right if (swipeAngle <= SWIPE_ANGLE_THRESHOLD || swipeAngle >= 360 - SWIPE_ANGLE_THRESHOLD) { if (swipeTouchCount == 1) { // Single swipe: space #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT dumpTraces(); saveTraces(Qt::Key_Space, 100); #endif cancelRecognition(); ic->inputEngine()->virtualKeyClick(Qt::Key_Space, QString(" "), Qt::NoModifier); } else if (swipeTouchCount == 2) { // Double swipe: commit word, or insert space cancelRecognition(); #ifdef HAVE_HUNSPELL if (activeWordIndex != -1) { q->selectionListItemSelected(SelectionListModel::WordCandidateList, activeWordIndex); return; } #endif ic->inputEngine()->virtualKeyClick(Qt::Key_Space, QString(" "), Qt::NoModifier); } return; } // Swipe up if (swipeAngle <= 270 + SWIPE_ANGLE_THRESHOLD && swipeAngle >= 270 - SWIPE_ANGLE_THRESHOLD) { if (swipeTouchCount == 1) { // Single swipe: toggle input mode #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT dumpTraces(); saveTraces(Qt::Key_Mode_switch, 100); #endif cancelRecognition(); if (!(ic->inputMethodHints() & (Qt::ImhDialableCharactersOnly | Qt::ImhFormattedNumbersOnly | Qt::ImhDigitsOnly))) { InputEngine::InputMode inputMode = ic->inputEngine()->inputMode(); inputMode = inputMode == InputEngine::Latin ? InputEngine::Numeric : InputEngine::Latin; ic->inputEngine()->setInputMode(inputMode); } } else if (swipeTouchCount == 2) { // Double swipe: toggle text case cancelRecognition(); ic->shiftHandler()->toggleShift(); } return; } } } } QVariantMap detectGesture() { if (traceList.count() > 0 && traceList.count() < 3) { // Swipe gesture detection // ======================= // // The following algorithm is based on the assumption that a // vector composed of two arbitrary selected, but consecutive // measuring points, and a vector composed of the first and last // of the measuring points, are approximately in the same angle. // // If the measuring points are located very close to each other, // the angle can fluctuate a lot. This has been taken into account // by setting a minimum Euclidean distance between the measuring // points. // // Minimum euclidean distance of a segment (in millimeters) static const int MINIMUM_EUCLIDEAN_DISTANCE = 8; // Maximum theta variance (in degrees) static const qreal THETA_THRESHOLD = 25.0; // Maximum width variance in multitouch swipe (+- in percent) static const int MAXIMUM_WIDTH_VARIANCE = 20; const int dpi = deviceInfo->getXDPI() >= 0 ? deviceInfo->getXDPI() : 96; const qreal minimumEuclideanDistance = MINIMUM_EUCLIDEAN_DISTANCE / 25.4 * dpi; static const qreal thetaThreshold = qDegreesToRadians(THETA_THRESHOLD); QList<QVector2D> swipeVectors; int traceIndex; const int traceCount = traceList.size(); for (traceIndex = 0; traceIndex < traceCount; ++traceIndex) { const Trace *trace = traceList.at(traceIndex); const QVariantList &points = trace->points(); QVector2D swipeVector; const int pointCount = points.count(); int pointIndex = 0; if (pointCount >= 2) { QPointF startPosition = points.first().toPointF(); swipeVector = QVector2D(points.last().toPointF() - startPosition); const qreal swipeLength = swipeVector.length(); if (swipeLength >= minimumEuclideanDistance) { QPointF previousPosition = startPosition; qreal euclideanDistance = 0; for (pointIndex = 1; pointIndex < pointCount; ++pointIndex) { QPointF currentPosition(points.at(pointIndex).toPointF()); euclideanDistance += QVector2D(currentPosition - previousPosition).length(); if (euclideanDistance >= minimumEuclideanDistance) { // Set the angle (theta) between the sample vector and the swipe vector const QVector2D sampleVector(currentPosition - startPosition); const qreal theta = qAcos(QVector2D::dotProduct(swipeVector, sampleVector) / (swipeLength * sampleVector.length())); // Rejected when theta above threshold if (theta >= thetaThreshold) { swipeVector = QVector2D(); break; } startPosition = currentPosition; euclideanDistance = 0; } previousPosition = currentPosition; } if (pointIndex < pointCount) { swipeVector = QVector2D(); break; } // Check to see if angle and length matches to existing touch points if (!swipeVectors.isEmpty()) { bool matchesToExisting = true; const qreal minimumSwipeLength = (swipeLength * (100.0 - MAXIMUM_WIDTH_VARIANCE) / 100.0); const qreal maximumSwipeLength = (swipeLength * (100.0 + MAXIMUM_WIDTH_VARIANCE) / 100.0); foreach (const QVector2D &otherSwipeVector, swipeVectors) { const qreal otherSwipeLength = otherSwipeVector.length(); const qreal theta = qAcos(QVector2D::dotProduct(swipeVector, otherSwipeVector) / (swipeLength * otherSwipeLength)); if (theta >= thetaThreshold) { matchesToExisting = false; break; } if (otherSwipeLength < minimumSwipeLength || otherSwipeLength > maximumSwipeLength) { matchesToExisting = false; break; } } if (!matchesToExisting) { swipeVector = QVector2D(); break; } } } else { swipeVector = QVector2D(); } } if (swipeVector.isNull()) break; swipeVectors.append(swipeVector); } if (swipeVectors.size() == traceCount) { QVariantMap swipeGesture; // Get swipe angle from the first vector: // 0 degrees == right // 90 degrees == down // 180 degrees == left // 270 degrees == up QList<QVector2D>::ConstIterator swipeVector = swipeVectors.constBegin(); qreal swipeLength = swipeVector->length(); qreal swipeAngle = qAcos(swipeVector->x() / swipeLength); if (swipeVector->y() < 0) swipeAngle = 2 * M_PI - swipeAngle; // Calculate an average length of the vector for (++swipeVector; swipeVector != swipeVectors.end(); ++swipeVector) swipeLength += swipeVector->length(); swipeLength /= traceCount; swipeGesture[QLatin1String("type")] = QLatin1String("swipe"); swipeGesture[QLatin1String("angle")] = swipeAngle; swipeGesture[QLatin1String("angle_degrees")] = qRadiansToDegrees(swipeAngle); swipeGesture[QLatin1String("length")] = swipeLength; swipeGesture[QLatin1String("length_mm")] = swipeLength / dpi * 25.4; swipeGesture[QLatin1String("touch_count")] = traceCount; return swipeGesture; } } return QVariantMap(); } void clearTraces() { qDeleteAll(traceList); traceList.clear(); traceGroup.emptyAllTraces(); } void addPointsToTraceGroup(Trace *trace) { vector<LTKChannel> channels; channels.push_back(LTKChannel("X", DT_INT, true)); channels.push_back(LTKChannel("Y", DT_INT, true)); bool hasTime = trace->channels().contains("t"); if (hasTime) channels.push_back(LTKChannel("T", DT_FLOAT, true)); LTKTraceFormat traceFormat(channels); LTKTrace ltktrace(traceFormat); const QVariantList points = trace->points(); const QVariantList timeData = hasTime ? trace->channelData("t") : QVariantList(); QVariantList::ConstIterator t = timeData.constBegin(); foreach (const QVariant &p, points) { const QPointF pt(p.toPointF()); vector<float> point; point.push_back(pt.x()); point.push_back(pt.y()); if (hasTime) { point.push_back(t->toFloat()); t++; } ltktrace.addPoint(point); } traceGroup.addTrace(ltktrace); } void finishRecognition() { #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT dumpTraces(); #endif stopRecognizeTimer(); clearTraces(); if (recognitionTask && !delayedResult.isEmpty() && recognitionTask->resultId() == delayedResult["resultId"].toInt()) processResult(delayedResult); delayedResult.clear(); recognitionTask.reset(); } void restartRecognition() { recognitionTask = recognizer.newRecognition(*deviceInfo, *screenContext, subsetOfClasses, 0.0f, 4); if (recognitionTask) { Q_Q(LipiInputMethod); recognitionTask->traceGroup = traceGroup; QSharedPointer<LipiRecognitionResultsTask> resultsTask = recognizer.startRecognition(recognitionTask); q->connect(resultsTask.data(), SIGNAL(resultsAvailable(const QVariantList &)), SLOT(resultsAvailable(const QVariantList &))); resetRecognizeTimer(); } else { stopRecognizeTimer(); } } bool cancelRecognition() { stopRecognizeTimer(); clearTraces(); delayedResult.clear(); bool result = !recognitionTask.isNull(); recognitionTask.reset(); return recognizer.cancelRecognition() || result; } void resetRecognizeTimer() { Q_Q(LipiInputMethod); stopRecognizeTimer(); recognizeTimer = q->startTimer(300); } void stopRecognizeTimer() { if (recognizeTimer) { Q_Q(LipiInputMethod); q->killTimer(recognizeTimer); recognizeTimer = 0; } } void resultsAvailable(const QVariantList &resultList) { if (!resultList.isEmpty()) { const QVariantMap result = resultList.at(0).toMap(); if (recognitionTask && recognitionTask->resultId() == result["resultId"].toInt()) delayedResult = result; else processResult(result); } } void processResult(const QVariantMap &result) { const QChar ch = result["unicode"].toChar(); const QChar chUpper = ch.toUpper(); #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT // In recording mode, the text case must match with the current text case if (ch.isLetter() && (ch.isUpper() != (textCase == InputEngine::Upper))) return; saveTraces(ch.unicode(), qRound(result["confidence"].toDouble() * 100)); #endif Q_Q(LipiInputMethod); q->inputContext()->inputEngine()->virtualKeyClick((Qt::Key)chUpper.unicode(), textCase == InputEngine::Lower ? QString(ch.toLower()) : QString(chUpper), Qt::NoModifier); } #ifdef QT_VIRTUALKEYBOARD_LIPI_RECORD_TRACE_INPUT QStringList recordedData; void dumpTraces() { recordedData.clear(); recordedData.append(QStringLiteral(".VERSION 1.0")); recordedData.append(QStringLiteral(".HIERARCHY CHARACTER")); recordedData.append(QStringLiteral(".COORD X Y T")); recordedData.append(QStringLiteral(".SEGMENT CHARACTER")); recordedData.append(QStringLiteral(".X_DIM %1").arg(qRound(screenContext->getBboxRight()))); recordedData.append(QStringLiteral(".Y_DIM %1").arg(qRound(screenContext->getBboxBottom()))); recordedData.append(QStringLiteral(".X_POINTS_PER_INCH %1").arg(deviceInfo->getXDPI())); recordedData.append(QStringLiteral(".Y_POINTS_PER_INCH %1").arg(deviceInfo->getYDPI())); recordedData.append(QStringLiteral(".POINTS_PER_SECOND %1").arg(deviceInfo->getSamplingRate())); qlonglong t0 = 0; foreach (const Trace *trace, traceList) { const QVariantList &points = trace->points(); const bool hasTime = trace->channels().contains("t"); const QVariantList timeData = hasTime ? trace->channelData("t") : QVariantList(); QVariantList::ConstIterator t = timeData.constBegin(); if (t0 == 0 && hasTime) t0 = t->toLongLong(); recordedData.append(QStringLiteral(".PEN_DOWN")); foreach (const QVariant &point, points) { const QPointF pt(point.toPointF()); QString pointStr(QStringLiteral("%1 %2 ").arg(qRound(pt.x())).arg(qRound(pt.y()))); if (hasTime) { pointStr.append(QString::number(t->toLongLong() - t0)); t++; } else { pointStr.append(QStringLiteral("0")); } recordedData.append(pointStr); } recordedData.append(QStringLiteral(".PEN_UP")); } } void saveTraces(uint unicode, uint confidence) { QString fileName; QStringList homeLocations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); if (!homeLocations.isEmpty()) { QString filePath = QStringLiteral("%1/%2").arg(homeLocations.at(0)).arg("VIRTUAL_KEYBOARD_TRACES"); QDir fileDir(filePath); if (!fileDir.exists()) fileDir.mkpath(filePath); if (fileDir.exists()) { int fileIndex = 0; do { fileName = fileDir.absoluteFilePath(QStringLiteral("%1_%2_%3.txt").arg(unicode).arg(confidence, 3, 10, QLatin1Char('0')).arg(fileIndex++)); } while (QFileInfo(fileName).exists()); } } QString dataStr(recordedData.join('\n')); dataStr.append('\n'); QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { file.write(dataStr.toUtf8().constData()); } else { qWarning() << "Cannot open file for writing" << fileName; } } #endif LipiInputMethod *q_ptr; LipiSharedRecognizer recognizer; QByteArray currentContext; QScopedPointer<LTKCaptureDevice> deviceInfo; QScopedPointer<LTKScreenContext> screenContext; QSharedPointer<LipiRecognitionTask> recognitionTask; LTKTraceGroup traceGroup; QList<Trace *> traceList; int recognizeTimer; InputEngine::TextCase textCase; vector<int> subsetOfClasses; QVariantMap delayedResult; }; /*! \class QtVirtualKeyboard::LipiInputMethod \internal */ LipiInputMethod::LipiInputMethod(QObject *parent) : LipiInputMethodBase(*new LipiInputMethodPrivate(this), parent) { } LipiInputMethod::~LipiInputMethod() { } QList<InputEngine::InputMode> LipiInputMethod::inputModes(const QString &locale) { Q_UNUSED(locale) return QList<InputEngine::InputMode>() << InputEngine::Latin << InputEngine::Numeric << InputEngine::Dialable; } bool LipiInputMethod::setInputMode(const QString &locale, InputEngine::InputMode inputMode) { Q_UNUSED(locale) Q_D(LipiInputMethod); #ifdef HAVE_HUNSPELL HunspellInputMethod::setInputMode(locale, inputMode); #endif bool result = d->recognizer.setModel(QStringLiteral("SHAPEREC_ALPHANUM")); if (!result) return false; d->subsetOfClasses.clear(); switch (inputMode) { case InputEngine::Latin: d->recognizer.subsetOfClasses(QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?,.@"), d->subsetOfClasses); break; case InputEngine::Numeric: case InputEngine::Dialable: d->recognizer.subsetOfClasses(QStringLiteral("1234567890,.+"), d->subsetOfClasses); break; default: break; } return true; } bool LipiInputMethod::setTextCase(InputEngine::TextCase textCase) { Q_D(LipiInputMethod); d->textCase = textCase; #ifdef HAVE_HUNSPELL HunspellInputMethod::setTextCase(textCase); #endif return true; } bool LipiInputMethod::keyEvent(Qt::Key key, const QString &text, Qt::KeyboardModifiers modifiers) { #ifdef HAVE_HUNSPELL Q_D(LipiInputMethod); switch (key) { case Qt::Key_Enter: case Qt::Key_Return: d->cancelRecognition(); break; case Qt::Key_Backspace: if (d->cancelRecognition()) return true; break; default: break; } return HunspellInputMethod::keyEvent(key, text, modifiers); #else Q_UNUSED(key) Q_UNUSED(text) Q_UNUSED(modifiers) return false; #endif } void LipiInputMethod::reset() { LipiInputMethodBase::reset(); Q_D(LipiInputMethod); d->cancelRecognition(); } void LipiInputMethod::update() { LipiInputMethodBase::update(); } void LipiInputMethod::selectionListItemSelected(SelectionListModel::Type type, int index) { LipiInputMethodBase::selectionListItemSelected(type, index); Q_D(LipiInputMethod); d->cancelRecognition(); } QList<InputEngine::PatternRecognitionMode> LipiInputMethod::patternRecognitionModes() const { return QList<InputEngine::PatternRecognitionMode>() << InputEngine::HandwritingRecoginition; } Trace *LipiInputMethod::traceBegin(int traceId, InputEngine::PatternRecognitionMode patternRecognitionMode, const QVariantMap &traceCaptureDeviceInfo, const QVariantMap &traceScreenInfo) { Q_D(LipiInputMethod); return d->traceBegin(traceId, patternRecognitionMode, traceCaptureDeviceInfo, traceScreenInfo); } bool LipiInputMethod::traceEnd(Trace *trace) { Q_D(LipiInputMethod); d->traceEnd(trace); return true; } void LipiInputMethod::timerEvent(QTimerEvent *timerEvent) { Q_D(LipiInputMethod); if (timerEvent->timerId() == d->recognizeTimer) { d->finishRecognition(); } } void LipiInputMethod::resultsAvailable(const QVariantList &resultList) { #ifdef QT_VIRTUALKEYBOARD_DEBUG { VIRTUALKEYBOARD_DEBUG() << "LipiInputMethod::resultsAvailable():"; for (int i = 0; i < resultList.size(); i++) { QVariantMap result = resultList.at(i).toMap(); VIRTUALKEYBOARD_DEBUG() << QString("%1: %2 (%3)").arg(i + 1).arg(result["unicode"].toChar()).arg(result["confidence"].toFloat()).toUtf8().constData(); } } #endif Q_D(LipiInputMethod); d->resultsAvailable(resultList); } } // namespace QtVirtualKeyboard
a72585f275c585c47f6ac66323fed0352dab49e5
270f577621a657bfe023f48e24771726b21d0907
/src/SimulinkConnector.h
0f5ad722db719fe2d7c3861274eb32a4e2c34288
[ "MIT" ]
permissive
WRidder/Arduino-SimulinkConnector
8a55e270c5c12540f63d026627c278537a2073ba
621f703922e9fe3298add22058b353e2876920ef
refs/heads/master
2021-01-22T16:18:11.377985
2015-03-28T14:10:07
2015-03-28T14:10:07
32,677,572
0
0
null
null
null
null
UTF-8
C++
false
false
6,098
h
SimulinkConnector.h
#ifndef __SIMULINKCONNECTOR_H__ #define __SIMULINKCONNECTOR_H__ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include <iterator> // The iterator has to be included if you want to use <vector> #include <vector> #include <climits> /** * Provides an interface between simulink and Arduino. * * Dependencies: * STL library: iterator, vector and climits. See https://github.com/maniacbug/StandardCplusplus * * Usage example (check function specific descriptions for extra information): * Initialization: * std::vector<long> outputPacketVector(5,0); * std::vector<long> receivedPacketVector(5,0); // We expect 5 values from simulink * SimulinkConnector simulinkConnection("S %l %l %l %l %l E", receivedPacketVector, outputPacketVector, 20); * * Arduino loop: * simulinkConnection.update(); * * Set output variables (at any point in the loop or supporting function): * outputPacketVector[0] = 99; * * Read input variables (this is always accesible after initialization): * int incomingValue = receivedPacketVector[2] // Read third value of incoming data vector * * <p> * The simulink->arduino protocol is defined as follows: * "<Start bit><Data><Stop bit>" * The start bit always consists of: '<'[char] / 60[DEC] (8 bits). * The end bit always consists of: '>'[char] / 62[DEC] (8 bits). * * Currently CRC checks have not been implemented. This is is mainly because this library is meant to be used with USB serial which has its own CRC as well. * * <p> * More information on serial connections: * http://www.pjrc.com/teensy/td_serial.html * http://eopossum.blogspot.nl/2011/11/processing-simple-osc-messages-on.html * http://my.safaribooksonline.com/book/hobbies/9781449399368/serial-communications/sending_binary_values_from_processing * http://leaflabs.com/docs/lang/cpp/bitshift.html * http://stackoverflow.com/questions/15869609/arduino-trouble-with-serial-readbytes-when-reading-from-a-java-program-over-us * http://www.gammon.com.au/forum/?id=11425 * * @author Wilbert van de Ridder <l.w.vanderidder @ student.utwente.nl> * @version 1.1 * @since 2013-07-07 */ class SimulinkConnector { public: /** * Constructor * * The output format accepts the following types: * l = long * ul = unsigned long * u = unsigned int * i or d = int * Multiple datatypes can be used at once, however, * the sendPacket() function only accepts long types. * You can use casting to transmit the other datatypes. * * @param aOutputFormat char string containing the output format; e.g. "S %d %l %ul E". * @param aInputPacketVector vector to which serial input will be written * @param aOutputPacketVector vector from which output serial is composed * @param aOutputInterval sample time of serial output in milliseconds */ SimulinkConnector(char* aOutputFormat, std::vector<long>& aInputPacketVector, const std::vector<long>& aOutputPacketVector, int aOutputInterval); /** * Constructor * * The output format accepts the following types: * l = long * ul = unsigned long * u = unsigned int * i or d = int * Multiple datatypes can be used at once, however, * the sendPacket() function only accepts long types. * You can use casting to transmit the other datatypes. * * @param aOutputFormat char string containing the output format; e.g. "S %d %l %ul E". * @param aInputPacketVector vector to which serial input will be written * @param aOutputPacketVector vector from which output serial is composed * @param aOutputInterval sample time of serial output in milliseconds * @param aEnabled boolean to indicate whether the connection is active */ SimulinkConnector(char* aOutputFormat, std::vector<long>& aInputPacketVector, const std::vector<long>& aOutputPacketVector, int aOutputInterval, bool aEnabled); /** * Updates/changes the output serial packet format. * * @param aOutputFormat string containing the output format; */ void setPacketFormat(char* aOutputFormat); /** * Check if new serial input has been received * * @return boolean */ bool isUpdated(); /** * Update the simulink connection. Checks for incoming messages and sends output message if sample time interval has passed. * * @return boolean */ void update(); /** * Enable or disable the current connection. * * @param bool to enable/disable */ void enable(bool); private: /** * The serial output format; e.g. "S %d %d %d E" */ char* outputFormat; /** * Keeps track of the current state. Currently these are defined: * 0. Wait for start bit * 1. Receiving data * 2. Checking end bit * 3. CRC check (not used at the moment) */ byte currentState; /** * Checks for incoming messages */ void checkIncoming(); /** * Transition to next packet read state */ void nextState(); /** * Sends a data packet using serial output in the format defined earlier. * * @see SimulinkConnector() * @see setPacketFormat() * @see outputFormat */ void sendPacket(); /** * Helper function to set default values. To be called from any of the constructors. */ void setDefaults(); /** * Keep track of available amount of states */ byte totalStates; /** * boolean to store new incoming message available indication */ bool updated; /** * value to keep track of what index the currently receiving value has in the output vector */ byte currentValuePosition; /** * Sample time of output messages in milliseconds */ int outputInterval; /** * Save timestamp of last update */ long lastUpdateTime; /** * Reference vector of received values */ std::vector<long>& inputPacketVector; /** * Reference vector of output values */ const std::vector<long>& outputPacketVector; /** * Boolean to track whether the connection is enabled */ bool enabled; }; #endif
8be9b670ad7fe2abdde23b83a5a62127352da029
fe300d59765c4d5fe846d26533f03d060d783275
/geneticAlgorithm/Menu/CMenuTree.h
b6e6761aad90f4088482d5af4ed8ef5552680f99
[]
no_license
Joanna065/GeneticAlgorithm
30b5854ad95cd45d992be96a99e253e3e2ac485a
db3757087803699dfe6f63aa3431877f385760d4
refs/heads/master
2020-04-29T19:40:26.279487
2019-05-23T08:01:44
2019-05-23T08:01:44
176,363,124
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
CMenuTree.h
#pragma once #include <string> class CMenuItem; class CManager; class CMenuTree { public: CMenuTree(); ~CMenuTree(); void vInitMenuItems(CManager* pcManager); bool bInitMenuItems(std::string& sReadStringMenu); void vRunMenu(); bool bRunMenu(std::string& sReadStringMenu); CMenuItem* pcGetRootMenu() const { return pc_root; } private: CMenuItem* pc_root; };
9c41ebf6d2460ae4442e0a9e08794fa979b846a4
5afcc3b02b7f4fe14e90f33b0a42bfc51b278e19
/ml-cv/cv/cimg_to_slow.cc
6b2e4001088305af7dd54d153165e00a0ed0f9fe
[ "MIT", "Apache-2.0" ]
permissive
zaqwes8811/micro-apps
c9e51fa7931c9d5625e1517bad7b1593104a50c0
bb1643562751dda70ae4f8bd632a171f1de05df5
refs/heads/master
2023-04-27T21:04:09.457192
2023-04-25T08:41:23
2023-04-25T08:41:23
11,820,285
1
0
null
null
null
null
UTF-8
C++
false
false
1,173
cc
cimg_to_slow.cc
#include "CImg.h" #include <iostream> #include <sys/time.h> using namespace std; using namespace cimg_library; int main () { //CImg<unsigned char> img("photo.jpeg"); //(img, img.get_blur(8)).display("Hello, CImg!"); unsigned char tab[1024*1024] = { 212 }; CImg<unsigned char> img(tab,1024,1024,1,1,true); // http://cimg.eu/reference/structcimg__library_1_1CImg.html //const CImg<float> img1(129,129,1,3,"0,64,128,192,255",true); // Construct image filled from a value sequence. //const CImg<float> img2(129,129,1,3,"if(c==0,255*abs(cos(x/10)),1.8*y)",false); // Construct image filled from a formula. //(img1,img2).display(); struct timeval t1, t2; double elapsedTime; // start timer gettimeofday(&t1, NULL); // do something // ... img.get_blur(1); // stop timer gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms cout << elapsedTime << " ms.\n"; //(img, img.get_blur(8)).display("Hello, CImg!"); return 0; }
abdea79d9e8a64343c174461e9cf63e45e2c46ac
7cfed835bcd18eb8410e8ea7f15e2664de86b1fd
/Force/main.cpp
f3b4657e5a894196f2cc2e1cbe54ff0867d1daa5
[]
no_license
Syntriax/SFML_Experiments
282aa81df09a6d21ff753f1f9cddd8bf9e9e4a78
b964978394991a4c4f6bebf2d309e1f598b1e641
refs/heads/master
2020-12-04T11:35:55.749828
2020-05-09T09:35:23
2020-05-09T09:35:23
231,749,863
0
0
null
null
null
null
UTF-8
C++
false
false
4,621
cpp
main.cpp
#include <SFML/Graphics.hpp> #include <sstream> #include <math.h> #include "Entity.h" #define WindowSize sf::VideoMode(960, 540) #define WindowStyle sf::Style::Titlebar | sf::Style::Close #define WindowTitle "Test Window Syntriax" sf::Vertex CreateVertex(double, double); int main() { std::ostringstream textToDisplay; sf::RenderWindow window(WindowSize, WindowTitle, WindowStyle); sf::Event event; sf::Clock clock; sf::Text text; sf::Font font; sf::Vector2f vector; float radiantValue; float timePassed; float deltaTime; float force = 1000; EntityPool pool; bool isFocused = true; bool isFixedForce = true; pool.SetGravity(false); pool.SetDrag(0.0); if (!font.loadFromFile("../OpenSans-Bold.ttf")) return -1; text.setFont(font); window.setVerticalSyncEnabled(true); // window.setFramerateLimit(140); while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::LostFocus) isFocused = false; else if (event.type == sf::Event::GainedFocus) isFocused = true; else if (event.type == sf::Event::KeyPressed) { if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) pool.RemoveEntities(pool.Size()); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) pool.SetDrag(2); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) pool.SetDrag(1); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) pool.SetDrag(0.5); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::F)) pool.SetDrag(0.25); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::G)) pool.SetDrag(0.1); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::H)) pool.SetDrag(0.0); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) force = 100; else if(sf::Keyboard::isKeyPressed(sf::Keyboard::X)) force = 500; else if(sf::Keyboard::isKeyPressed(sf::Keyboard::C)) force = 1000; else if(sf::Keyboard::isKeyPressed(sf::Keyboard::V)) force = 2500; else if(sf::Keyboard::isKeyPressed(sf::Keyboard::B)) force = 10000; else if(sf::Keyboard::isKeyPressed(sf::Keyboard::L)) isFixedForce = !isFixedForce; } } if(!isFocused) { timePassed = clock.getElapsedTime().asSeconds(); continue; } deltaTime = clock.getElapsedTime().asSeconds() - timePassed; timePassed = clock.getElapsedTime().asSeconds(); pool.Update(deltaTime); textToDisplay.str(""); textToDisplay.clear(); textToDisplay << "Entity Count: " << pool.Size() << "\nDrag: " << pool.GetDrag() << "\nForce: " << force << "\nForce Mode: " << (isFixedForce ? "Fixed" : "Distance") << "\nFPS: " << (1.0 / deltaTime); text.setString(textToDisplay.str()); if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Right)) { vector = (sf::Vector2f) sf::Mouse::getPosition(window); for (int i = 0; i < 18; i++) { radiantValue = ((float)i / 18.0 * 7.28) + timePassed; pool.AddNewEntity(vector.x + sin(radiantValue) * 100.0, vector.y + cos(radiantValue) * 100.0); } } if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) pool.ForceToPoint((sf::Vector2f) sf::Mouse::getPosition(window), force, deltaTime, isFixedForce); if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Middle)) pool.ForceFromPoint((sf::Vector2f) sf::Mouse::getPosition(window), force, deltaTime, isFixedForce); window.clear(); for (int i = 0; i < pool.Size(); i++) window.draw(&pool[i].GetVertex(), 1, sf::PrimitiveType::Points); window.draw(text); // window.draw(&player.GetVertex(), 1, sf::PrimitiveType::Points); window.display(); } return 0; } sf::Vertex CreateVertex(double x, double y) { return sf::Vertex(sf::Vector2f(x, y)); }
c38ae31b203d675e78a292f4092975c487c2ef0f
54f5c5be8d40e432135d2fb4223deb4531a462eb
/bin/include/format/abc/Operation.h
48b27d73a17e2244668104aac61a6d3b1c893250
[]
no_license
jet6666/swfrocks
d4b82d8a5c707b1ff590e18aa1a802a0f3c8bee9
aec09f09fd04f4beaedad64d15db4b38706af006
refs/heads/master
2021-01-20T10:42:11.706666
2014-08-21T11:16:06
2014-08-21T11:16:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,825
h
Operation.h
#ifndef INCLUDED_format_abc_Operation #define INCLUDED_format_abc_Operation #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(format,abc,Operation) namespace format{ namespace abc{ class Operation_obj : public hx::EnumBase_obj { typedef hx::EnumBase_obj super; typedef Operation_obj OBJ_; public: Operation_obj() {}; HX_DO_ENUM_RTTI; static void __boot(); static void __register(); ::String GetEnumName( ) const { return HX_CSTRING("format.abc.Operation"); } ::String __ToString() const { return HX_CSTRING("Operation.") + tag; } static ::format::abc::Operation OpAdd; static inline ::format::abc::Operation OpAdd_dyn() { return OpAdd; } static ::format::abc::Operation OpAnd; static inline ::format::abc::Operation OpAnd_dyn() { return OpAnd; } static ::format::abc::Operation OpAs; static inline ::format::abc::Operation OpAs_dyn() { return OpAs; } static ::format::abc::Operation OpBitNot; static inline ::format::abc::Operation OpBitNot_dyn() { return OpBitNot; } static ::format::abc::Operation OpDecr; static inline ::format::abc::Operation OpDecr_dyn() { return OpDecr; } static ::format::abc::Operation OpDiv; static inline ::format::abc::Operation OpDiv_dyn() { return OpDiv; } static ::format::abc::Operation OpEq; static inline ::format::abc::Operation OpEq_dyn() { return OpEq; } static ::format::abc::Operation OpGt; static inline ::format::abc::Operation OpGt_dyn() { return OpGt; } static ::format::abc::Operation OpGte; static inline ::format::abc::Operation OpGte_dyn() { return OpGte; } static ::format::abc::Operation OpIAdd; static inline ::format::abc::Operation OpIAdd_dyn() { return OpIAdd; } static ::format::abc::Operation OpIDecr; static inline ::format::abc::Operation OpIDecr_dyn() { return OpIDecr; } static ::format::abc::Operation OpIIncr; static inline ::format::abc::Operation OpIIncr_dyn() { return OpIIncr; } static ::format::abc::Operation OpIMul; static inline ::format::abc::Operation OpIMul_dyn() { return OpIMul; } static ::format::abc::Operation OpINeg; static inline ::format::abc::Operation OpINeg_dyn() { return OpINeg; } static ::format::abc::Operation OpISub; static inline ::format::abc::Operation OpISub_dyn() { return OpISub; } static ::format::abc::Operation OpIn; static inline ::format::abc::Operation OpIn_dyn() { return OpIn; } static ::format::abc::Operation OpIncr; static inline ::format::abc::Operation OpIncr_dyn() { return OpIncr; } static ::format::abc::Operation OpIs; static inline ::format::abc::Operation OpIs_dyn() { return OpIs; } static ::format::abc::Operation OpLt; static inline ::format::abc::Operation OpLt_dyn() { return OpLt; } static ::format::abc::Operation OpLte; static inline ::format::abc::Operation OpLte_dyn() { return OpLte; } static ::format::abc::Operation OpMemGet16; static inline ::format::abc::Operation OpMemGet16_dyn() { return OpMemGet16; } static ::format::abc::Operation OpMemGet32; static inline ::format::abc::Operation OpMemGet32_dyn() { return OpMemGet32; } static ::format::abc::Operation OpMemGet8; static inline ::format::abc::Operation OpMemGet8_dyn() { return OpMemGet8; } static ::format::abc::Operation OpMemGetDouble; static inline ::format::abc::Operation OpMemGetDouble_dyn() { return OpMemGetDouble; } static ::format::abc::Operation OpMemGetFloat; static inline ::format::abc::Operation OpMemGetFloat_dyn() { return OpMemGetFloat; } static ::format::abc::Operation OpMemSet16; static inline ::format::abc::Operation OpMemSet16_dyn() { return OpMemSet16; } static ::format::abc::Operation OpMemSet32; static inline ::format::abc::Operation OpMemSet32_dyn() { return OpMemSet32; } static ::format::abc::Operation OpMemSet8; static inline ::format::abc::Operation OpMemSet8_dyn() { return OpMemSet8; } static ::format::abc::Operation OpMemSetDouble; static inline ::format::abc::Operation OpMemSetDouble_dyn() { return OpMemSetDouble; } static ::format::abc::Operation OpMemSetFloat; static inline ::format::abc::Operation OpMemSetFloat_dyn() { return OpMemSetFloat; } static ::format::abc::Operation OpMod; static inline ::format::abc::Operation OpMod_dyn() { return OpMod; } static ::format::abc::Operation OpMul; static inline ::format::abc::Operation OpMul_dyn() { return OpMul; } static ::format::abc::Operation OpNeg; static inline ::format::abc::Operation OpNeg_dyn() { return OpNeg; } static ::format::abc::Operation OpNot; static inline ::format::abc::Operation OpNot_dyn() { return OpNot; } static ::format::abc::Operation OpOr; static inline ::format::abc::Operation OpOr_dyn() { return OpOr; } static ::format::abc::Operation OpPhysEq; static inline ::format::abc::Operation OpPhysEq_dyn() { return OpPhysEq; } static ::format::abc::Operation OpShl; static inline ::format::abc::Operation OpShl_dyn() { return OpShl; } static ::format::abc::Operation OpShr; static inline ::format::abc::Operation OpShr_dyn() { return OpShr; } static ::format::abc::Operation OpSign1; static inline ::format::abc::Operation OpSign1_dyn() { return OpSign1; } static ::format::abc::Operation OpSign16; static inline ::format::abc::Operation OpSign16_dyn() { return OpSign16; } static ::format::abc::Operation OpSign8; static inline ::format::abc::Operation OpSign8_dyn() { return OpSign8; } static ::format::abc::Operation OpSub; static inline ::format::abc::Operation OpSub_dyn() { return OpSub; } static ::format::abc::Operation OpUShr; static inline ::format::abc::Operation OpUShr_dyn() { return OpUShr; } static ::format::abc::Operation OpXor; static inline ::format::abc::Operation OpXor_dyn() { return OpXor; } }; } // end namespace format } // end namespace abc #endif /* INCLUDED_format_abc_Operation */
c484eb9b9fe4a96e2ab943659dc5d4d8361e3d37
545882210ca9bbd0d10f4f29fe7fef83703364b6
/include/lxw_item.hpp
17ffb6879111b31dc82999a2153fae4ae324ce2d
[]
no_license
kioku-systemk/mrzExporter
8992ccf4c78f94bc284b3fb1697c1f54d5323a81
73d803d8b6031cda6abeebe539a12f1bcc04da4a
refs/heads/master
2021-01-15T17:45:31.719753
2014-01-30T11:11:09
2014-01-30T11:11:09
12,744,819
2
0
null
null
null
null
UTF-8
C++
false
false
27,507
hpp
lxw_item.hpp
/* * C++ wrapper for lxitem.h * * Copyright (c) 2008-2013 Luxology LLC * * 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. Except as contained * in this notice, the name(s) of the above copyright holders shall not be * used in advertising or otherwise to promote the sale, use or other dealings * in this Software without prior written authorization. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #ifndef LXW_ITEM_HPP #define LXW_ITEM_HPP #include <lxitem.h> #include <lx_wrap.hpp> #include <string> namespace lx { static const LXtGUID guid_ChannelGraph = {0xF70C8AD7,0xC15F,0x42e7,0x98,0xF6,0x4C,0x4C,0x7F,0x6D,0x57,0x7E}; static const LXtGUID guid_Item = {0x7FF2D6D5,0x5E28,0x4650,0x93,0xED,0x89,0xFF,0x25,0x7F,0x96,0x29}; static const LXtGUID guid_ItemGraph = {0xC34D7C65,0x031A,0x4c9d,0x8C,0x01,0x31,0x87,0xD3,0x83,0x93,0x7B}; static const LXtGUID guid_Scene = {0xFF870F44,0xFED9,0x4dbc,0x95,0xBA,0x29,0x72,0xA4,0x3F,0xC9,0x36}; static const LXtGUID guid_SceneGraph = {0xFE07D3C5,0xC7E4,0x46af,0x8F,0x0A,0x5A,0xB1,0x73,0xD4,0x84,0x45}; static const LXtGUID guid_Scene2Service = {0x3B1E02DD,0x8ACA,0x4f30,0x99,0xC4,0xF8,0x7B,0x62,0x6D,0x4F,0xA3}; static const LXtGUID guid_SceneService = {0x50190141,0x0059,0x48FE,0xB2,0x7D,0x6C,0x98,0xE1,0x34,0x8D,0x7B}; }; class CLxLoc_ChannelGraph : public CLxLocalize<ILxChannelGraphID> { public: void _init() {m_loc=0;} CLxLoc_ChannelGraph() {_init();} CLxLoc_ChannelGraph(ILxUnknownID obj) {_init();set(obj);} CLxLoc_ChannelGraph(const CLxLoc_ChannelGraph &other) {_init();set(other.m_loc);} const LXtGUID * guid() const {return &lx::guid_ChannelGraph;} LxResult AddLink (ILxUnknownID from, int fromChan, ILxUnknownID to, int toChan) { return m_loc[0]->AddLink (m_loc,(ILxUnknownID)from,fromChan,(ILxUnknownID)to,toChan); } LxResult SetLink (ILxUnknownID from, int fromChan, int fromIndex, ILxUnknownID to, int toChan, int toIndex) { return m_loc[0]->SetLink (m_loc,(ILxUnknownID)from,fromChan,fromIndex,(ILxUnknownID)to,toChan,toIndex); } LxResult DeleteLink (ILxUnknownID from, int fromChan, ILxUnknownID to, int toChan) { return m_loc[0]->DeleteLink (m_loc,(ILxUnknownID)from,fromChan,(ILxUnknownID)to,toChan); } LxResult FwdCount (ILxUnknownID item, int channel, unsigned *count) { return m_loc[0]->FwdCount (m_loc,(ILxUnknownID)item,channel,count); } LxResult FwdByIndex (ILxUnknownID item, int channel, unsigned index, void **ppvObj, int *objChan) { return m_loc[0]->FwdByIndex (m_loc,(ILxUnknownID)item,channel,index,ppvObj,objChan); } bool FwdByIndex (ILxUnknownID item, int channel, unsigned index, CLxLocalizedObject &dest, int *objChan) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->FwdByIndex (m_loc,(ILxUnknownID)item,channel,index,&obj,objChan)) && dest.take(obj); } LxResult RevCount (ILxUnknownID item, int channel, unsigned *count) { return m_loc[0]->RevCount (m_loc,(ILxUnknownID)item,channel,count); } LxResult RevByIndex (ILxUnknownID item, int channel, unsigned index, void **ppvObj, int *objChan) { return m_loc[0]->RevByIndex (m_loc,(ILxUnknownID)item,channel,index,ppvObj,objChan); } bool RevByIndex (ILxUnknownID item, int channel, unsigned index, CLxLocalizedObject &dest, int *objChan) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RevByIndex (m_loc,(ILxUnknownID)item,channel,index,&obj,objChan)) && dest.take(obj); } }; class CLxLoc_Item : public CLxLocalize<ILxItemID> { public: void _init() {m_loc=0;} CLxLoc_Item() {_init();} CLxLoc_Item(ILxUnknownID obj) {_init();set(obj);} CLxLoc_Item(const CLxLoc_Item &other) {_init();set(other.m_loc);} const LXtGUID * guid() const {return &lx::guid_Item;} LXtItemType Type (void) { return m_loc[0]->Type (m_loc); } LxResult TestType (LXtItemType type) { return m_loc[0]->TestType (m_loc,type); } LxResult TestTypes (const LXtItemType *types) { return m_loc[0]->TestTypes (m_loc,types); } LxResult Ident (const char **ident) const { return m_loc[0]->Ident (m_loc,ident); } LxResult SetIdent (const char *ident) { return m_loc[0]->SetIdent (m_loc,ident); } LxResult Name (const char **name) { return m_loc[0]->Name (m_loc,name); } LxResult SetName (const char *name) { return m_loc[0]->SetName (m_loc,name); } LxResult UniqueName (const char **name) { return m_loc[0]->UniqueName (m_loc,name); } LxResult UniqueIndex (unsigned *index) { return m_loc[0]->UniqueIndex (m_loc,index); } LxResult SetUniqueIndex (unsigned index) { return m_loc[0]->SetUniqueIndex (m_loc,index); } LxResult Parent (void **ppvObj) { return m_loc[0]->Parent (m_loc,ppvObj); } bool Parent (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Parent (m_loc,&obj)) && dest.take(obj); } LxResult SetParent (ILxUnknownID parent) { return m_loc[0]->SetParent (m_loc,(ILxUnknownID)parent); } LxResult SubCount (unsigned *count) { return m_loc[0]->SubCount (m_loc,count); } LxResult SubByIndex (unsigned index, void **ppvObj) { return m_loc[0]->SubByIndex (m_loc,index,ppvObj); } bool SubByIndex (unsigned index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->SubByIndex (m_loc,index,&obj)) && dest.take(obj); } LxResult Root (void **ppvObj) { return m_loc[0]->Root (m_loc,ppvObj); } bool Root (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Root (m_loc,&obj)) && dest.take(obj); } LxResult Context (void **ppvObj) { return m_loc[0]->Context (m_loc,ppvObj); } bool Context (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Context (m_loc,&obj)) && dest.take(obj); } LxResult Reference (void **ppvObj) { return m_loc[0]->Reference (m_loc,ppvObj); } bool Reference (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Reference (m_loc,&obj)) && dest.take(obj); } LxResult IsReferenced (void) { return m_loc[0]->IsReferenced (m_loc); } LxResult Source (void **ppvObj) { return m_loc[0]->Source (m_loc,ppvObj); } bool Source (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Source (m_loc,&obj)) && dest.take(obj); } LxResult SetSource (ILxUnknownID source) { return m_loc[0]->SetSource (m_loc,(ILxUnknownID)source); } LxResult ChannelCount (unsigned *count) const { return m_loc[0]->ChannelCount (m_loc,count); } LxResult ChannelLookup (const char *name, unsigned *index) const { return m_loc[0]->ChannelLookup (m_loc,name,index); } LxResult ChannelName (unsigned index, const char **name) const { return m_loc[0]->ChannelName (m_loc,index,name); } LxResult ChannelType (unsigned index, unsigned *type) { return m_loc[0]->ChannelType (m_loc,index,type); } LxResult ChannelVectorMode (unsigned index, unsigned *mode, unsigned *components) { return m_loc[0]->ChannelVectorMode (m_loc,index,mode,components); } LxResult ChannelStorageType (unsigned index, const char **type) { return m_loc[0]->ChannelStorageType (m_loc,index,type); } LxResult ChannelEvalType (unsigned index, const char **type) { return m_loc[0]->ChannelEvalType (m_loc,index,type); } LxResult ChannelGradient (unsigned index, const char **input, const char **output) { return m_loc[0]->ChannelGradient (m_loc,index,input,output); } LxResult ChannelIntHint (unsigned index, const LXtTextValueHint **hints) const { return m_loc[0]->ChannelIntHint (m_loc,index,hints); } LxResult ChannelPackage (unsigned index, const char **package) { return m_loc[0]->ChannelPackage (m_loc,index,package); } LxResult PackageAdd (const char *package) { return m_loc[0]->PackageAdd (m_loc,package); } LxResult PackageTest (const char *package) const { return m_loc[0]->PackageTest (m_loc,package); } LxResult PackageStartIndex (const char *package, unsigned *index) { return m_loc[0]->PackageStartIndex (m_loc,package,index); } LxResult PackageRemove (const char *package) { return m_loc[0]->PackageRemove (m_loc,package); } LxResult ChannelAdd (int whatever) { return m_loc[0]->ChannelAdd (m_loc,whatever); } const char * GetTag (LXtID4 type) { return m_loc[0]->GetTag (m_loc,type); } LxResult SetTag (LXtID4 type, const char *tag) { return m_loc[0]->SetTag (m_loc,type,tag); } void InvalidateName (void) { m_loc[0]->InvalidateName (m_loc); } LxResult WasLoaded (unsigned test) { return m_loc[0]->WasLoaded (m_loc,test); } }; class CLxLoc_ItemGraph : public CLxLocalize<ILxItemGraphID> { public: void _init() {m_loc=0;} CLxLoc_ItemGraph() {_init();} CLxLoc_ItemGraph(ILxUnknownID obj) {_init();set(obj);} CLxLoc_ItemGraph(const CLxLoc_ItemGraph &other) {_init();set(other.m_loc);} const LXtGUID * guid() const {return &lx::guid_ItemGraph;} LxResult AddLink (ILxUnknownID from, ILxUnknownID to) { return m_loc[0]->AddLink (m_loc,(ILxUnknownID)from,(ILxUnknownID)to); } LxResult SetLink (ILxUnknownID from, int fromIndex, ILxUnknownID to, int toIndex) { return m_loc[0]->SetLink (m_loc,(ILxUnknownID)from,fromIndex,(ILxUnknownID)to,toIndex); } LxResult DeleteLink (ILxUnknownID from, ILxUnknownID to) { return m_loc[0]->DeleteLink (m_loc,(ILxUnknownID)from,(ILxUnknownID)to); } LxResult FwdCount (ILxUnknownID item, unsigned *count) { return m_loc[0]->FwdCount (m_loc,(ILxUnknownID)item,count); } LxResult FwdByIndex (ILxUnknownID item, unsigned index, void **ppvObj) { return m_loc[0]->FwdByIndex (m_loc,(ILxUnknownID)item,index,ppvObj); } bool FwdByIndex (ILxUnknownID item, unsigned index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->FwdByIndex (m_loc,(ILxUnknownID)item,index,&obj)) && dest.take(obj); } LxResult RevCount (ILxUnknownID item, unsigned *count) { return m_loc[0]->RevCount (m_loc,(ILxUnknownID)item,count); } LxResult RevByIndex (ILxUnknownID item, unsigned index, void **ppvObj) { return m_loc[0]->RevByIndex (m_loc,(ILxUnknownID)item,index,ppvObj); } bool RevByIndex (ILxUnknownID item, unsigned index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RevByIndex (m_loc,(ILxUnknownID)item,index,&obj)) && dest.take(obj); } }; class CLxLoc_Scene : public CLxLocalize<ILxSceneID> { public: void _init() {m_loc=0;} CLxLoc_Scene() {_init();} CLxLoc_Scene(ILxUnknownID obj) {_init();set(obj);} CLxLoc_Scene(const CLxLoc_Scene &other) {_init();set(other.m_loc);} const LXtGUID * guid() const {return &lx::guid_Scene;} LXtItemType ItemRootType (void) { return m_loc[0]->ItemRootType (m_loc); } LxResult Filename (const char **filename) { return m_loc[0]->Filename (m_loc,filename); } LxResult FriendlyFilename (unsigned flags, const char **filename) { return m_loc[0]->FriendlyFilename (m_loc,flags,filename); } LxResult FileFormat (const char **format) { return m_loc[0]->FileFormat (m_loc,format); } LxResult Changed (unsigned changed) { return m_loc[0]->Changed (m_loc,changed); } LxResult HasChanged (unsigned int *numChanges) { return m_loc[0]->HasChanged (m_loc,numChanges); } LxResult Parent (void **ppvObj) { return m_loc[0]->Parent (m_loc,ppvObj); } bool Parent (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Parent (m_loc,&obj)) && dest.take(obj); } LxResult SubSceneCount (LXtItemType type, unsigned int *count) { return m_loc[0]->SubSceneCount (m_loc,type,count); } LxResult SubSceneByIndex (LXtItemType type, unsigned int index, void **ppvObj) { return m_loc[0]->SubSceneByIndex (m_loc,type,index,ppvObj); } bool SubSceneByIndex (LXtItemType type, unsigned int index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->SubSceneByIndex (m_loc,type,index,&obj)) && dest.take(obj); } unsigned LoadFlags (void) { return m_loc[0]->LoadFlags (m_loc); } LxResult Channels (const char *name, double time, void **ppvObj) const { return m_loc[0]->Channels (m_loc,name,time,ppvObj); } bool Channels (const char *name, double time, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Channels (m_loc,name,time,&obj)) && dest.take(obj); } LxResult ItemCount (LXtItemType type, unsigned int *count) const { return m_loc[0]->ItemCount (m_loc,type,count); } LxResult ItemByIndex (LXtItemType type, unsigned int index, void **ppvObj) const { return m_loc[0]->ItemByIndex (m_loc,type,index,ppvObj); } bool ItemByIndex (LXtItemType type, unsigned int index, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemByIndex (m_loc,type,index,&obj)) && dest.take(obj); } LxResult ItemLookup (const char *id, void **ppvObj) const { return m_loc[0]->ItemLookup (m_loc,id,ppvObj); } bool ItemLookup (const char *id, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemLookup (m_loc,id,&obj)) && dest.take(obj); } LxResult ItemCountByTypes (const LXtItemType *types, unsigned *count) const { return m_loc[0]->ItemCountByTypes (m_loc,types,count); } LxResult ItemByIndexByTypes (const LXtItemType *types, unsigned index, void **ppvObj) const { return m_loc[0]->ItemByIndexByTypes (m_loc,types,index,ppvObj); } bool ItemByIndexByTypes (const LXtItemType *types, unsigned index, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemByIndexByTypes (m_loc,types,index,&obj)) && dest.take(obj); } LxResult AnyItemOfType (LXtItemType type, void **ppvObj) const { return m_loc[0]->AnyItemOfType (m_loc,type,ppvObj); } bool AnyItemOfType (LXtItemType type, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->AnyItemOfType (m_loc,type,&obj)) && dest.take(obj); } LxResult ItemLocalize (ILxUnknownID item, void **ppvObj) { return m_loc[0]->ItemLocalize (m_loc,(ILxUnknownID)item,ppvObj); } bool ItemLocalize (ILxUnknownID item, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemLocalize (m_loc,(ILxUnknownID)item,&obj)) && dest.take(obj); } LxResult ItemAdd (LXtItemType type, void **ppvObj) { return m_loc[0]->ItemAdd (m_loc,type,ppvObj); } bool ItemAdd (LXtItemType type, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemAdd (m_loc,type,&obj)) && dest.take(obj); } LxResult ItemDuplicate (ILxUnknownID item, void **ppvObj) { return m_loc[0]->ItemDuplicate (m_loc,(ILxUnknownID)item,ppvObj); } bool ItemDuplicate (ILxUnknownID item, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemDuplicate (m_loc,(ILxUnknownID)item,&obj)) && dest.take(obj); } LxResult ItemAddReference (ILxUnknownID item, void **ppvObj) { return m_loc[0]->ItemAddReference (m_loc,(ILxUnknownID)item,ppvObj); } bool ItemAddReference (ILxUnknownID item, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemAddReference (m_loc,(ILxUnknownID)item,&obj)) && dest.take(obj); } LxResult GraphLookup (const char *name, void **ppvObj) const { return m_loc[0]->GraphLookup (m_loc,name,ppvObj); } bool GraphLookup (const char *name, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->GraphLookup (m_loc,name,&obj)) && dest.take(obj); } LxResult GraphCount (int *count) const { return m_loc[0]->GraphCount (m_loc,count); } LxResult GraphByIndex (unsigned index, void **ppvObj) const { return m_loc[0]->GraphByIndex (m_loc,index,ppvObj); } bool GraphByIndex (unsigned index, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->GraphByIndex (m_loc,index,&obj)) && dest.take(obj); } LxResult ItemRemove (ILxUnknownID item) { return m_loc[0]->ItemRemove (m_loc,(ILxUnknownID)item); } LxResult Import (const char *path, ILxUnknownID monitor) { return m_loc[0]->Import (m_loc,path,(ILxUnknownID)monitor); } LxResult EvalModInvalidate (const char *modName) { return m_loc[0]->EvalModInvalidate (m_loc,modName); } LxResult EvalModReset (const char *modName) { return m_loc[0]->EvalModReset (m_loc,modName); } LxResult ItemReplace (ILxUnknownID item, int type, void **ppvObj) { return m_loc[0]->ItemReplace (m_loc,(ILxUnknownID)item,type,ppvObj); } bool ItemReplace (ILxUnknownID item, int type, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemReplace (m_loc,(ILxUnknownID)item,type,&obj)) && dest.take(obj); } LxResult SetupMode (void) { return m_loc[0]->SetupMode (m_loc); } LxResult SetupChannels (void **ppvObj) const { return m_loc[0]->SetupChannels (m_loc,ppvObj); } bool SetupChannels (CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->SetupChannels (m_loc,&obj)) && dest.take(obj); } LxResult ItemLookupIdent (const char *id, void **ppvObj) { return m_loc[0]->ItemLookupIdent (m_loc,id,ppvObj); } bool ItemLookupIdent (const char *id, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemLookupIdent (m_loc,id,&obj)) && dest.take(obj); } LxResult ItemLookupImported (const char *id, void **ppvObj) { return m_loc[0]->ItemLookupImported (m_loc,id,ppvObj); } bool ItemLookupImported (const char *id, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->ItemLookupImported (m_loc,id,&obj)) && dest.take(obj); } LxResult RenderCameraCount (int *count) const { return m_loc[0]->RenderCameraCount (m_loc,count); } LxResult RenderCameraByIndex (int index, void **ppvObj) const { return m_loc[0]->RenderCameraByIndex (m_loc,index,ppvObj); } bool RenderCameraByIndex (int index, CLxLocalizedObject &dest) const { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RenderCameraByIndex (m_loc,index,&obj)) && dest.take(obj); } LxResult RenderCameraIndex (ILxUnknownID eval, int *index) const { return m_loc[0]->RenderCameraIndex (m_loc,(ILxUnknownID)eval,index); } }; class CLxLoc_SceneGraph : public CLxLocalize<ILxSceneGraphID> { public: void _init() {m_loc=0;} CLxLoc_SceneGraph() {_init();} CLxLoc_SceneGraph(ILxUnknownID obj) {_init();set(obj);} CLxLoc_SceneGraph(const CLxLoc_SceneGraph &other) {_init();set(other.m_loc);} const LXtGUID * guid() const {return &lx::guid_SceneGraph;} LxResult Name (const char **name) { return m_loc[0]->Name (m_loc,name); } LxResult Context (void **ppvObj) { return m_loc[0]->Context (m_loc,ppvObj); } bool Context (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Context (m_loc,&obj)) && dest.take(obj); } LxResult RootCount (int *count) { return m_loc[0]->RootCount (m_loc,count); } LxResult RootByIndex (int index, void **ppvObj) { return m_loc[0]->RootByIndex (m_loc,index,ppvObj); } bool RootByIndex (int index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RootByIndex (m_loc,index,&obj)) && dest.take(obj); } LxResult RootFirst (void **ppvObj) { return m_loc[0]->RootFirst (m_loc,ppvObj); } bool RootFirst (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RootFirst (m_loc,&obj)) && dest.take(obj); } LxResult RootNext (void **ppvObj) { return m_loc[0]->RootNext (m_loc,ppvObj); } bool RootNext (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->RootNext (m_loc,&obj)) && dest.take(obj); } LxResult RootSetPos (ILxUnknownID item, int pos) { return m_loc[0]->RootSetPos (m_loc,(ILxUnknownID)item,pos); } LxResult RootRemove (ILxUnknownID item) { return m_loc[0]->RootRemove (m_loc,(ILxUnknownID)item); } }; class CLxLoc_SceneService : public CLxLocalizedService { ILxSceneServiceID m_loc; public: void _init() {m_loc=0;} CLxLoc_SceneService() {_init();set();} ~CLxLoc_SceneService() {} void set() {if(!m_loc)m_loc=reinterpret_cast<ILxSceneServiceID>(lx::GetGlobal(&lx::guid_SceneService));} LxResult ScriptQuery (void **ppvObj) { return m_loc[0]->ScriptQuery (m_loc,ppvObj); } LxResult Root (void **ppvObj) { return m_loc[0]->Root (m_loc,ppvObj); } bool Root (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->Root (m_loc,&obj)) && dest.take(obj); } unsigned ItemTypeCount (void) { return m_loc[0]->ItemTypeCount (m_loc); } LxResult ItemTypeByIndex (unsigned index, LXtItemType *type) { return m_loc[0]->ItemTypeByIndex (m_loc,index,type); } LxResult ItemTypeLookup (const char *name, LXtItemType *type) { return m_loc[0]->ItemTypeLookup (m_loc,name,type); } LxResult ItemTypeName (LXtItemType type, const char **name) { return m_loc[0]->ItemTypeName (m_loc,type,name); } LxResult ItemTypeTest (LXtItemType what, LXtItemType isA) { return m_loc[0]->ItemTypeTest (m_loc,what,isA); } LxResult ItemTypeSuper (LXtItemType type, LXtItemType *super) { return m_loc[0]->ItemTypeSuper (m_loc,type,super); } LxResult ItemTypeCommonChannels (ILxUnknownID item1, ILxUnknownID item2, unsigned *count) { return m_loc[0]->ItemTypeCommonChannels (m_loc,(ILxUnknownID)item1,(ILxUnknownID)item2,count); } LxResult ItemSubTypeCount (LXtItemType type, unsigned int *count) { return m_loc[0]->ItemSubTypeCount (m_loc,type,count); } LxResult ItemSubTypeByIndex (LXtItemType type, unsigned int index, const char **subtype) { return m_loc[0]->ItemSubTypeByIndex (m_loc,type,index,subtype); } LxResult ChannelVectorSize (unsigned int mode, unsigned int *size) { return m_loc[0]->ChannelVectorSize (m_loc,mode,size); } LxResult ChannelVectorTextHints (const LXtTextValueHint **hints) { return m_loc[0]->ChannelVectorTextHints (m_loc,hints); } LxResult CreateScene (void **ppvObj) { return m_loc[0]->CreateScene (m_loc,ppvObj); } bool CreateScene (CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->CreateScene (m_loc,&obj)) && dest.take(obj); } LxResult DestroyScene (ILxUnknownID scene) { return m_loc[0]->DestroyScene (m_loc,(ILxUnknownID)scene); } LxResult SubSceneAdd (ILxUnknownID scene, ILxUnknownID other, unsigned refItems) { return m_loc[0]->SubSceneAdd (m_loc,(ILxUnknownID)scene,(ILxUnknownID)other,refItems); } LxResult SubSceneLoad (ILxUnknownID scene, const char *path, ILxUnknownID monitor, void **ppvObj) { return m_loc[0]->SubSceneLoad (m_loc,(ILxUnknownID)scene,path,(ILxUnknownID)monitor,ppvObj); } bool SubSceneLoad (ILxUnknownID scene, const char *path, ILxUnknownID monitor, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->SubSceneLoad (m_loc,(ILxUnknownID)scene,path,(ILxUnknownID)monitor,&obj)) && dest.take(obj); } LxResult GetMeshInstSourceItem (ILxUnknownID inst, void **ppvObj) { return m_loc[0]->GetMeshInstSourceItem (m_loc,(ILxUnknownID)inst,ppvObj); } bool GetMeshInstSourceItem (ILxUnknownID inst, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->GetMeshInstSourceItem (m_loc,(ILxUnknownID)inst,&obj)) && dest.take(obj); } int MeshInstanceCount (ILxUnknownID mesh) { return m_loc[0]->MeshInstanceCount (m_loc,(ILxUnknownID)mesh); } LxResult MeshInstanceByIndex (ILxUnknownID mesh, int index, void **ppvObj) { return m_loc[0]->MeshInstanceByIndex (m_loc,(ILxUnknownID)mesh,index,ppvObj); } bool MeshInstanceByIndex (ILxUnknownID mesh, int index, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->MeshInstanceByIndex (m_loc,(ILxUnknownID)mesh,index,&obj)) && dest.take(obj); } LxResult LoadImage (ILxUnknownID scene, const char *name, unsigned *flags, ILxUnknownID monitor, void **ppvObj) { return m_loc[0]->LoadImage (m_loc,(ILxUnknownID)scene,name,flags,(ILxUnknownID)monitor,ppvObj); } bool LoadImage (ILxUnknownID scene, const char *name, unsigned *flags, ILxUnknownID monitor, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->LoadImage (m_loc,(ILxUnknownID)scene,name,flags,(ILxUnknownID)monitor,&obj)) && dest.take(obj); } LxResult GetReplicatorEnumerator (ILxUnknownID replicatorItem, void **ppvObj) { return m_loc[0]->GetReplicatorEnumerator (m_loc,(ILxUnknownID)replicatorItem,ppvObj); } bool GetReplicatorEnumerator (ILxUnknownID replicatorItem, CLxLocalizedObject &dest) { LXtObjectID obj; dest.clear(); return LXx_OK(m_loc[0]->GetReplicatorEnumerator (m_loc,(ILxUnknownID)replicatorItem,&obj)) && dest.take(obj); } LxResult ItemTypeGetTag (LXtItemType type, const char *tag, unsigned super, const char **value) { return m_loc[0]->ItemTypeGetTag (m_loc,type,tag,super,value); } }; #endif
a97e50c366dd235ba78b6ce96422c82bf1bd75c1
debc1f82c5bb479eb09c116647036f8ff43058b1
/ParameterAlpha.cpp
34e6b3f54b77481da1cf077bb285d533766a8088
[]
no_license
JiaChangjiang/Object-Ortiented_Monte_Carlo_Control_Variate
38674898a15ba5b9261c6257a5f9057fe11f1f00
ad8f27b0f82988430ef1ecc08260c29cc8b56398
refs/heads/master
2020-07-07T05:24:15.947373
2019-08-20T00:05:12
2019-08-20T00:05:12
203,263,764
1
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
ParameterAlpha.cpp
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // ParameterAlpha.cpp //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #include "ParameterAlpha.h" //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // constructor //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ParameterAlpha::ParameterAlpha() { name = "Alpha"; } //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // end //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1fdc6219f5a44bb3948518763c0507f79d32dd56
7d100f8706311994172975f6e86b614d4bfcf4b5
/gstd/src/Reader.h
d8234fb3545531f47f97c63f097e361171d12625
[ "MIT" ]
permissive
georgephilipp/cppgstd_legacy
2d502a481b52f57edcd46b40908139ac31ad57e1
e130860da7700aae42b915bc36a7efa4cae06d56
refs/heads/master
2020-03-29T14:28:26.203999
2018-09-29T23:19:33
2018-09-29T23:19:33
150,019,516
0
0
null
null
null
null
UTF-8
C++
false
false
2,577
h
Reader.h
/* * File: Reader.h * Author: gschoenh * * Created on November 22, 2013, 6:58 PM */ #include "stdafx.h" #include"standard.h" #include"ex.h" #include"Base.h" #include<fstream> #include "Parser.h" #ifndef READER_H #define READER_H namespace msii810161816 { namespace gstd { class MSII810161816_GSTD_API Reader : virtual public Base { public: Reader(); ~Reader(); //inputs std::string location; //options char delimiter; //actions void open(); void close(); bool fileIsOpen(); gstd::trial<std::string> line(int index = -1); template<typename type> gstd::trial<std::vector<type> > row(int index = -1) { gstd::trial<std::vector<type> > res; gstd::trial<std::string> l = line(index); if(!l.success) { res.success = false; return res; } res.success = true; res.result = gstd::Parser::vector<type>(l.result, delimiter); return res; } static int numRows(std::string location); static std::vector<std::string> ls(std::string location); template<typename type> static std::vector<std::vector<type> > rs(std::string location, char delimiter) { Reader reader; reader.location = location; reader.delimiter = delimiter; reader.open(); std::vector<std::vector<type> > res; while (1) { gstd::trial<std::vector<type> > next = reader.row<type>(); if (!next.success) break; else res.push_back(next.result); } return res; } protected: std::ifstream file; int position; private: bool openInner(); //Base Package public: virtual gstd::TypeName getTypeName(); virtual void setInputs(); virtual bool test(); virtual std::string toString(); private: std::string getTestFileName(); //needed for the test }; } } namespace msii810161816 { namespace gstd { template<> struct TypeNameGetter<Reader> { static TypeName get() { TypeName t; t.name = "gstd::Reader"; return t; } }; } } #endif /* READER_H */
ae2d3ba7fd46fba3871931fd0d36e71e27c3e26b
0a5c1807ec80fb3f5baf02b911e76ec2e0bcb19b
/main.cpp
89e5e6326bd27ad96dfc04c0329877dc6c262461
[]
no_license
Sa2x/grafika_hf_2019_osz_1
6cb6c8e32eaf1bf71cd27a108e6af1c9e0761f0f
03774b16c8075c7ddc2e74d27943534d2ec4fc5e
refs/heads/master
2020-05-04T13:07:39.234211
2019-04-02T15:40:24
2019-04-02T15:40:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,798
cpp
main.cpp
//============================================================================================= // Mintaprogram: Zöld háromszög. Ervenyes 2018. osztol. // // A beadott program csak ebben a fajlban lehet, a fajl 1 byte-os ASCII karaktereket tartalmazhat, BOM kihuzando. // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni a printf-et kiveve // - Mashonnan atvett programresszleteket forrasmegjeloles nelkul felhasznalni es // - felesleges programsorokat a beadott programban hagyni!!!!!!! // - felesleges kommenteket a beadott programba irni a forrasmegjelolest kommentjeit kiveve // --------------------------------------------------------------------------------------------- // A feladatot ANSI C++ nyelvu forditoprogrammal ellenorizzuk, a Visual Studio-hoz kepesti elteresekrol // es a leggyakoribb hibakrol (pl. ideiglenes objektumot nem lehet referencia tipusnak ertekul adni) // a hazibeado portal ad egy osszefoglalot. // --------------------------------------------------------------------------------------------- // A feladatmegoldasokban csak olyan OpenGL fuggvenyek hasznalhatok, amelyek az oran a feladatkiadasig elhangzottak // A keretben nem szereplo GLUT fuggvenyek tiltottak. // // NYILATKOZAT // --------------------------------------------------------------------------------------------- // Nev : // Neptun : // --------------------------------------------------------------------------------------------- // ezennel kijelentem, hogy a feladatot magam keszitettem, es ha barmilyen segitseget igenybe vettem vagy // mas szellemi termeket felhasznaltam, akkor a forrast es az atvett reszt kommentekben egyertelmuen jeloltem. // A forrasmegjeloles kotelme vonatkozik az eloadas foliakat es a targy oktatoi, illetve a // grafhazi doktor tanacsait kiveve barmilyen csatornan (szoban, irasban, Interneten, stb.) erkezo minden egyeb // informaciora (keplet, program, algoritmus, stb.). Kijelentem, hogy a forrasmegjelolessel atvett reszeket is ertem, // azok helyessegere matematikai bizonyitast tudok adni. Tisztaban vagyok azzal, hogy az atvett reszek nem szamitanak // a sajat kontribucioba, igy a feladat elfogadasarol a tobbi resz mennyisege es minosege alapjan szuletik dontes. // Tudomasul veszem, hogy a forrasmegjeloles kotelmenek megsertese eseten a hazifeladatra adhato pontokat // negativ elojellel szamoljak el es ezzel parhuzamosan eljaras is indul velem szemben. //============================================================================================= #include <algorithm> #include <complex> #include "framework.h" // vertex shader in GLSL: It is a Raw string (C++11) since it contains new line characters const char * const vertexSource = R"( #version 330 // Shader 3.3 precision highp float; // normal floats, makes no difference on desktop computers uniform mat4 MVP; // uniform variable, the Model-View-Projection transformation matrix layout(location = 0) in vec2 vertexPos; // Varying input: vp = vertex position is expected in attrib array 0 layout(location = 1) in vec3 vertexColor; out vec3 color; void main() { gl_Position = vec4(vertexPos.x, vertexPos.y, 0, 1) * MVP; // transform vp from modeling space to normalized device space color = vertexColor; } )"; const char * backgroundVertexShader = R"( #version 330 precision highp float; layout(location = 0) in vec2 vertexPosition; // Attrib Array 0 layout(location = 1) in vec2 vertexUV; // Attrib Array 1 out vec2 texCoord; // output attribute void main() { texCoord = vertexUV; // copy texture coordinates gl_Position = vec4(vertexPosition.x, vertexPosition.y, 0, 1); // transform to clipping space } )"; // fragment shader in GLSL const char * const fragmentSource = R"( #version 330 // Shader 3.3 precision highp float; // normal floats, makes no difference on desktop computers in vec3 color; out vec4 outColor; // computed color of the current pixel void main() { outColor = vec4(color, 1); // computed color is the color of the primitive } )"; const char * backgroundFragmentShader = R"( #version 330 precision highp float; uniform sampler2D textureUnit; in vec2 texCoord; // variable input: interpolated texture coordinates out vec4 fragmentColor; // output that goes to the raster memory as told by glBindFragDataLocation void main() { fragmentColor = texture(textureUnit, texCoord); } )"; GPUProgram gpuProgram; // vertex and fragment shaders GPUProgram backgroundProgram; class Camera2D { vec2 wCenter; // center in world coordinates vec2 wSize; // width and height in world coordinates public: Camera2D() : wCenter(0, 0), wSize(2, 2) { } mat4 V() { return TranslateMatrix(-wCenter); } mat4 P() { return ScaleMatrix(vec2(2 / wSize.x, 2 / wSize.y)); } mat4 Vinv() { return TranslateMatrix(wCenter); } mat4 Pinv() { return ScaleMatrix(vec2(wSize.x / 2, wSize.y / 2)); } void Zoom(float s) { wSize = wSize * s; } void Pan(vec2 t) { wCenter = wCenter + t; } } camera; class Object { protected: const mat4 M() const { mat4 scaleM( scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); mat4 rotateZM( cosf(rotate.z), sinf(rotate.z), 0, 0, -sinf(rotate.z), cosf(rotate.z), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) ; mat4 translateM( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x, position.y, 0, 1 ); return scaleM * rotateZM * translateM; } const mat4 Minv() const { return mat4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x * (-1), position.y * (-1), 0, 1 ); } const vec2 vecTransform(const vec2 & vec) const { vec4 wVertex = vec4(vec.x, vec.y, 0, 1) * camera.Pinv() * camera.Vinv(); // * Minv(); return vec2(wVertex.x, wVertex.y); } public: vec2 scale = vec2(1, 1); vec2 position; vec3 rotate; virtual void Draw() const { mat4 MVPTransform = M() * camera.V() * camera.P(); MVPTransform.SetUniform(gpuProgram.getId(), "MVP"); } }; class TexturedQuad { GLuint vao, vbo[2]; vec2 vertices[4], uvs[4]; Texture * pTexture; unsigned int width = 128, height = 128; public: TexturedQuad() { vertices[0] = vec2(-1, -1); uvs[0] = vec2(0, 0); vertices[1] = vec2(1, -1); uvs[1] = vec2(1, 0); vertices[2] = vec2(1, 1); uvs[2] = vec2(1, 1); vertices[3] = vec2(-1, 1); uvs[3] = vec2(0, 1); } void Init() { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(2, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); std::vector<vec4> image(width * height); for (unsigned int y = 0; y < height; y++) { for (unsigned int x = 0; x < width; x++) { image[y * width + x] = vec4(Mandelbrot(x, y), 0, 0, 1); } } pTexture = new Texture(width, height, image); } float Mandelbrot (unsigned int x, unsigned int y) { std::complex<float> point((float)x / width - 1.5f, (float)y / height - 0.5f); std::complex<float> z(0, 0); unsigned int nb_iter = 0; while (abs (z) < 2 && nb_iter <= 34) { z = z * z + point; nb_iter++; } if (nb_iter < 34) return 1.0f; return 0.0f; } void Draw() { glBindVertexArray(vao); pTexture->SetUniform(backgroundProgram.getId(), "textureUnit"); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); // draw two triangles forming a quad } }; class VertexData { public: vec2 pos; vec3 color; explicit VertexData(vec2 pos = vec2(), vec3 color = vec3()) : pos{pos}, color{color} {}; }; class KochanekBartelsCurve : public Object { GLuint vao, vbo; std::vector<vec2> controlPoints; std::vector<vec2> vertices; std::vector<VertexData> vertexData; const unsigned int MIN_CONTROL_POINTS = 4; vec2 Hermite(vec2 p0, vec2 v0, float t0, vec2 p1, vec2 v1, float t1, float t) { vec2 a0 = p0; vec2 a1 = v0; vec2 a2 = ((p1 - p0) * 3) - (v1 + v0 * 2); vec2 a3 = ((p0 - p1) * 2) + (v1 + v0); // printf("t: %f, t0: %f t1: %f\n", t, t0, t1); return a3 * pow(t - t0, 3) + a2 * pow(t - t0, 2) + a1 * (t - t0) + a0; } vec2 r(float t) { for(unsigned int i = 1; i < controlPoints.size() - 2; i++) { if( (float)i <= t && t <= (float)(i+1) ) { vec2 v0 = ((controlPoints[i + 1] - controlPoints[i]) + (controlPoints[i] - controlPoints[i-1])) * 0.5f; vec2 v1 = ((controlPoints[i + 2] - controlPoints[i + 1]) + (controlPoints[i + 1] - controlPoints[i])) * 0.5f; return Hermite( controlPoints[i], v0, (float)i, controlPoints[i + 1], v1, (float)(i + 1), t ) ; } } return {}; } void generateCurve() { if( controlPoints.size() < MIN_CONTROL_POINTS ) return; vertices.clear(); vertexData.clear(); for(float t = 1.0f; t < controlPoints.size() - 2; t += 0.05f) { addVertex(r(t), vec3(1.0f, 0.0f, 0.0f)); } loadVbo(); } void addVertex(const vec2 & v, const vec3 & color) { vertices.emplace_back(v); vertexData.emplace_back(VertexData(vecTransform(v), color)); } void loadVbo() { glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData) * vertexData.size(), &vertexData[0], GL_DYNAMIC_DRAW); } static bool comparePos(vec2 v1, vec2 v2) { return (v1.x < v2.x); } public: void Init() { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), reinterpret_cast<void*>(sizeof(vec2))); } public: void addControlPoint(float x, float y) { controlPoints.emplace_back(x, y); std::sort(controlPoints.begin(), controlPoints.end(), comparePos); generateCurve(); } void Draw() const override { if( controlPoints.size() < MIN_CONTROL_POINTS ) return; Object::Draw(); glBindVertexArray(vao); glDrawArrays(GL_LINE_STRIP, 0, static_cast<GLsizei>(vertexData.size())); } unsigned long getControlPointsSize() const { return controlPoints.size(); } const std::vector<vec2> & getVertices() const { return vertices; } }; class BicycleRoadGround : Object { GLuint vao, vbo; std::vector<VertexData> vertices; void generate(std::vector<vec2> const & verts) { vertices.clear(); for(unsigned long i = 0; i < verts.size() - 1; i++) { addVertices(verts[i]); addVertices(vec2(verts[i].x, -1)); addVertices(verts[i + 1]); addVertices(vec2(verts[i].x, -1)); addVertices(verts[i + 1]); addVertices(vec2(verts[i + 1].x, -1)); } loadVbo(); } void addVertices(const vec2 & pos) { vertices.emplace_back(VertexData(vecTransform(pos), vec3(0, 1, 0))); } void loadVbo() { glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData) * vertices.size(), &vertices[0], GL_DYNAMIC_DRAW); } public: void Init() { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), reinterpret_cast<void*>(sizeof(vec2))); } void Draw() const override { if( vertices.empty() ) return; Object::Draw(); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertices.size())); } void onControlPointAdded(unsigned long nCps, std::vector<vec2> const & verts) { if( nCps < 4 ) return; generate(verts); } }; class Cyclist : Object { GLuint vao[2], vbo[2]; std::vector<VertexData> staticVertices; std::vector<VertexData> dynamicVertices; const float headRadius = 0.03f; const float bodyLength = 0.05f; const float bicycleRadius = 0.06f; const vec3 headColor = vec3(0, 0, 1); const vec3 bodyColor = vec3(0, 1, 1); const vec3 wheelColor = vec3(1, 0, 1); vec2 bicycleCenter; float time = 0.0f; unsigned int stepOnRoad = 0; bool dirOnRoad = true; void initStaticVao() { glBindVertexArray(vao[0]); glGenBuffers(1, &vbo[0]); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), reinterpret_cast<void*>(sizeof(vec2))); loadStaticBuffers(); } void initDynamicVao() { glBindVertexArray(vao[1]); glGenBuffers(1, &vbo[1]); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), reinterpret_cast<void*>(sizeof(vec2))); loadDynamicBuffers(); } void loadStaticBuffers() { loadHead(); loadBody(); loadWheel(); loadSpoke(); loadStaticVbo(); } void loadDynamicBuffers() { dynamicVertices.clear(); loadFoot(); loadDynamicVbo(); } void addStaticVertex(const vec2 & v, const vec3 & color) { staticVertices.emplace_back(VertexData(vecTransform(v), color)); } void addDynamicVertex(const vec2 & v, const vec3 & color) { dynamicVertices.emplace_back(VertexData(vecTransform(v), color)); } void loadHead() { for(unsigned int i = 0; i < 360; i++) { vec2 p = vec2( sinf(i * M_PI / 180.0f), cosf(i * M_PI / 180.0f) ) * headRadius; addStaticVertex(p, headColor); } } void loadBody() { addStaticVertex(vec2(0, headRadius * (-1)), bodyColor); addStaticVertex(vec2(0, (headRadius + bodyLength) * (-1)), bodyColor); } void loadWheel() { for(unsigned int i = 0; i < 360; i++) { vec2 p = vec2( sinf(i * M_PI / 180.0f), cosf(i * M_PI / 180.0f) ) * bicycleRadius; addStaticVertex(p + bicycleCenter, wheelColor); } } void loadSpoke() { for(unsigned int i = 0; i < 360; i += 36) { vec2 p = vec2( sinf(i * M_PI / 180.0f + time), cosf(i * M_PI / 180.0f + time) ) * bicycleRadius; addStaticVertex(vec2(), wheelColor); addStaticVertex(p, wheelColor); } } void loadFoot() { vec2 hipPos = vec2(0, (headRadius + bodyLength) *(-1)); vec2 kneePos = hipPos + vec2(0.08f, sin(time) * 0.05f); vec2 wheelRot = vec2( sinf(M_PI / 180.0f + time), cosf(M_PI / 180.0f + time) ) * bicycleRadius; vec2 wheelPos = vec2(wheelRot + bicycleCenter); addDynamicVertex(hipPos, bodyColor); addDynamicVertex(kneePos, bodyColor); addDynamicVertex(kneePos, bodyColor); addDynamicVertex(wheelPos, bodyColor); } void loadStaticVbo() { glBindVertexArray(vao[0]); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData) * staticVertices.size(), &staticVertices[0], GL_STATIC_DRAW); } void loadDynamicVbo() { glBindVertexArray(vao[1]); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData) * dynamicVertices.size(), &dynamicVertices[0], GL_DYNAMIC_DRAW); } mat4 wheelM() const { mat4 trans = mat4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, bicycleCenter.y, 0, 1 ); mat4 rotate = mat4( cos(time), sin(time), 0, 0, sin(time) * (-1), cos(time), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return rotate * trans * M(); } public: Cyclist() { bicycleCenter = vec2(0, (headRadius + bodyLength + bicycleRadius) * (-1)); } void Init() { glGenVertexArrays(2, &vao[0]); initStaticVao(); initDynamicVao(); } void Animate(float dt, const KochanekBartelsCurve & road) { time = dt; unsigned long size = road.getVertices().size(); position = road.getVertices()[stepOnRoad] - bicycleCenter + vec2(0, bicycleRadius) ; if( dirOnRoad ) { stepOnRoad++; if( stepOnRoad == size - 1 ) { dirOnRoad = false; } } else { stepOnRoad--; if( stepOnRoad == 0 ) { dirOnRoad = true; } } loadDynamicBuffers(); } void Draw() const override { Object::Draw(); glBindVertexArray(vao[0]); glDrawArrays(GL_LINE_LOOP, 0, 360); glDrawArrays(GL_LINE_STRIP, 360, 2); // it should be GL_LINES. wtf? glDrawArrays(GL_LINE_LOOP, 362, 360); mat4 MVPTransform = wheelM() * camera.V() * camera.P(); MVPTransform.SetUniform(gpuProgram.getId(), "MVP"); glDrawArrays(GL_LINES, 722, 360); Object::Draw(); glBindVertexArray(vao[1]); glDrawArrays(GL_LINES, 0, 4); } }; TexturedQuad background; KochanekBartelsCurve bicycleRoad; BicycleRoadGround bicycleRoadGround; Cyclist cyclist; // Initialization, create an OpenGL context void onInitialization() { glViewport(0, 0, windowWidth, windowHeight); background.Init(); bicycleRoad.Init(); bicycleRoadGround.Init(); cyclist.Init(); for(float x = -1.5f; x < 1.5f; x += 0.1f) { bicycleRoad.addControlPoint(x, sin(x * 10) * 0.1f - 0.3f); } bicycleRoadGround.onControlPointAdded(bicycleRoad.getControlPointsSize(), bicycleRoad.getVertices()); // create program for the GPU gpuProgram.Create(vertexSource, fragmentSource, "outColor"); backgroundProgram.Create(backgroundVertexShader, backgroundFragmentShader, "fragmentColor"); } // Window has become invalid: Redraw void onDisplay() { glClearColor(0, 0, 0, 0); // background color glClear(GL_COLOR_BUFFER_BIT); // clear frame buffer backgroundProgram.Use(); background.Draw(); gpuProgram.Use(); bicycleRoad.Draw(); bicycleRoadGround.Draw(); cyclist.Draw(); glutSwapBuffers(); // exchange buffers for double buffering } // Key of ASCII code pressed void onKeyboard(unsigned char key, int pX, int pY) { switch(key) { case 's': camera.Pan(vec2(-1, 0)); break; case 'd': camera.Pan(vec2(+1, 0)); break; case 'e': camera.Pan(vec2( 0, 1)); break; case 'x': camera.Pan(vec2( 0,-1)); break; case 'z': camera.Zoom(0.9f); break; case 'Z': camera.Zoom(1.1f); break; default: break; } } // Key of ASCII code released void onKeyboardUp(unsigned char key, int pX, int pY) { } // Move mouse with key pressed void onMouseMotion(int pX, int pY) { // pX, pY are the pixel coordinates of the cursor in the coordinate system of the operation system // Convert to normalized device space //float cX = 2.0f * pX / windowWidth - 1; // flip y axis //float cY = 1.0f - 2.0f * pY / windowHeight; //printf("Mouse moved to (%3.2f, %3.2f)\n", cX, cY); } // Mouse click event void onMouse(int button, int state, int pX, int pY) { // pX, pY are the pixel coordinates of the cursor in the coordinate system of the operation system // Convert to normalized device space float cX = 2.0f * pX / windowWidth - 1; // flip y axis float cY = 1.0f - 2.0f * pY / windowHeight; if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) { // printf("cX: %f, cY: %f\n", cX, cY) ; bicycleRoad.addControlPoint(cX, cY); bicycleRoadGround.onControlPointAdded(bicycleRoad.getControlPointsSize(), bicycleRoad.getVertices()); glutPostRedisplay(); } /* char * buttonStat; switch (state) { case GLUT_DOWN: buttonStat = "pressed"; break; case GLUT_UP: buttonStat = "released"; break; } switch (button) { case GLUT_LEFT_BUTTON: printf("Left button %s at (%3.2f, %3.2f)\n", buttonStat, cX, cY); break; case GLUT_MIDDLE_BUTTON: printf("Middle button %s at (%3.2f, %3.2f)\n", buttonStat, cX, cY); break; case GLUT_RIGHT_BUTTON: printf("Right button %s at (%3.2f, %3.2f)\n", buttonStat, cX, cY); break; } */ } // Idle event indicating that some time elapsed: do animation here void onIdle() { // static float oldTime = 0.0f; float time = glutGet(GLUT_ELAPSED_TIME) / 1000.f; // elapsed time since the start of the program // float dt = time - oldTime; // oldTime = time; cyclist.Animate(time, bicycleRoad); glutPostRedisplay(); }
4696c97279145f3d9702d457222fdb1badf6f247
f7822dd5e998d12f96e19b3d7d091130a8a5c766
/GameEngine/Core/Utility.cpp
25f6ca1d3d45275daa508102cf4644bba8a853fc
[ "MIT" ]
permissive
lulufa390/ElfGE
0b683154c8bcbc4e5c1309dc9953b67d0f69c3ea
9689ca3d890bfc538f74d449a9ecde8c7aa02d7b
refs/heads/master
2020-04-09T05:03:34.597404
2018-09-03T05:23:54
2018-09-03T05:23:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
Utility.cpp
// // Created by 张程易 on 29/10/2017. // #define STB_IMAGE_IMPLEMENTATION #include "Utility.h" int Utility::SCREEN_WIDTH = 1024; int Utility::SCREEN_HEIGHT = 768; double Utility::MOUSE_X = 0.0; double Utility::MOUSE_Y = 0.0; double Utility::deltaTime = 0.0; GLFWwindow *Utility::window = nullptr; std::string Utility::WINDOW_NAME = "ElfGameEngine"; std::string Utility::RESOURCE_PREFIX = "../Resources/"; const char *Utility::getTextFromFile(const char *filePath) { FILE *fp = fopen(filePath, "r"); if (fp == nullptr) return nullptr; fseek(fp, 0L, SEEK_END); long flen = ftell(fp); char *result = (char *) malloc((size_t) flen); fseek(fp, 0L, SEEK_SET); char *now = result; int c; while ((c = fgetc(fp)) != EOF) *now++ = (char) c; *now = 0; return result; }
6a42c3f3fc15833e60d11539402080ef71d9c075
b42d16c0424c4710d7bb19e58cc52580462183a1
/ComIOP/Wrapper/ProxyServer/Da/COpcUaDaProxyEnumItem.cpp
b79e4d076948b65c3106ba9fae58f5a3948183e5
[]
no_license
OPCFoundation/UA-.NET-Legacy
9bbdd6f031a91783f797c0f15ab9daf39df465ab
b4b4d91a9244e181e9f60f1654c830d469d8083a
refs/heads/master
2023-08-16T00:57:29.410771
2022-07-11T13:18:52
2022-07-11T13:18:52
42,255,070
119
160
null
2022-11-24T13:25:45
2015-09-10T16:01:14
C#
UTF-8
C++
false
false
5,878
cpp
COpcUaDaProxyEnumItem.cpp
/* ======================================================================== * Copyright (c) 2005-2017 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ #include "StdAfx.h" #include "COpcUaDaProxyEnumItem.h" #include "COpcUaProxyUtils.h" using namespace System; /// <summary> /// Dumps the current state. /// </summary> static void TraceState(String^ context, ... array<Object^>^ args) { #ifdef TRACESTATE COpcUaProxyUtils::TraceState("COpcUaDaProxyEnumItem", context, args); #endif } //============================================================================ // COpcUaDaProxyEnumItem COpcUaDaProxyEnumItem::COpcUaDaProxyEnumItem() { TraceState("COpcUaDaProxyEnumItem"); m_uIndex = 0; m_uCount = 0; m_pItems = NULL; } // Constructor COpcUaDaProxyEnumItem::COpcUaDaProxyEnumItem(UINT uCount, OPCITEMATTRIBUTES* pItems) { TraceState("COpcUaDaProxyEnumItem"); m_uIndex = 0; m_uCount = uCount; m_pItems = pItems; } // Destructor COpcUaDaProxyEnumItem::~COpcUaDaProxyEnumItem() { TraceState("~COpcUaDaProxyEnumItem"); COpcLock cLock(*this); for (UINT ii = 0; ii < m_uCount; ii++) { Clear(m_pItems[ii]); } OpcFree(m_pItems); } // Init void COpcUaDaProxyEnumItem::Init(OPCITEMATTRIBUTES& cAttributes) { memset(&cAttributes, 0, sizeof(OPCITEMATTRIBUTES)); } // Clear void COpcUaDaProxyEnumItem::Clear(OPCITEMATTRIBUTES& cAttributes) { OpcFree(cAttributes.szAccessPath); OpcFree(cAttributes.szItemID); OpcFree(cAttributes.pBlob); OpcVariantClear(&cAttributes.vEUInfo); } // Copy void COpcUaDaProxyEnumItem::Copy(OPCITEMATTRIBUTES& cDst, OPCITEMATTRIBUTES& cSrc) { cDst.szAccessPath = OpcStrDup(cSrc.szAccessPath); cDst.szItemID = OpcStrDup(cSrc.szItemID); cDst.bActive = cSrc.bActive; cDst.hClient = cSrc.hClient; cDst.hServer = cSrc.hServer; cDst.dwAccessRights = cSrc.dwAccessRights; cDst.dwBlobSize = cSrc.dwBlobSize; if (cSrc.dwBlobSize > 0) { cDst.pBlob = (BYTE*)OpcAlloc(cSrc.dwBlobSize); memcpy(cDst.pBlob, cSrc.pBlob, cSrc.dwBlobSize); } cDst.vtRequestedDataType = cSrc.vtRequestedDataType; cDst.vtCanonicalDataType = cSrc.vtCanonicalDataType; cDst.dwEUType = cSrc.dwEUType; OpcVariantCopy(&cDst.vEUInfo, &cSrc.vEUInfo); } //============================================================================ // IEnumOPCItemAttributes // Next HRESULT COpcUaDaProxyEnumItem::Next( ULONG celt, OPCITEMATTRIBUTES** ppItemArray, ULONG* pceltFetched ) { TraceState("Next"); COpcLock cLock(*this); // check for invalid arguments. if (ppItemArray == NULL || pceltFetched == NULL) { return E_INVALIDARG; } *pceltFetched = 0; // all items already returned. if (m_uIndex >= m_uCount) { return S_FALSE; } // copy items. *ppItemArray = (OPCITEMATTRIBUTES*)OpcArrayAlloc(OPCITEMATTRIBUTES, celt); memset(*ppItemArray, 0, celt*sizeof(OPCITEMATTRIBUTES)); UINT ii = 0; for (ii = m_uIndex; ii < m_uCount && *pceltFetched < celt; ii++) { Copy((*ppItemArray)[*pceltFetched], m_pItems[ii]); (*pceltFetched)++; } // no enough strings left. if (*pceltFetched < celt) { m_uIndex = m_uCount; return S_FALSE; } m_uIndex = ii; return S_OK; } // Skip HRESULT COpcUaDaProxyEnumItem::Skip(ULONG celt) { TraceState("Skip"); COpcLock cLock(*this); if (m_uIndex + celt > m_uCount) { m_uIndex = m_uCount; return S_FALSE; } m_uIndex += celt; return S_OK; } // Reset HRESULT COpcUaDaProxyEnumItem::Reset() { TraceState("Reset"); COpcLock cLock(*this); m_uIndex = 0; return S_OK; } // Clone HRESULT COpcUaDaProxyEnumItem::Clone(IEnumOPCItemAttributes** ppEnum) { TraceState("Clone"); COpcLock cLock(*this); // check for invalid arguments. if (ppEnum == NULL) { return E_INVALIDARG; } // allocate enumerator. COpcUaDaProxyEnumItem* pEnum = new COpcUaDaProxyEnumItem(); if (m_uCount > 0) { // copy items. OPCITEMATTRIBUTES* pItems = OpcArrayAlloc(OPCITEMATTRIBUTES, m_uCount); for (UINT ii = 0; ii < m_uCount; ii++) { Copy(pItems[ii], m_pItems[ii]); } // set new enumerator state. pEnum->m_pItems = pItems; pEnum->m_uCount = m_uCount; pEnum->m_uIndex = m_uIndex; } // query for interface. HRESULT hResult = pEnum->QueryInterface(IID_IEnumOPCItemAttributes, (void**)ppEnum); // release local reference. pEnum->Release(); return hResult; }
e095d3573b8c2c69d020480cce2b37e3d52819d0
5f7808cc98ee307eca3749c28bdbf66de12d42cb
/moteur.cpp
13b273c38effc1fdc20f69704b835d16a18ab25c
[]
no_license
LeVirus/Bomberman
c8782744cdc2b09e86dda7105744eca8626d67f0
8d721a8bdaafa61f6f5762300a5a2bd91a009be0
refs/heads/master
2021-01-13T09:17:29.782475
2019-05-30T08:41:20
2019-05-30T08:41:20
72,005,017
0
0
null
null
null
null
UTF-8
C++
false
false
16,374
cpp
moteur.cpp
#include "moteur.hpp" #include "tilemap.hpp" #include "NetworkDataUtils.hpp" #include "networkserialstruct.hpp" #include "vector2D.hpp" #include "ECSconstantes.hpp" #include "moveablebombermancomponent.hpp" #include "constants.hpp" #include "componentmanager.hpp" #include "inputbombermancomponent.hpp" #include "tilemapbombermancomponent.hpp" #include "tilemapsystem.hpp" #include "inputbombermansystem.hpp" #include "collrectboxcomponent.hpp" #include "flagcomponent.hpp" #include "playerconfigbombermancomponent.hpp" #include "networkcomponent.hpp" #include "jeu.hpp" #include "socketsystem.hpp" #include "displaysystem.hpp" #include "positioncomponent.hpp" #include "timerbombermancomponent.hpp" #include <SFML/Graphics.hpp> #include <bitset> #include <cassert> #include <SFML/System/Clock.hpp> Moteur::Moteur(const Jeu &jeu): mGestECS(*this), mPtrJeu(jeu) { mMoteurGraphique.linkMainEngine(this); } const Jeu &Moteur::getJeu() const { return mPtrJeu; } void Moteur::lancerBoucle() { mMoteurGraphique.initialiserFenetre(); do { mGestECS.getECSEngine()->execIteration(); getInput(); mMoteurGraphique.raffraichirEcran(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { mLetMeOut = true; break; } if(Niveau::getNumCurrentNumberPlayer() <= 1) { mGestECS.getECSEngine()->RmAllEntity(); break; } }while(true); } void Moteur::getInput() { InputBombermanSystem * ss = mGestECS.getECSSystemManager() -> searchSystemByType< InputBombermanSystem > ( INPUT_BOMBER_SYSTEM ); assert(ss && "ss null"); const std::vector<uint32_t> &vectNumEntitySystem = mGestECS.getECSSystemManager() -> searchSystemByType< InputBombermanSystem > ( INPUT_BOMBER_SYSTEM )->getVectNumEntity(); for( uint32_t i = 0 ; i < vectNumEntitySystem.size() ; ++i ) { InputBombermanComponent *ic = mGestECS.getECSComponentManager() -> searchComponentByType< InputBombermanComponent >( vectNumEntitySystem[i], INPUT_BOMBER_COMPONENT ); if(! ic)continue; //default INPUT_PLAYER_A sf::Keyboard::Key up = sf::Keyboard::Z, down = sf::Keyboard::S, left = sf::Keyboard::Q, right = sf::Keyboard::D, launchBomb = sf::Keyboard::Space; switch(ic->mNumInput) { case INPUT_PLAYER_A: break; case INPUT_PLAYER_B: up = sf::Keyboard::Up; down = sf::Keyboard::Down; left = sf::Keyboard::Left; right = sf::Keyboard::Right; launchBomb = sf::Keyboard::RControl; break; case INPUT_PLAYER_C: up = sf::Keyboard::Numpad8; down = sf::Keyboard::Numpad5; left = sf::Keyboard::Numpad4; right = sf::Keyboard::Numpad6; launchBomb = sf::Keyboard::Numpad0; break; case INPUT_PLAYER_D: up = sf::Keyboard::O; down = sf::Keyboard::L; left = sf::Keyboard::K; right = sf::Keyboard::M; launchBomb = sf::Keyboard::P; break; } if(sf::Keyboard::isKeyPressed(up))ic->mBitsetInput[MOVE_UP] = true; if(sf::Keyboard::isKeyPressed(down))ic->mBitsetInput[MOVE_DOWN] = true; if(sf::Keyboard::isKeyPressed(left))ic->mBitsetInput[MOVE_LEFT] = true; if(sf::Keyboard::isKeyPressed(right))ic->mBitsetInput[MOVE_RIGHT] = true; if(sf::Keyboard::isKeyPressed(launchBomb))ic->mBitsetInput[LAUNCH_BOMB] = true; } } void Moteur::loadLevelTileMap(Niveau &niv, uint32_t numNiv) { mMoteurGraphique.loadLevelTileMap(niv, numNiv); } GestionnaireECS &Moteur::getGestionnaireECS() { return mGestECS; } uint32_t Moteur::initLevel() { uint32_t memEntity; //création de l'entité avec les composants nécessaires std::vector<bool> bitsetComp; bitsetComp.resize(getGestionnaireECS().getECSComponentManager()->getNumberComponent()); bitsetComp[TILEMAP_BOMBER_COMPONENT] = true; bitsetComp[ecs::POSITION_COMPONENT] = true; memEntity = mGestECS.addEntity(bitsetComp); mGestECS.getECSComponentManager()->instanciateExternComponent(memEntity, std::make_unique<TilemapBombermanComponent>()); ecs::PositionComponent *pc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::PositionComponent >(memEntity, ecs::POSITION_COMPONENT); assert(pc && "Moteur::initLevel PositionComponent == null\n"); pc->vect2DPosComp.mfX = POSITION_LEVEL_X; pc->vect2DPosComp.mfY = POSITION_LEVEL_Y; return memEntity; } bool Moteur::loadPlayersAndBot(uint32_t uiNumPlayer, uint32_t uiNumBot) { if(MAX_PLAYER < uiNumPlayer + uiNumBot)return false; mMoteurGraphique.loadBaseSprites(); for(uint32_t i = 0 ; i < uiNumPlayer ; ++i) { uint32_t numEntity = createBomberman(i); if(Jeu::getGameMode() != GameMode::SOLO) { Players PlayerId = getSocketSystem()->getProcessPlayerID(); if(PlayerId == i) { NetworkBombermanComponent *nc = mGestECS.getECSComponentManager()-> searchComponentByType<NetworkBombermanComponent>(numEntity, NETWORK_BOMBER_COMPONENT); assert(nc && "ss null"); getSocketSystem()->attributePlayerNetworkID(nc->mNetworkId); } } } return true; //uiNumBot a implémenter ultérieurement } uint32_t Moteur::createBomberman(uint32_t numPlayer) { assert(numPlayer < MAX_PLAYER && "Player number out of bound."); std::vector<bool> bitsetComp; fillBombermanEntityBitset(bitsetComp, numPlayer); uint32_t memEntity = instanciateBombermanComponents(bitsetComp); configBombermanComponents(memEntity, numPlayer, bitsetComp); return memEntity; } void Moteur::fillBombermanEntityBitset(std::vector<bool> &bombermanBitset, uint32_t uiNumPlayer) { bombermanBitset.resize(getGestionnaireECS().getECSComponentManager()->getNumberComponent()); bombermanBitset[ecs::DISPLAY_COMPONENT] = true; bombermanBitset[ecs::POSITION_COMPONENT] = true; bombermanBitset[MOVEABLE_BOMBER_COMPONENT] = true; bombermanBitset[ecs::COLL_RECTBOX_COMPONENT] = true; bombermanBitset[FLAG_BOMBER_COMPONENT] = true; bombermanBitset[PLAYER_CONFIG_BOMBER_COMPONENT] = true; bombermanBitset[TIMER_BOMBER_COMPONENT] = true; if(Jeu::getGameMode() != GameMode::SOLO) { Players playerID = getSocketSystem()->getProcessPlayerID(); if(playerID == uiNumPlayer) { bombermanBitset[INPUT_BOMBER_COMPONENT] = true; } bombermanBitset[NETWORK_BOMBER_COMPONENT] = true; } else { bombermanBitset[INPUT_BOMBER_COMPONENT] = true; } } uint32_t Moteur::instanciateBombermanComponents(std::vector<bool> &bombermanBitset) { uint32_t memEntity = mGestECS.addEntity(bombermanBitset); if(bombermanBitset[INPUT_BOMBER_COMPONENT]) { mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<InputBombermanComponent>()); } if(bombermanBitset[NETWORK_BOMBER_COMPONENT]) { mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<NetworkBombermanComponent>()); } mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<MoveableBombermanComponent>()); mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<FlagBombermanComponent>()); mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<PlayerConfigBombermanComponent>()); mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<TimerBombermanComponent>()); return memEntity; } void Moteur::configBombermanComponents(uint32_t numEntity, uint32_t numPlayer, const std::vector<bool> &bombermanBitset) { uint32_t memBombermanSprite = SPRITE_BOMBERMAN_DOWN_STATIC; uint32_t largeurTile = mPtrJeu.getNiveau().getLargeurTile(); uint32_t longueurTile = mPtrJeu.getNiveau().getLongueurTile(); if(bombermanBitset[NETWORK_BOMBER_COMPONENT]) { NetworkBombermanComponent *nb = mGestECS.getECSComponentManager()-> searchComponentByType<NetworkBombermanComponent> (numEntity, NETWORK_BOMBER_COMPONENT); nb->mEntityType = TypeEntityFlag::FLAG_BOMBERMAN; nb->mNetworkId = NetworkBombermanComponent::attributeNum(); } FlagBombermanComponent *fc = mGestECS.getECSComponentManager()-> searchComponentByType <FlagBombermanComponent> (numEntity, FLAG_BOMBER_COMPONENT); assert(fc && "dc == null\n"); fc->muiNumFlag = FLAG_BOMBERMAN; ecs::CollRectBoxComponent * cc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::CollRectBoxComponent >(numEntity, ecs::COLL_RECTBOX_COMPONENT); assert(cc && "dc == null\n"); //offset cc->mVect2dVectOrigins.mfX = 5; cc->mRectBox.mSetLenghtRectBox(longueurTile - 10); cc->mVect2dVectOrigins.mfY = 56; cc->mRectBox.mSetHeightRectBox(largeurTile - 10); ecs::DisplayComponent * dc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::DisplayComponent >(numEntity, ecs::DISPLAY_COMPONENT); assert(dc && "dc == null\n"); dc->muiNumSprite = memBombermanSprite; ecs::PositionComponent * pc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::PositionComponent >(numEntity, ecs::POSITION_COMPONENT); assert(pc && "pc == null\n"); PlayerConfigBombermanComponent * playerConfig = mGestECS.getECSComponentManager() -> searchComponentByType<PlayerConfigBombermanComponent>(numEntity, PLAYER_CONFIG_BOMBER_COMPONENT); assert(playerConfig && "pc == null\n"); const vectPairUi_t &memInitPosition = Niveau::static_getVectInitPositionBomberman(); playerConfig->mInitX = memInitPosition[numPlayer].first; playerConfig->mInitY = memInitPosition[numPlayer].second; InputBombermanComponent * inputComp = nullptr; if(bombermanBitset[INPUT_BOMBER_COMPONENT]) { inputComp = mGestECS.getECSComponentManager() -> searchComponentByType<InputBombermanComponent>(numEntity, INPUT_BOMBER_COMPONENT); assert(inputComp && "inputComp == null\n"); } mMoteurGraphique.static_positionnerCaseTileMap(*pc, Niveau::static_getVectInitPositionBomberman()[numPlayer].first, Niveau::static_getVectInitPositionBomberman()[numPlayer].second, true); if(bombermanBitset[INPUT_BOMBER_COMPONENT]) { if(Jeu::getGameMode() != GameMode::SOLO) { Players playerID = getSocketSystem()->getProcessPlayerID(); switch(playerID) { case Players::P_SERVER: inputComp->mNumInput = INPUT_PLAYER_A; break; case Players::P_CLIENT_A: inputComp->mNumInput = INPUT_PLAYER_B; break; case Players::P_CLIENT_B: inputComp->mNumInput = INPUT_PLAYER_C; break; case Players::P_CLIENT_C: inputComp->mNumInput = INPUT_PLAYER_D; break; } } else { if(numPlayer == 0 && Jeu::getGameMode() != GameMode::CLIENT) { inputComp->mNumInput = INPUT_PLAYER_A; } // == 1 pour les tests else if(numPlayer == 1 && Jeu::getGameMode() != GameMode::SERVER) { inputComp->mNumInput = INPUT_PLAYER_B; } } } } void Moteur::loadLevelWall(const Niveau &niv) { std::vector< bool > bitsetComp(getGestionnaireECS().getECSComponentManager()->getNumberComponent()); TilemapBombermanComponent *tmc = mGestECS.getECSComponentManager() -> searchComponentByType<TilemapBombermanComponent>(niv.getNumEntityLevel(), TILEMAP_BOMBER_COMPONENT); assert(tmc && "level TilemapBombermanComponent is null"); const std::vector<unsigned char> &memTabNiv = tmc->mTabTilemap.getTab(); uint32_t longueurNiveau = niv.getLongueurNiveau(); uint32_t largeurTile = mPtrJeu.getNiveau().getLargeurTile(); uint32_t longueurTile = mPtrJeu.getNiveau().getLongueurTile(); uint32_t cmptX = 0, cmptY = 0; std::vector<unsigned char>::const_iterator it = memTabNiv.begin(); for(; it != memTabNiv.end(); ++it) { if(*it > TILE_DESTRUCTIBLE_WALL) { ++cmptX; if(cmptX >= longueurNiveau) { cmptX = 0; ++cmptY; } continue; } bitsetComp.assign(bitsetComp.size(), false); bitsetComp[ ecs::POSITION_COMPONENT ] = true; bitsetComp[ ecs::COLL_RECTBOX_COMPONENT ] = true; bitsetComp[ FLAG_BOMBER_COMPONENT ] = true; uint32_t memEntity = mGestECS.addEntity(bitsetComp); //memorize entity number for destructible wall if(*it == TILE_DESTRUCTIBLE_WALL) { if(! Niveau::static_setNumWallEntityOnPosition(cmptX, cmptY, memEntity)) { assert(false && "Value destruct wall position is out of bound."); } } mGestECS.getECSComponentManager()-> instanciateExternComponent(memEntity, std::make_unique<FlagBombermanComponent>()); FlagBombermanComponent *fc = mGestECS.getECSComponentManager()-> searchComponentByType <FlagBombermanComponent> ( memEntity, FLAG_BOMBER_COMPONENT ); fc->muiNumFlag = FLAG_DESTRUCTIBLE_WALL; ecs::PositionComponent * pc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::PositionComponent >( memEntity, ecs::POSITION_COMPONENT ); assert(pc && "Moteur::loadLevelWall positionComp == null\n"); ecs::CollRectBoxComponent * cc = mGestECS.getECSComponentManager() -> searchComponentByType< ecs::CollRectBoxComponent >( memEntity, ecs::COLL_RECTBOX_COMPONENT ); cc->mRectBox.mSetHeightRectBox(largeurTile); cc->mRectBox.mSetLenghtRectBox(longueurTile); //positionner le décallage cc->mVect2dVectOrigins.mfX = 0; cc->mVect2dVectOrigins.mfY = 0; positionnerComponent(*pc, cmptX, cmptY); cc->mRectBox.mSetOriginsRectBox(pc->vect2DPosComp + cc->mVect2dVectOrigins); ++cmptX; if(cmptX >= longueurNiveau) { cmptX = 0; ++cmptY; } } } void Moteur::waitServerSync(Niveau &niv) { SocketSystem * sss = getSocketSystem(); assert(sss && "SocketSystem == nullptr"); sss->sendData("127.0.0.1", SERVER_PORT); sss->clientSyncPlayerID(); synchLevelFromServer(*sss, niv); synchPlayersFromServer(*sss); sss->launchReceptThread(false); } void Moteur::synchLevelFromServer(SocketSystem &socketSystem, Niveau &niv) { socketSystem.receiveData(false, false); NetworkLevelData levelData; socketSystem.clientSyncNetworkLevel(levelData); mMoteurGraphique.loadLevelTileMapFromServer(niv, levelData); } void Moteur::synchPlayersFromServer(SocketSystem &socketSystem) { socketSystem.receiveData(false, false); uint32_t numPlayers = socketSystem.getBufferReceptSize() / sizeof(NetworkData); //create players from number of players received assert(numPlayers <= MAX_PLAYER); loadPlayersAndBot(numPlayers, 0); std::cout << "Number of players :: " << numPlayers << std::endl; socketSystem.clientSyncNetworkID(); } SocketSystem *Moteur::getSocketSystem() { SocketSystem *sss = mGestECS.getECSSystemManager()-> searchSystemByType<SocketSystem>(SOCKET_SYSTEM); assert(sss && "SocketSystem == nullptr"); return sss; } bool Moteur::stopGame() const { return mLetMeOut; } void Moteur::positionnerComponent(ecs::PositionComponent &posComp, uint32_t posX, uint32_t posY) { posComp.vect2DPosComp.mfX = POSITION_LEVEL_X + posX * mPtrJeu.getNiveau().getLongueurTile(); posComp.vect2DPosComp.mfY = POSITION_LEVEL_Y + posY * mPtrJeu.getNiveau().getLargeurTile(); }
9d1920fcc0739ed4ecef9af1e24b9b37edfb892d
9369318cdbde33f5910c6de3736f1d07400cf276
/427C.cpp
1d2a9eb6157de5799ceebe7148c1693e05b71393
[]
no_license
cwza/codeforces
cc58c646383a201e10422ec80567b52bef4a0da9
e193f5d766e8ddda6cdc8a43b9f1826eeecfc870
refs/heads/master
2023-04-11T12:22:04.555974
2021-04-22T04:45:20
2021-04-22T04:45:20
352,477,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,598
cpp
427C.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define ar array /* Strongly Connected Component */ int n, m; const int maxN = 1e5, maxM = 3e5, M = 1e9+7; int cost[maxN]; vector<int> adj[maxN], radj[maxN]; bool visited[maxN]; vector<int> s; vector<ar<int, 2>> groups; // (minVal, cnt) void dfs1(int u) { visited[u] = true; for(int v : adj[u]) { if(!visited[v]) { dfs1(v); } } s.push_back(u); } void dfs2(int u) { visited[u] = true; if(cost[u] == groups.back()[0]) { groups.back()[1]++; } if(cost[u] < groups.back()[0]) { groups.back()[0] = cost[u]; groups.back()[1] = 1; } for(int v : radj[u]) { if(!visited[v]) { dfs2(v); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); cin >> n; for(int i = 0; i < n; ++i) cin >> cost[i]; cin >> m; for(int i = 0, u, v; i < m; ++i) { cin >> u >> v; u--, v--; adj[u].push_back(v); radj[v].push_back(u); } for(int u = 0; u < n; ++u) { if(!visited[u]) { dfs1(u); } } fill(visited, visited+n, false); for(int i = s.size()-1; i >= 0; --i) { int u = s[i]; if(!visited[u]) { groups.push_back({(int)1e9+1, 0}); dfs2(u); } } ll ans1 = 0, ans2 = 1; for(auto [val, cnt] : groups) { ans1 += val; ans2 = (ans2 * cnt) % M; } cout << ans1 << " " << ans2; }
3634366821f742280d0683d6818a079baa5b05eb
7aea5c7d4345adecdcfdeb87d757a2808519ec46
/JS-VEMCUCtl_20140409/VEMCUCtl/DlgTagClass.cpp
85227253d6f2c308df19d86ef98f13173153c99f
[]
no_license
wpmyj/MonitorSystem
105657d0c4aeb4eb677d8dc760143eb45805e718
f5c49c61f30676b3c5ff07c39fa043cc0dee31b4
refs/heads/master
2021-01-21T14:32:53.419350
2016-02-01T09:27:28
2016-02-01T09:27:28
null
0
0
null
null
null
null
GB18030
C++
false
false
2,519
cpp
DlgTagClass.cpp
// DlgTagClass.cpp : 实现文件 // #include "stdafx.h" #include "VEMCUCtl.h" #include "DlgTagClass.h" // CDlgTagClass 对话框 IMPLEMENT_DYNAMIC(CDlgTagClass, CDialog) CDlgTagClass::CDlgTagClass(CWnd* pParent /*=NULL*/) : CDialog(CDlgTagClass::IDD, pParent) , m_strStationName(_T("")) , m_strStationNum(_T("")) , m_strClass(_T("")) { m_hTreeItem = NULL; } CDlgTagClass::~CDlgTagClass() { } void CDlgTagClass::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_STATION_NAME, m_strStationName); DDV_MaxChars(pDX, m_strStationName, 255); DDX_Text(pDX, IDC_EDIT_CLASS, m_strClass); DDV_MaxChars(pDX, m_strClass, 255); DDX_Control(pDX, IDC_BTN_MODIFY, m_btnModify); DDX_Control(pDX, IDC_BTN_CANCEL, m_btnCancel); } BEGIN_MESSAGE_MAP(CDlgTagClass, CDialog) ON_BN_CLICKED(IDC_BTN_MODIFY, &CDlgTagClass::OnBnClickedBtnModify) ON_BN_CLICKED(IDC_BTN_CANCEL, &CDlgTagClass::OnBnClickedBtnCancel) ON_WM_DESTROY() ON_WM_ERASEBKGND() ON_WM_NCHITTEST() END_MESSAGE_MAP() // CDlgTagClass 消息处理程序 BOOL CDlgTagClass::OnInitDialog() { CDialog::OnInitDialog(); ////////////////////////////////////////////////////////////////////////// LoadSkin(); return TRUE; } BOOL CDlgTagClass::LoadSkin() { m_Bmp.LoadBitmap(IDB_BITMAP_TAG_CLASS_BG); m_btnModify.LoadBitmap(IDB_BITMAP_MODIFY_BTN_BK); m_btnCancel.LoadBitmap(IDB_BITMAP_CANCEL_BTN_BK); return TRUE; } void CDlgTagClass::OnBnClickedBtnModify() { UpdateData(TRUE); OnOK(); } void CDlgTagClass::OnBnClickedBtnCancel() { OnCancel(); } void CDlgTagClass::OnDestroy() { CDialog::OnDestroy(); ////////////////////////////////////////////////////////////////////////// } BOOL CDlgTagClass::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN&&pMsg->wParam==VK_ESCAPE)//屏住ESC键 return TRUE; if(pMsg->message==WM_KEYDOWN&&pMsg->wParam==VK_RETURN)//屏住ENTER键 return TRUE; ////////////////////////////////////////////////////////////////////////// return CDialog::PreTranslateMessage(pMsg); } BOOL CDlgTagClass::OnEraseBkgnd(CDC* pDC) { CRect rect; GetClientRect(&rect); CDC dcMem; CBitmap* pOldBitmap = NULL; BITMAP bm; m_Bmp.GetObject(sizeof(BITMAP),(LPVOID)&bm); dcMem.CreateCompatibleDC(pDC); pOldBitmap = dcMem.SelectObject(&m_Bmp); pDC->BitBlt(rect.left,rect.top,bm.bmWidth,bm.bmHeight,&dcMem,0,0,SRCCOPY); dcMem.SelectObject(pOldBitmap); return TRUE; } LRESULT CDlgTagClass::OnNcHitTest(CPoint point) { return HTCAPTION; }
a381436ea4e864b9090e31e0f11c0a79fd4c54d0
36183993b144b873d4d53e7b0f0dfebedcb77730
/GameDevelopment/AI Game Programming Wisdom/SourceCode/03 Pathfinding with Astar/01 Matthews/ase/NodeView.cpp
3d9fc39650d070eb6cbdba48965459a0c2dcfe20
[]
no_license
alecnunn/bookresources
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
4562f6430af5afffde790c42d0f3a33176d8003b
refs/heads/master
2020-04-12T22:28:54.275703
2018-12-22T09:00:31
2018-12-22T09:00:31
162,790,540
20
14
null
null
null
null
UTF-8
C++
false
false
5,299
cpp
NodeView.cpp
// LeftView.cpp : implementation of the CNodeView class // #include "stdafx.h" #include "ase.h" #include "aseDoc.h" #include "NodeView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CNodeView IMPLEMENT_DYNCREATE(CNodeView, CTreeView) BEGIN_MESSAGE_MAP(CNodeView, CTreeView) //{{AFX_MSG_MAP(CNodeView) ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnSelChanged) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNodeView construction/destruction TVSORTCB CNodeView::m_tvSortData; CNodeView::CNodeView() { m_cImageList.Create(IDB_NODEICONS,16,16,RGB(255,0,255)); m_cTahoma.CreatePointFont(80, "Verdana"); } CNodeView::~CNodeView() { } BOOL CNodeView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CTreeView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CNodeView drawing void CNodeView::OnDraw(CDC* pDC) { CAseDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here } void CNodeView::OnInitialUpdate() { CTreeView::OnInitialUpdate(); CTreeCtrl &ctrl = GetTreeCtrl(); ctrl.SetFont(&m_cTahoma, true); ctrl.SetImageList(&m_cImageList, TVSIL_NORMAL); ctrl.DeleteAllItems(); m_tvSortData.hParent = NULL; m_tvSortData.lpfnCompare = SortByF; m_tvSortData.lParam = 0; } ///////////////////////////////////////////////////////////////////////////// // CNodeView diagnostics #ifdef _DEBUG void CNodeView::AssertValid() const { CTreeView::AssertValid(); } void CNodeView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } CAseDoc* CNodeView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CAseDoc))); return (CAseDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CNodeView message handlers BOOL CNodeView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { dwStyle |= TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS; return CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); } int CNodeView::OnNotifyChild(_asNode *parent, _asNode *child, int data, void *pThis) { CNodeView *me = reinterpret_cast<CNodeView *>(pThis); CTreeCtrl &treectrl = me->GetTreeCtrl(); CString str; str.Format("%d,%d: f=%d, g=%d, h=%d", child->x, child->y, child->f, child->g, child->h); HTREEITEM hNew; HTREEITEM hTree = (parent) ? HTREEITEM(parent->dataptr) : treectrl.GetRootItem(); me->GetDocument()->NodeAdded(child, data); int icon = data; hNew = treectrl.InsertItem(str, icon, icon, hTree); child->dataptr = (void *)(hNew); treectrl.SetItemData(hNew, DWORD(child)); return 0; } int CNodeView::OnNotifyList(_asNode *previous, _asNode *addnode, int data, void *pThis) { CNodeView *me = reinterpret_cast<CNodeView *>(pThis); HTREEITEM hItem; HTREEITEM hPrevious = (previous) ? HTREEITEM(previous->dataptr) : NULL; CString str; CTreeCtrl &treectrl = me->GetTreeCtrl(); if (data < 3) { hItem = treectrl.GetNextItem(treectrl.GetRootItem(), TVGN_NEXT); str.Format("%d,%d: f = %d", addnode->x, addnode->y, addnode->f); if (data == 0) { hItem = treectrl.InsertItem(str, 2, 2, hItem, hPrevious); treectrl.SetItemData(hItem, DWORD(addnode)); } else if (data == 1) { hItem = treectrl.InsertItem(str, 2, 2, hItem, hItem); treectrl.SetItemData(hItem, DWORD(addnode)); } else if (data == 2) { hItem = treectrl.GetChildItem(hItem); if (hItem) treectrl.DeleteItem(hItem); } } else if (data == 3) { hItem = treectrl.GetRootItem(); hItem = treectrl.GetNextItem(hItem, TVGN_NEXT); hItem = treectrl.GetNextItem(hItem, TVGN_NEXT); str.Format("%d,%d", addnode->x, addnode->y); hItem = treectrl.InsertItem(str, 4, 4, hItem, NULL); treectrl.SetItemData(hItem, DWORD(addnode)); } return 0; } void CNodeView::OnSelChanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; HTREEITEM hTreeItem = pNMTreeView->itemNew.hItem; _asNode *node = (_asNode *)(GetTreeCtrl().GetItemData(hTreeItem)); GetDocument()->DrawNode(node); *pResult = 0; } void CNodeView::OnPreAStar() { m_hGoalNode = NULL; GetTreeCtrl().DeleteAllItems(); } void CNodeView::OnPostAStar(_asNode *end) { ASSERT(end); m_hGoalNode = HTREEITEM(end->dataptr); GetTreeCtrl().SetItemState(m_hGoalNode, TVIS_BOLD, TVIS_BOLD); } void CNodeView::DisplayGoalNode() { if (m_hGoalNode) GetTreeCtrl().EnsureVisible(m_hGoalNode); } int CNodeView::SortByF(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { _asNode *item1 = reinterpret_cast<_asNode *>(lParam1); _asNode *item2 = reinterpret_cast<_asNode *>(lParam2); if (item1->f <= item2->f) return -1; return 1; } void CNodeView::SortOpen() { HTREEITEM hItem; hItem = GetTreeCtrl().GetNextItem(GetTreeCtrl().GetRootItem(), TVGN_NEXT); if (hItem) { m_tvSortData.hParent = hItem; GetTreeCtrl().SortChildrenCB(&m_tvSortData); } }
e3854172f62e19725d52a06a31c710d7fc62c2e0
acc56d2dbed5bf594b66f34fc0505a5935f331ea
/source/qmltoolbox/include/qmltoolbox/ForwardingStreamBuffer.h
5b333dcd146e2f6f933eb83a49b24a8d90d261b2
[ "MIT" ]
permissive
cginternals/qmltoolbox
6432783bf851c7290b4e3257fa5a040bd5696233
451df41aed9c8e0925fd8527ee6babaa08e1e201
refs/heads/master
2022-06-25T05:50:45.150683
2022-05-30T13:17:35
2022-05-30T13:17:35
69,814,899
5
2
null
2017-08-28T14:39:39
2016-10-02T18:43:20
QML
UTF-8
C++
false
false
1,576
h
ForwardingStreamBuffer.h
#pragma once #include <streambuf> #include <ostream> #include <QtCore/qglobal.h> #include <qmltoolbox/MessageHandler.h> namespace qmltoolbox { class MessageHandler; /** * @brief * Stream buffer implementation that forwards messages to MessageHandler */ class QMLTOOLBOX_API ForwardingStreamBuffer : public std::streambuf { public: /** * @brief * Constructor * * @param[in] stream * Standard stream that is redirected * @param[in] handler * Message handler * @param[in] msgType * Message type */ ForwardingStreamBuffer(std::ostream & stream, MessageHandler & handler, MessageHandler::MessageType msgType); /** * @brief * Destructor */ virtual ~ForwardingStreamBuffer(); /** * @brief * Get pointer to the redirected stream buffer * * @return * Stream buffer */ std::streambuf * redirected() const; protected: // Virtual std::streambuf interface virtual int_type overflow(int_type value) override; virtual std::streamsize xsputn(const char * buffer, std::streamsize size) override; virtual int sync() override; private: qmltoolbox::MessageHandler & m_handler; ///< Message handler to which the messages are forwarded MessageHandler::MessageType m_msgType; ///< Message type std::ostream & m_stream; ///< Standard stream that is redirected std::streambuf * m_prevBuffer; ///< Stream buffer of the stream that has been replaced }; } // namespace qmltoolbox
8c016fa925d2c621d8b093ed0bcb29f8bfa1f426
62f8b2bd2a915eb416e23fda07f7b8ce4abf406e
/SlamCodes/zz_replay_ros/src/zz_replay/src/replaykit.cpp
c52b68bdc54ae2590e3c827cc602a3cca2d99d84
[]
no_license
mfkiwl/SLAM-KDQ
8847ec6cf6cbdc5ed452c70ef0f265f9541fbeb0
f7311b8655c190e3189a6b6ea279149eaefc48cb
refs/heads/master
2023-07-27T02:02:25.443106
2021-09-05T02:29:00
2021-09-05T02:29:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,452
cpp
replaykit.cpp
#include <ros/ros.h> #include <rosbag/bag.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <mutex> #include <eigen3/Eigen/Dense> #include "rovio.pb.h" #include "image.pb.h" #include "replaykit.h" using namespace std; string IMU_TOPIC = "/imu"; string IMAGE_TOPIC = "/image"; string REPLAY_FOLDER = "./"; string OUTPUT_PATH = "./"; double SKIP_TIME_S = 0; double SPEED_K = 1.0; int WRITE_BAG_FLG = false; rosbag::Bag bagOut; mutex lck; struct TimedImuData { double t; Eigen::Vector3d gyr; Eigen::Vector3d acc; Eigen::Vector3d init_vel; Eigen::Quaterniond init_quat; float proxi; bool steady_on_ground; bool servo_checking; }; typedef ::zz::replaykit::ReplayKit< ::zz::replaykit::Topics<vision::BottomImage, rovio::InputInfoPack>, ::zz::replaykit::Commands<>> ReplayKitType; void readParameters(const string configFile) { cv::FileStorage fs(configFile,cv::FileStorage::READ); if(!fs.isOpened()) { std::cerr << "ERROR: Wrong path to settings" << std::endl; } fs["imu_topic"] >> IMU_TOPIC; fs["image_topic"] >> IMAGE_TOPIC; fs["replay_folder"] >> REPLAY_FOLDER; fs["output_path"] >> OUTPUT_PATH; fs["skip_time"] >> SKIP_TIME_S; fs["write_bag"] >> WRITE_BAG_FLG; fs["speed_k"] >> SPEED_K; if (WRITE_BAG_FLG) { string rosBagName = OUTPUT_PATH + "/dataset.bag"; bagOut.open(rosBagName, rosbag::bagmode::Write); } } void publishImu(const TimedImuData &imuData,ros::Publisher& publisher) { std::lock_guard<std::mutex> lock(lck); sensor_msgs::Imu imuMsg; imuMsg.angular_velocity.x = imuData.gyr.x(); imuMsg.angular_velocity.y = imuData.gyr.y(); imuMsg.angular_velocity.z = imuData.gyr.z(); imuMsg.linear_acceleration.x = imuData.acc.x(); imuMsg.linear_acceleration.y = imuData.acc.y(); imuMsg.linear_acceleration.z = imuData.acc.z(); imuMsg.header.stamp.fromSec(imuData.t); if(WRITE_BAG_FLG){ bagOut.write(IMU_TOPIC,ros::Time::now(),imuMsg); } else { publisher.publish(imuMsg); } } void publishImage(const double t,const cv::Mat& img,ros::Publisher& publisher) { //KDQ:如果不上锁很可能被imu的callback打断,导致内存泄露 std::lock_guard<std::mutex> lock(lck); std_msgs::Header timestamp; timestamp.stamp.fromSec(t); cv_bridge::CvImage imgMsg(timestamp,"mono8",img); if(WRITE_BAG_FLG){ bagOut.write(IMAGE_TOPIC,ros::Time::now(),imgMsg.toImageMsg()); }else{ sensor_msgs::ImagePtr msgPtr = imgMsg.toImageMsg(); publisher.publish(msgPtr); } } int main(int argc, char **argv) { ros::init(argc, argv, "zz_replay"); ros::NodeHandle n("~"); cout << "para:" << argc << endl; if (argc < 2) { ROS_ERROR("Please input config file path!"); ros::shutdown(); return -1; } ros::Publisher pub_img,pub_imu; string configFile = argv[1]; //n.getParam("config_file",configFile); readParameters(configFile); ReplayKitType replaykit; pub_img = n.advertise<sensor_msgs::Image>(IMAGE_TOPIC,1000); pub_imu = n.advertise<sensor_msgs::Imu>(IMU_TOPIC,2000); printf("Input replay folder:%s\n", REPLAY_FOLDER.c_str()); replaykit.Subscribe<0>([&](double now_time, const vision::BottomImage &bottomImage) { const cv::Mat im = cv::Mat(cv::Size(bottomImage.width(), bottomImage.height()), CV_8UC1, (char *) bottomImage.image_buffer().c_str()).clone(); auto delay = static_cast<float>(now_time - bottomImage.timestamp()); auto exp_time = bottomImage.exposure_time(); if (1) { printf("[Image] Get %12.6f at %12.6f, exp = %7.3fms, delay = %7.3fms\n", bottomImage.timestamp(), now_time, exp_time * 1e3f, delay * 1e3f); } publishImage(bottomImage.timestamp() + exp_time * 0.5,im,pub_img); }); replaykit.Subscribe<1>([&](double now_time, const rovio::InputInfoPack &info_pack) { TimedImuData element{}; for (size_t i = 0; i < info_pack.info_size(); i++) { element.t = info_pack.info(i).t(); element.gyr.x() = info_pack.info(i).gyr().x(); element.gyr.y() = info_pack.info(i).gyr().y(); element.gyr.z() = info_pack.info(i).gyr().z(); element.acc.x() = info_pack.info(i).acc().x(); element.acc.y() = info_pack.info(i).acc().y(); element.acc.z() = info_pack.info(i).acc().z(); element.init_quat.w() = info_pack.info(i).quat().w(); element.init_quat.x() = info_pack.info(i).quat().x(); element.init_quat.y() = info_pack.info(i).quat().y(); element.init_quat.z() = info_pack.info(i).quat().z(); element.init_vel.x() = 0.; element.init_vel.y() = 0.; element.init_vel.z() = 0.; element.proxi = info_pack.info(i).proxi(); // printf("InputInfo: %11.6f, %7.3f,%7.3f,%7.3f, %7.3f,%7.3f,%7.3f, %7.4f,%7.4f,%7.4f,%7.4f\n", // parsed.t, // parsed.gyr[0], parsed.gyr[1], parsed.gyr[2], // parsed.acc[0], parsed.acc[1], parsed.acc[2], // parsed.init_quat.w(), parsed.init_quat.x(), parsed.init_quat.y(), parsed.init_quat.z()); publishImu(element,pub_imu); } }); zz::replaykit::FileReplayReader<ReplayKitType> reader(REPLAY_FOLDER, replaykit, SPEED_K); reader.SetStartTime(SKIP_TIME_S); std::thread replay_thread([&]() { replaykit.Start(); }); reader.Start(); printf("Rovio replay finished!\n"); while(ros::ok()) { usleep(1000); } ros::spin(); return 0; }
4a8a38dc33493cd8e0d029468e31a82142940bc3
a84c522cc552f6788a40de44fc0a2921deea2263
/1009.cpp
6c6f76c284700de1af3f75fd22a4e06dff0b248a
[]
no_license
tawsifsazid/Lightoj-Solutions
3fc02d4b64f9c22fea3a456302d549bd81dca432
48cc4f0d2bddd08fd1da202fb555a19bb396bf44
refs/heads/master
2020-03-18T09:54:15.947534
2018-08-10T09:55:14
2018-08-10T09:55:14
134,586,265
0
0
null
null
null
null
UTF-8
C++
false
false
1,919
cpp
1009.cpp
#include<bits/stdc++.h> using namespace std; int k,res,ct=0,cases,n; vector<int>graph[20005]; int color[20005]; queue<int>Q; void bfs(){ int i,j,now,vamp,lyken; for(i=0;i<=20000;i++){ vamp = 0; lyken = 0; if(!graph[i].empty() && color[i]==0){ color[i]=1; //printf("%d == vamp\n",i); vamp++; //printf("vamp = %d\n",vamp); Q.push(i); while(!Q.empty()){ now = Q.front(); //printf("now for %d\n",now); Q.pop(); for(i=0;i<graph[now].size();i++){ if(color[graph[now][i]]==0){ if(color[now]==1){ color[graph[now][i]]=2; lyken++; //printf("%d = lyken\n",graph[now][i]); } else{ color[graph[now][i]]=1; vamp++; //printf("%d == vamp\n",graph[now][i]); } Q.push(graph[now][i]); } } } res = res + max(vamp,lyken); } } } int main(){ //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int i,j; scanf("%d",&cases); while(cases--){ ct++; res=0; memset(color,0,sizeof color); Q=queue<int>(); for(i=0;i<=20000;i++)graph[i].clear(); scanf("%d",&n); int u,v; for(i=1;i<=n;i++){ scanf("%d %d",&u,&v); graph[u].push_back(v); graph[v].push_back(u); } bfs(); printf("Case %d: %d\n",ct,res); } }
b6635cc572c449e2088ad5c80343f30de3d1822e
4174c9f65c32a5b117b2ec86abdfaa28ba5abc50
/include/interface/ILogWidget.hpp
7fa5b539c762261f3816178cbbcf59d2769e3fff
[ "Apache-2.0" ]
permissive
icprog/DataTransfer
bc23200f7c732a0f3e7a0529afddec771c666b8e
a71e3625f8aa52f8e42d29d717a2d3bcbe723dc1
refs/heads/master
2020-04-04T16:49:00.418318
2018-08-01T09:52:07
2018-08-01T09:52:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
hpp
ILogWidget.hpp
/** * @file ILogWidget.h * @brief 多文档-日志窗. * * 这里是详细说明。 * @author 刘伯俊 * @par Copyright (c): * 刘伯俊. * All Rights Reserved * @date 2016:07:04 * @note 这里是注意事项。 * @version <版本号> */ #ifndef ILogWidget_h__ #define ILogWidget_h__ #include <QTextEdit> class ILogWidget : public QTextEdit { Q_OBJECT public: ILogWidget(QWidget *parent = NULL) : QTextEdit(parent) { m_iLineNum = 0; setAttribute(Qt::WA_DeleteOnClose); setReadOnly(true); } virtual ~ILogWidget() {} signals: // 用此信号通知菜单栏上的Action void closed(bool flag); protected: virtual void closeEvent(QCloseEvent *e) { // 绑定QAction的setChecked槽,所以此处需要用逆向 emit closed(false); } public slots: virtual void addLine(const QString &msg) { if (m_iLineNum > 500) { m_iLineNum = 0; clear(); } append(msg); m_iLineNum++; } private: qint32 m_iLineNum; }; #endif // ILogWidget_h__
a8068722021e788545dca60a720fbe37c220460f
16d616dd505ded88c54229c127d9e846dd185fe4
/2nd_term/2.1.cpp
fce62ed1ae7abe198c6d7fc1dcb0a551a734865a
[]
no_license
alperenunuvar/C-Exercises
20ce9a01ae861a0d26a27b88d33a27cf8d5611a9
79e325f4f4108413b2096b52613bad661cffa990
refs/heads/master
2020-03-28T08:42:06.044262
2018-09-30T14:34:32
2018-09-30T14:34:32
147,983,226
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
2.1.cpp
/* Complete the following program to print the address and value of each element of array to the screen without changing the pointer value. #include <stdio.h> int main(){ int var[] = {10,100,200} int i, *ptr; // let us have arrray address in pointer ptr = var; */ #include <stdio.h> int main(void) { /* Arrays */ int var[] = {10, 100, 200}; /* Variables */ int i, *ptr; ptr = var; printf("Array\tValue\tAddress\n"); for(i=0;i<3;i++) { printf("var[%d]\t%d\t%p\n", i, *(ptr+i), (ptr+i)); } return 0; }
ec53f74f5e0a3be6bdaf5b08c5ee04d471813680
c0b1a5c911205e47b31f414e3ca92d800ade01d5
/normal/normal-pushdown/src/s3/S3SelectParser.h
125fe5ebe442270cf147e97e231d84c30e31890c
[]
no_license
cloud-olap/s3filter
31b14fe3ed07c3b9d38693993319ba74cc275489
0a7fbb4588044f40881b6ca14d9115133186b6bb
refs/heads/master
2023-06-23T13:30:39.912829
2019-12-16T11:03:00
2019-12-16T11:03:00
387,652,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
h
S3SelectParser.h
// // Created by matt on 14/12/19. // #ifndef NORMAL_NORMAL_PUSHDOWN_SRC_S3_S3SELECTPARSER_H #define NORMAL_NORMAL_PUSHDOWN_SRC_S3_S3SELECTPARSER_H #include <string> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/s3/S3Client.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/ratelimiter/DefaultRateLimiter.h> #include <aws/core/Aws.h> #include <aws/s3/model/SelectObjectContentRequest.h> #include <aws/core/client/ClientConfiguration.h> #include <normal/core/TupleSet.h> class S3SelectParser { private: static const int CSV_READER_BUFFER_SIZE = 128 * 1024; std::vector<unsigned char> partial{}; static std::shared_ptr<TupleSet> parseCompletePayload( const std::vector<unsigned char, Aws::Allocator<unsigned char>>::iterator &from, const std::vector<unsigned char, Aws::Allocator<unsigned char>>::iterator &to); public: std::shared_ptr<TupleSet> parsePayload(Aws::Vector<unsigned char> &Vector); }; #endif //NORMAL_NORMAL_PUSHDOWN_SRC_S3_S3SELECTPARSER_H
169fa85ba1ab176fdaab986fe109615cd34114dd
dbe6e82154f6003e6fefdcf05f92f6ccd54a67cd
/module-c-cpp-concepts-4/sprintf_snprintf 2.cpp
b307e45d27175344e79d391d3224b953dd0021ba
[]
no_license
SrinivasuluCharupally/expert_programming
7866a1d8085365f8626648ca466ad0954ac53d1c
5090f8b7aa9f08a2b8d0a6324a16e800e1a990fd
refs/heads/master
2022-12-23T03:16:56.653585
2020-10-06T02:36:04
2020-10-06T02:36:04
268,735,622
1
0
null
null
null
null
UTF-8
C++
false
false
595
cpp
sprintf_snprintf 2.cpp
#include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a string %d chars long\n",buffer,n); char buffer1 [100]; int cx; cx = snprintf ( buffer1, 100, "The half of %d is %d", 60, 60/2 ); if (cx>=0 && cx<100) // check returned value snprintf ( buffer1+cx, 100-cx, ", and the half of that is %d.", 60/2/2 ); puts (buffer1); return 0; } /* output: [5 plus 3 is 8] is a string 13 chars long The half of 60 is 30, and the half of that is 15. */
2ee22c994f83c8f5d367c61885e9aa8d3684b24c
aa34c5a8bb86c2f43ddbbae6d59ecd0174191991
/CodeChef/INTEST.cpp
2bdb792971fcd204c4bfc1c2677cc96e02be8bfa
[]
no_license
ankitsbu/Contest_Programming
bdc69d68c8696688f2f5d96cf33cedf300e0cf6c
a2bafe9e41a9441c422343f0b9c62beba4fefeb4
refs/heads/master
2016-09-06T21:28:46.064204
2015-01-28T17:05:23
2015-01-28T17:05:23
28,459,638
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
INTEST.cpp
#include <bits/stdc++.h> using namespace std; #define lld long long int #define readlld(n) scanf("%lld",&n) #define print(n) printf("%lld",n) int main() { lld cnt=0,n,k,a; readlld(n); readlld(k); while(n--) { readlld(a); if(a%k==0) cnt++; } print(cnt); }
473da31e877e370dd4049360dd0775d153da7e72
03a957f10754ae97d998b9a5af01e0ec43a36409
/src/chrome/browser/guest_view/guest_view_manager.cc
833123f4be4954d9a877688aa32d7e7293d5daf3
[ "BSD-3-Clause" ]
permissive
xph906/TrackingFree
e5d39ced8909380ec29a38f0776814f762389aea
41540f0bdc8e146630f680d835a4107e7b8fd2c4
refs/heads/master
2021-01-19T11:43:34.409514
2014-05-21T01:54:24
2014-05-21T01:54:24
19,993,612
1
1
null
null
null
null
UTF-8
C++
false
false
10,694
cc
guest_view_manager.cc
// Copyright 2014 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 "chrome/browser/guest_view/guest_view_manager.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/guest_view/guest_view_base.h" #include "chrome/browser/guest_view/guest_view_constants.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/user_metrics.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/result_codes.h" #include "content/public/common/url_constants.h" #include "extensions/browser/extension_system.h" #include "net/base/escape.h" #include "url/gurl.h" using content::BrowserContext; using content::SiteInstance; using content::WebContents; // A WebContents does not immediately have a RenderProcessHost. It acquires one // on initial navigation. This observer exists until that initial navigation in // order to grab the ID if tis RenderProcessHost so that it can register it as // a guest. class GuestWebContentsObserver : public content::WebContentsObserver { public: explicit GuestWebContentsObserver(WebContents* guest_web_contents) : WebContentsObserver(guest_web_contents) { } virtual ~GuestWebContentsObserver() { } // WebContentsObserver: virtual void DidStartProvisionalLoadForFrame( int64 frame_id, int64 parent_frame_id, bool is_main_frame, const GURL& validated_url, bool is_error_page, bool is_iframe_srcdoc, content::RenderViewHost* render_view_host) OVERRIDE { GuestViewManager::FromBrowserContext(web_contents()->GetBrowserContext())-> AddRenderProcessHostID(web_contents()->GetRenderProcessHost()->GetID()); delete this; } virtual void WebContentsDestroyed() OVERRIDE { delete this; } private: DISALLOW_COPY_AND_ASSIGN(GuestWebContentsObserver); }; GuestViewManager::GuestViewManager(content::BrowserContext* context) : current_instance_id_(0), context_(context) {} GuestViewManager::~GuestViewManager() {} // static. GuestViewManager* GuestViewManager::FromBrowserContext( BrowserContext* context) { GuestViewManager* guest_manager = static_cast<GuestViewManager*>(context->GetUserData( guestview::kGuestViewManagerKeyName)); if (!guest_manager) { guest_manager = new GuestViewManager(context); context->SetUserData(guestview::kGuestViewManagerKeyName, guest_manager); } return guest_manager; } content::WebContents* GuestViewManager::GetGuestByInstanceIDSafely( int guest_instance_id, int embedder_render_process_id) { if (!CanEmbedderAccessInstanceIDMaybeKill(embedder_render_process_id, guest_instance_id)) { return NULL; } return GetGuestByInstanceID(guest_instance_id, embedder_render_process_id); } int GuestViewManager::GetNextInstanceID() { return ++current_instance_id_; } content::WebContents* GuestViewManager::CreateGuest( content::SiteInstance* embedder_site_instance, int instance_id, const std::string& storage_partition_id, bool persist_storage, scoped_ptr<base::DictionaryValue> extra_params) { content::RenderProcessHost* embedder_process_host = embedder_site_instance->GetProcess(); // Validate that the partition id coming from the renderer is valid UTF-8, // since we depend on this in other parts of the code, such as FilePath // creation. If the validation fails, treat it as a bad message and kill the // renderer process. if (!base::IsStringUTF8(storage_partition_id)) { content::RecordAction( base::UserMetricsAction("BadMessageTerminate_BPGM")); base::KillProcess( embedder_process_host->GetHandle(), content::RESULT_CODE_KILLED_BAD_MESSAGE, false); return NULL; } const GURL& embedder_site_url = embedder_site_instance->GetSiteURL(); const std::string& host = embedder_site_url.host(); std::string url_encoded_partition = net::EscapeQueryParamValue( storage_partition_id, false); // The SiteInstance of a given webview tag is based on the fact that it's // a guest process in addition to which platform application the tag // belongs to and what storage partition is in use, rather than the URL // that the tag is being navigated to. GURL guest_site(base::StringPrintf("%s://%s/%s?%s", content::kGuestScheme, host.c_str(), persist_storage ? "persist" : "", url_encoded_partition.c_str())); // If we already have a webview tag in the same app using the same storage // partition, we should use the same SiteInstance so the existing tag and // the new tag can script each other. SiteInstance* guest_site_instance = GetGuestSiteInstance(guest_site); if (!guest_site_instance) { // Create the SiteInstance in a new BrowsingInstance, which will ensure // that webview tags are also not allowed to send messages across // different partitions. guest_site_instance = SiteInstance::CreateForURL( embedder_site_instance->GetBrowserContext(), guest_site); } WebContents::CreateParams create_params( embedder_site_instance->GetBrowserContext(), guest_site_instance); create_params.guest_instance_id = instance_id; create_params.guest_extra_params.reset(extra_params.release()); return WebContents::Create(create_params); } void GuestViewManager::MaybeGetGuestByInstanceIDOrKill( int guest_instance_id, int embedder_render_process_id, const GuestByInstanceIDCallback& callback) { if (!CanEmbedderAccessInstanceIDMaybeKill(embedder_render_process_id, guest_instance_id)) { // If we kill the embedder, then don't bother calling back. return; } content::WebContents* guest_web_contents = GetGuestByInstanceID(guest_instance_id, embedder_render_process_id); callback.Run(guest_web_contents); } SiteInstance* GuestViewManager::GetGuestSiteInstance( const GURL& guest_site) { for (GuestInstanceMap::const_iterator it = guest_web_contents_by_instance_id_.begin(); it != guest_web_contents_by_instance_id_.end(); ++it) { if (it->second->GetSiteInstance()->GetSiteURL() == guest_site) return it->second->GetSiteInstance(); } return NULL; } bool GuestViewManager::ForEachGuest(WebContents* embedder_web_contents, const GuestCallback& callback) { for (GuestInstanceMap::iterator it = guest_web_contents_by_instance_id_.begin(); it != guest_web_contents_by_instance_id_.end(); ++it) { WebContents* guest = it->second; GuestViewBase* guest_view = GuestViewBase::FromWebContents(guest); if (embedder_web_contents != guest_view->embedder_web_contents()) continue; if (callback.Run(guest)) return true; } return false; } void GuestViewManager::AddGuest(int guest_instance_id, WebContents* guest_web_contents) { DCHECK(guest_web_contents_by_instance_id_.find(guest_instance_id) == guest_web_contents_by_instance_id_.end()); guest_web_contents_by_instance_id_[guest_instance_id] = guest_web_contents; // This will add the RenderProcessHost ID when we get one. new GuestWebContentsObserver(guest_web_contents); } void GuestViewManager::RemoveGuest(int guest_instance_id) { GuestInstanceMap::iterator it = guest_web_contents_by_instance_id_.find(guest_instance_id); DCHECK(it != guest_web_contents_by_instance_id_.end()); render_process_host_id_multiset_.erase( it->second->GetRenderProcessHost()->GetID()); guest_web_contents_by_instance_id_.erase(it); } void GuestViewManager::AddRenderProcessHostID(int render_process_host_id) { render_process_host_id_multiset_.insert(render_process_host_id); } content::WebContents* GuestViewManager::GetGuestByInstanceID( int guest_instance_id, int embedder_render_process_id) { GuestInstanceMap::const_iterator it = guest_web_contents_by_instance_id_.find(guest_instance_id); if (it == guest_web_contents_by_instance_id_.end()) return NULL; return it->second; } bool GuestViewManager::CanEmbedderAccessInstanceIDMaybeKill( int embedder_render_process_id, int guest_instance_id) { if (!CanEmbedderAccessInstanceID(embedder_render_process_id, guest_instance_id)) { // The embedder process is trying to access a guest it does not own. content::RecordAction( base::UserMetricsAction("BadMessageTerminate_BPGM")); base::KillProcess( content::RenderProcessHost::FromID(embedder_render_process_id)-> GetHandle(), content::RESULT_CODE_KILLED_BAD_MESSAGE, false); return false; } return true; } bool GuestViewManager::CanEmbedderAccessInstanceID( int embedder_render_process_id, int guest_instance_id) { // The embedder is trying to access a guest with a negative or zero // instance ID. if (guest_instance_id <= guestview::kInstanceIDNone) return false; // The embedder is trying to access an instance ID that has not yet been // allocated by GuestViewManager. This could cause instance ID // collisions in the future, and potentially give one embedder access to a // guest it does not own. if (guest_instance_id > current_instance_id_) return false; GuestInstanceMap::const_iterator it = guest_web_contents_by_instance_id_.find(guest_instance_id); if (it == guest_web_contents_by_instance_id_.end()) return true; GuestViewBase* guest_view = GuestViewBase::FromWebContents(it->second); if (!guest_view) return false; return CanEmbedderAccessGuest(embedder_render_process_id, guest_view); } bool GuestViewManager::CanEmbedderAccessGuest(int embedder_render_process_id, GuestViewBase* guest) { // The embedder can access the guest if it has not been attached and its // opener's embedder lives in the same process as the given embedder. if (!guest->attached()) { if (!guest->GetOpener()) return false; return embedder_render_process_id == guest->GetOpener()->embedder_web_contents()->GetRenderProcessHost()-> GetID(); } return embedder_render_process_id == guest->embedder_web_contents()->GetRenderProcessHost()->GetID(); }
550790dfcb9e0d3dcf53dcdc4deaaa8942450fe8
5c7b1407c16a014660232f58f4c533a587022aa0
/rleveldb/rleveldb.cpp
cc7e3376e2693fa0febda1d8352510af2798844b
[]
no_license
kajiken/rleveldb
6373b894a07a45e6391bd8047f348e68b9b35295
70a67d7cbe0057c23716ca47f65be51fa7694929
refs/heads/master
2020-12-25T19:26:19.984127
2011-09-04T14:20:53
2011-09-04T14:20:53
2,323,414
0
0
null
null
null
null
UTF-8
C++
false
false
3,099
cpp
rleveldb.cpp
#include "rleveldb.h" VALUE leveldb_open(VALUE self, VALUE _pathname) { Check_Type(_pathname, T_STRING); Leveldb *ldb; Data_Get_Struct(self, Leveldb, ldb); char* pathname_c = RSTRING_PTR(_pathname); std::string pathname = std::string((char*)RSTRING_PTR(_pathname)); leveldb::Options options; leveldb::Status status = leveldb::DB::Open(options, pathname, &ldb->db); if(status.ok()) { return Qtrue; } return Qnil; } VALUE leveldb_put(VALUE self, VALUE _key, VALUE _val) { Check_Type(_key, T_STRING); Check_Type(_val, T_STRING); Leveldb *ldb; Data_Get_Struct(self, Leveldb, ldb); leveldb::Slice key = leveldb::Slice(RSTRING_PTR(_key), RSTRING_LEN(_key)); leveldb::Slice val = leveldb::Slice(RSTRING_PTR(_val), RSTRING_LEN(_val)); leveldb::Status status = ldb->db->Put(leveldb::WriteOptions(), key, val); if(status.ok()) { return Qtrue; } return Qnil; } VALUE leveldb_get(VALUE self, VALUE _key) { Check_Type(_key, T_STRING); Leveldb *ldb; Data_Get_Struct(self, Leveldb, ldb); leveldb::Slice key = leveldb::Slice(RSTRING_PTR(_key), RSTRING_LEN(_key)); std::string val; leveldb::Status status = ldb->db->Get(leveldb::ReadOptions(), key, &val); if(status.ok()) { return rb_str_new(val.data(), val.size()); } return Qnil; } VALUE leveldb_del(VALUE self, VALUE _key) { Check_Type(_key, T_STRING); Leveldb *ldb; Data_Get_Struct(self, Leveldb, ldb); leveldb::Slice key = leveldb::Slice(RSTRING_PTR(_key), RSTRING_LEN(_key)); std::string val; leveldb::Status status = ldb->db->Get(leveldb::ReadOptions(), key, &val); if (status.IsNotFound()) return Qnil; status = ldb->db->Delete(leveldb::WriteOptions(), key); if(status.ok()) { return rb_str_new(val.data(), val.size()); } return Qnil; } static VALUE leveldb_close(VALUE self) { Leveldb* ldb; Data_Get_Struct(self, Leveldb, ldb); if(ldb->db != NULL) { delete ldb->db; ldb->db = NULL; } return Qtrue; } static void leveldb_obj_free(Leveldb *ldb) { if(ldb->db != NULL) { delete ldb->db; ldb->db = NULL; } delete ldb; } static VALUE leveldb_obj_alloc(VALUE klass) { Leveldb *ldb = new Leveldb; return Data_Wrap_Struct(klass, 0, leveldb_obj_free, ldb); } extern "C" { void Init_leveldb() { static VALUE leveldb = rb_define_module("LevelDB"); VALUE klass = rb_define_class_under(leveldb, "DB", rb_cObject); rb_define_singleton_method(klass, "new", reinterpret_cast<VALUE(*)(...)>(leveldb_obj_alloc), 0); rb_define_method(klass, "open", reinterpret_cast<VALUE(*)(...)>(leveldb_open), 1); rb_define_method(klass, "close", reinterpret_cast<VALUE(*)(...)>(leveldb_close), 0); rb_define_method(klass, "put", reinterpret_cast<VALUE(*)(...)>(leveldb_put), 2); rb_define_method(klass, "get", reinterpret_cast<VALUE(*)(...)>(leveldb_get), 1); rb_define_method(klass, "del", reinterpret_cast<VALUE(*)(...)>(leveldb_del), 1); } }
6cdb69bebd709e88bb6ded30948025526b83509a
32e1b816aff36fc5708ec495221da9e9cf3c9716
/448.find-all-numbers-disappeared-in-an-array.cpp
9b379d3974a5451831244cdd078c53cb172d83df
[]
no_license
blank-27/C-coding
2e276ef3872c7f0b6ec01b7baf4b2ad27a0404df
92e0e506d927ee911be0fa7d7ca5ba76f045ecef
refs/heads/master
2022-10-31T16:06:02.415295
2022-10-26T03:51:05
2022-10-26T03:51:05
212,297,396
0
21
null
2022-10-26T03:51:06
2019-10-02T09:08:27
C++
UTF-8
C++
false
false
726
cpp
448.find-all-numbers-disappeared-in-an-array.cpp
/* * @lc app=leetcode id=448 lang=cpp * * [448] Find All Numbers Disappeared in an Array */ // @lc code=start class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> v; int n = nums.size(); for(int i=0;i<n;i++){ int m = nums[i]; if(m>0){ m=m; }else{ m=-1*m; } if(nums[m-1]>0){ nums[m-1] *=-1; } } // cout<<endl; for(int i=0;i<n;i++){ if(nums[i]>0){ v.push_back(i+1); } } return v; } }; // @lc code=end
b202978ede25cf837a171ff4e103dd32ddf66252
1fe14e05538544b143b261b18c39388d9518ea15
/joke-lang/frontend/my.h
3d9820cd442cff2a1b0752d93d253115c5dec7cd
[ "Apache-2.0" ]
permissive
holoubekm/BI-PJP
25beadbb0be166ebafb7f2f4d5462d7287d9c3fc
5a04757894a6c1c26d81a6e9f366cc9370083cae
refs/heads/master
2021-04-15T16:27:03.141346
2018-03-24T20:59:01
2018-03-24T20:59:01
126,638,659
0
0
null
null
null
null
UTF-8
C++
false
false
156
h
my.h
#include <iostream> #include <cstdlib> #include <cstdio> #include "syntaxparser.h" using namespace std; void parseFile(const char*, vec<tree, va_gc>**);
a0deaf637017d75563ca50c7bcaa7ceb0db85aa3
f55bb4df4419a63e6c070acac27b08b46b390cd4
/cpp/graphs/dfsusingcpp.cpp
3ecbc5f7462969cba2d3349ab3954e8c3563a611
[]
no_license
Shreyansh-Mishra/Data-Structures
199d7818cdc29f9ffebe6696cb1a7045187147e8
4f13b7a43967070e0455ab41cd2f7e1de567f737
refs/heads/master
2022-12-12T02:58:01.515339
2020-09-02T11:03:14
2020-09-02T11:03:14
261,539,485
0
0
null
null
null
null
UTF-8
C++
false
false
757
cpp
dfsusingcpp.cpp
#include<bits/stdc++.h> using namespace std; class Graph{ long long int V; list<long long int>adj[4]; public: void addEdge(long long int a, long long int b){ adj[a].push_back(b); } void dfsutil(long long int v,bool visited[]){ visited[v]=true; cout<<v<<" "; list<long long int>::iterator i; for(i=adj[v].begin();i!=adj[v].end();i++){ if(!visited[*i]){ dfsutil(*i,visited); } } } void dfs(long long int v,long long int size){ bool V[size]; for(int i=0;i<size;i++){ V[i]=false; } dfsutil(v,V); } }; int main(){ Graph g1; g1.addEdge(0,1); g1.addEdge(0,2); g1.addEdge(1,2); g1.addEdge(2,0); g1.addEdge(2,3); g1.addEdge(3,3); g1.dfs(2,4); }
4faa5ffa5ad21dbfcdd1c2c9caa511ea0192f6b5
15a2f9a1b9a246a429976ad26153c7fa8a8c0e97
/luogu/p2216.cpp
3edaac551d8bbe70a53cef9f4202d290ce233d7d
[]
no_license
RealFakeAccount/Oi-times
e6e78074df940452f25f83c7e10ddd0f7a7b1215
8f9ef3203549b310619cc8eaf14d0f392936c9db
refs/heads/master
2022-12-31T07:51:56.038465
2020-10-17T16:40:22
2020-10-17T16:40:22
304,764,604
3
0
null
null
null
null
UTF-8
C++
false
false
1,511
cpp
p2216.cpp
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 1e2 + 10; const int MAXM = 1e3 + 10; inline int read() { int x = 0; char ch = getchar(); while(!isdigit(ch)) ch = getchar(); while(isdigit(ch)) x = x * 10 + ch -'0', ch = getchar(); return x; } int A, B, N; int squ[MAXM][MAXM]; int fmn[MAXM][MAXM], fmx[MAXM][MAXM];//0->min, 1->max; int qmin[MAXM], qmax[MAXM], lmin, lmax, rmin, rmax; int main() { cin>>A>>B>>N; for(int i = 1; i <= A; i++) for(int j = 1; j <= B; j++) squ[i][j] = read(); for(int i = 1; i <= A; i++){ lmin = lmax = rmin = rmax = 1; qmin[1] = qmax[1] = 1; for(int j = 2; j <= B; j++){ while(lmin <= rmin && squ[i][qmin[rmin]] >= squ[i][j]) --rmin; while(lmax <= rmax && squ[i][qmax[rmax]] <= squ[i][j]) --rmax; qmin[++rmin] = j;qmax[++rmax] = j; while((j - qmin[lmin] + 1) > N) ++lmin; while((j - qmax[lmax] + 1) > N) ++lmax; fmn[i][j] = squ[i][qmin[lmin]], fmx[i][j] = squ[i][qmax[lmax]]; } } int ans = (1 << 29); for(int i = N; i <= B; i++){ lmin = rmin = lmax = rmax = 1; qmin[1] = fmn[N][i], qmax[1] = fmx[N][i]; for(int j = N; j <= A; j++){ while(lmin <= rmin && fmn[qmin[rmin]] >= fmn[j]) --rmin; while(lmax <= rmax && fmx[qmax[rmax]] <= fmx[j]) --rmax; qmin[++rmin] = j, qmax[++rmax] = j; while((j - qmin[lmin] + 1) > N) ++lmin; while((j - qmax[lmax] + 1) > N) ++lmax; ans = min(ans, qmax[lmax] - qmin[lmin]); } } cout<<ans<<endl; return 0; }
c5b79a209be2b9119267ac72a5a393a674ff9405
c23b42b301b365f6c074dd71fdb6cd63a7944a54
/contest/Daejeon/2015/d.cpp
b9e02056986a5b37229aac41717bbb4a3cc5de0c
[]
no_license
NTUwanderer/PECaveros
6c3b8a44b43f6b72a182f83ff0eb908c2e944841
8d068ea05ee96f54ee92dffa7426d3619b21c0bd
refs/heads/master
2020-03-27T22:15:49.847016
2019-01-04T14:20:25
2019-01-04T14:20:25
147,217,616
1
0
null
2018-09-03T14:40:49
2018-09-03T14:40:49
null
UTF-8
C++
false
false
538
cpp
d.cpp
#include <bits/stdc++.h> using namespace std; typedef long long LL; #define N 101010 LL n , x[ N ] , y[ N ]; void init(){ scanf( "%lld" , &n ); for( int i = 0 ; i < n ; i ++ ) scanf( "%lld%lld" , &x[ i ] , &y[ i ] ); x[ n ] = x[ 0 ]; y[ n ] = y[ 0 ]; } void solve(){ int cnt = 0; for( int i = 0 ; i < n ; i ++ ){ LL ret = x[ i ] * y[ i + 1 ] - y[ i ] * x[ i + 1 ]; if( ret < 0 ) cnt ++; } puts( cnt > 2 ? "NO" : "YES" ); } int main(){ int _; scanf( "%d" , &_ ); while( _ -- ){ init(); solve(); } }
4af02feb60f05d56fa0f326f30f22cea8680027f
ef1360311214b04c7f394c2bbd3670ec49a01ef3
/ISTbd-22/Енилов Д.А/lab8.2/main.cpp
0cf15646d868cf07c12f0ebea0aaf8bf92b5a486
[]
no_license
Qui-Gon173/AiSD-2020
64ac282ee8ff9b931cef5a9593f531b2436cf6e7
5a07321590c047cd8add2563a67a7381db37277e
refs/heads/master
2023-02-17T00:14:06.089644
2021-01-15T16:07:23
2021-01-15T16:07:23
303,781,723
7
21
null
2021-01-15T16:07:25
2020-10-13T17:33:14
C++
UTF-8
C++
false
false
4,605
cpp
main.cpp
#include <iostream> #include <algorithm> #include "List.h" #include <list> #include "my_geo_generator.cpp" using namespace std; //вывод контейнера void print_container(List& container){ cout<<"size: "<<container.getsize()<<endl; for(auto& item:container){ cout<<item<<endl; } } //вывод суммы контейнера void calculate_sum(List& container){ //cout<<"size: "<<container.getsize()<<endl; unsigned long s=0; for(auto& item:container){ s+=item; } cout<<"Sum: "<<s<<endl; } //вывод среднего значения контейнера void calculate_midValue(List& container){ //cout<<"size: "<<container.getsize()<<endl; unsigned long s=0; for(auto& item:container){ s+=item; } s=s/container.getsize(); cout<<"MidValue: "<<s<<endl; } //вывод минимального значения<algorithm> void MinValue(List& container){ auto s=min_element(container.begin(),container.end()); cout<<"MinValue: "<<*s<<endl; } //вывод максимального значения<algorithm> void MaxValue(List& container){ auto s=max_element(container.begin(),container.end()); cout<<"MaxValue: "<<*s<<endl; } //вывод индекса минимального значения<algorithm> void MinValueIndex(List& container){ auto s=min_element(container.begin(),container.end()); cout<<"MinValueIndex "; container.poisk_by_value(*s); } //вывод индекса максимального значения<algorithm> void MaxValueIndex(List& container){ auto s=max_element(container.begin(),container.end()); cout<<"MaxValueIndex "; container.poisk_by_value(*s); } void init_container(List& container,unsigned long first,unsigned long borderValue,int denominator){ auto generator= my_geo_generator(first,borderValue,denominator); for(auto& item:generator){ container.Add_last_special_for_generator(item); } } int main() { /*WAS BEFORE //создаем список и начальные узлы //создаем список и начальные узлы List lst; lst.just_create_node(1);//создали голову lst.just_create_node(1234);//создали хвост lst.just_create_node(123);//создали 1ый стартовый элемент lst.just_create_node(12);//создали 2ой стартовый элемент lst.printList_from_head_to_tail();//вывели стартовый список от начала до конца */ //NOW auto container=new List; container->just_create_node(1); container->just_create_node(12); //container->just_create_node(123); init_container(*container,2,16,2); print_container(*container);//функция, выводящая контейнер //calculate_sum(*container);//функция, выводящая сумму значений контейнера //calculate_midValue(*container);//функция выводящая среднее значение //MinValue(*container);//функция, выводящая минимальное значение //MaxValue(*container);//функция, выводящая максимальное значение //MinValueIndex(*container);//функция, выводящая индекс минимального значения //MaxValueIndex(*container);//функция, выводящая индекс максимального значения //lst.printList_from_tail_to_head();//вывели стартовый список с конца до начала //lst.creation_node_in_target_place(2,55);метод вставки //lst.delete_target_element(3);//метод удаления //lst.printList_from_head_to_tail();вывели список с конца до начала //lst.poisk_by_value(123);//метод поиска элемента со значением 123 //cout<<lst.sum_values_list();метод возвращающий сумму значений элементов списка //cout<<lst.mid_value();метод возвращающий среднее значение элементов списка //cout<<lst.find_min_value();//метод возвращающий минимальный элемент //cout<<lst.find_max_value();//метод возвращающий максимальный элемент //cout<<"\n"<<lst.getsize();//метод возвращающий количество элементов container->clear();//чистка контейнера return 0; }
d57ca83e1862fdd6ddbe29fe6f796ebf67e4f566
afb7006e47e70c1deb2ddb205f06eaf67de3df72
/third_party/libwebrtc/third_party/abseil-cpp/absl/random/internal/explicit_seed_seq_test.cc
9f555710ad8155182c14ee7982add242c88ceb0d
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marco-c/gecko-dev-wordified
a66383f85db33911b6312dd094c36f88c55d2e2c
3509ec45ecc9e536d04a3f6a43a82ec09c08dff6
refs/heads/master
2023-08-10T16:37:56.660204
2023-08-01T00:39:54
2023-08-01T00:39:54
211,297,590
1
0
null
null
null
null
UTF-8
C++
false
false
7,935
cc
explicit_seed_seq_test.cc
/ / Copyright 2017 The Abseil Authors . / / / / 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 / / / / https : / / www . apache . org / licenses / LICENSE - 2 . 0 / / / / Unless required by applicable law or agreed to in writing software / / distributed under the License is distributed on an " AS IS " BASIS / / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied . / / See the License for the specific language governing permissions and / / limitations under the License . # include " absl / random / internal / explicit_seed_seq . h " # include < iterator > # include < random > # include < utility > # include " gmock / gmock . h " # include " gtest / gtest . h " # include " absl / random / seed_sequences . h " namespace { using : : absl : : random_internal : : ExplicitSeedSeq ; template < typename Sseq > bool ConformsToInterface ( ) { / / Check that the SeedSequence can be default - constructed . { Sseq default_constructed_seq ; } / / Check that the SeedSequence can be constructed with two iterators . { uint32_t init_array [ ] = { 1 3 5 7 9 } ; Sseq iterator_constructed_seq ( init_array & init_array [ 5 ] ) ; } / / Check that the SeedSequence can be std : : initializer_list - constructed . { Sseq list_constructed_seq = { 1 3 5 7 9 11 13 } ; } / / Check that param ( ) and size ( ) return state provided to constructor . { uint32_t init_array [ ] = { 1 2 3 4 5 } ; Sseq seq ( init_array & init_array [ ABSL_ARRAYSIZE ( init_array ) ] ) ; EXPECT_EQ ( seq . size ( ) ABSL_ARRAYSIZE ( init_array ) ) ; uint32_t state_array [ ABSL_ARRAYSIZE ( init_array ) ] ; seq . param ( state_array ) ; for ( int i = 0 ; i < ABSL_ARRAYSIZE ( state_array ) ; i + + ) { EXPECT_EQ ( state_array [ i ] i + 1 ) ; } } / / Check for presence of generate ( ) method . { Sseq seq ; uint32_t seeds [ 5 ] ; seq . generate ( seeds & seeds [ ABSL_ARRAYSIZE ( seeds ) ] ) ; } return true ; } } / / namespace TEST ( SeedSequences CheckInterfaces ) { / / Control case EXPECT_TRUE ( ConformsToInterface < std : : seed_seq > ( ) ) ; / / Abseil classes EXPECT_TRUE ( ConformsToInterface < ExplicitSeedSeq > ( ) ) ; } TEST ( ExplicitSeedSeq DefaultConstructorGeneratesZeros ) { const size_t kNumBlocks = 128 ; uint32_t outputs [ kNumBlocks ] ; ExplicitSeedSeq seq ; seq . generate ( outputs & outputs [ kNumBlocks ] ) ; for ( uint32_t & seed : outputs ) { EXPECT_EQ ( seed 0 ) ; } } TEST ( ExplicitSeeqSeq SeedMaterialIsForwardedIdentically ) { const size_t kNumBlocks = 128 ; uint32_t seed_material [ kNumBlocks ] ; std : : random_device urandom { " / dev / urandom " } ; for ( uint32_t & seed : seed_material ) { seed = urandom ( ) ; } ExplicitSeedSeq seq ( seed_material & seed_material [ kNumBlocks ] ) ; / / Check that output is same as seed - material provided to constructor . { const size_t kNumGenerated = kNumBlocks / 2 ; uint32_t outputs [ kNumGenerated ] ; seq . generate ( outputs & outputs [ kNumGenerated ] ) ; for ( size_t i = 0 ; i < kNumGenerated ; i + + ) { EXPECT_EQ ( outputs [ i ] seed_material [ i ] ) ; } } / / Check that SeedSequence is stateless between invocations : Despite the last / / invocation of generate ( ) only consuming half of the input - entropy the same / / entropy will be recycled for the next invocation . { const size_t kNumGenerated = kNumBlocks ; uint32_t outputs [ kNumGenerated ] ; seq . generate ( outputs & outputs [ kNumGenerated ] ) ; for ( size_t i = 0 ; i < kNumGenerated ; i + + ) { EXPECT_EQ ( outputs [ i ] seed_material [ i ] ) ; } } / / Check that when more seed - material is asked for than is provided nonzero / / values are still written . { const size_t kNumGenerated = kNumBlocks * 2 ; uint32_t outputs [ kNumGenerated ] ; seq . generate ( outputs & outputs [ kNumGenerated ] ) ; for ( size_t i = 0 ; i < kNumGenerated ; i + + ) { EXPECT_EQ ( outputs [ i ] seed_material [ i % kNumBlocks ] ) ; } } } TEST ( ExplicitSeedSeq CopyAndMoveConstructors ) { using testing : : Each ; using testing : : Eq ; using testing : : Not ; using testing : : Pointwise ; uint32_t entropy [ 4 ] ; std : : random_device urandom ( " / dev / urandom " ) ; for ( uint32_t & entry : entropy ) { entry = urandom ( ) ; } ExplicitSeedSeq seq_from_entropy ( std : : begin ( entropy ) std : : end ( entropy ) ) ; / / Copy constructor . { ExplicitSeedSeq seq_copy ( seq_from_entropy ) ; EXPECT_EQ ( seq_copy . size ( ) seq_from_entropy . size ( ) ) ; std : : vector < uint32_t > seeds_1 ( 1000 0 ) ; std : : vector < uint32_t > seeds_2 ( 1000 1 ) ; seq_from_entropy . generate ( seeds_1 . begin ( ) seeds_1 . end ( ) ) ; seq_copy . generate ( seeds_2 . begin ( ) seeds_2 . end ( ) ) ; EXPECT_THAT ( seeds_1 Pointwise ( Eq ( ) seeds_2 ) ) ; } / / Assignment operator . { for ( uint32_t & entry : entropy ) { entry = urandom ( ) ; } ExplicitSeedSeq another_seq ( std : : begin ( entropy ) std : : end ( entropy ) ) ; std : : vector < uint32_t > seeds_1 ( 1000 0 ) ; std : : vector < uint32_t > seeds_2 ( 1000 0 ) ; seq_from_entropy . generate ( seeds_1 . begin ( ) seeds_1 . end ( ) ) ; another_seq . generate ( seeds_2 . begin ( ) seeds_2 . end ( ) ) ; / / Assert precondition : Sequences generated by seed - sequences are not equal . EXPECT_THAT ( seeds_1 Not ( Pointwise ( Eq ( ) seeds_2 ) ) ) ; / / Apply the assignment - operator . / / GCC 12 has a false - positive - Wstringop - overflow warning here . # if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION ( 12 0 ) # pragma GCC diagnostic push # pragma GCC diagnostic ignored " - Wstringop - overflow " # endif another_seq = seq_from_entropy ; # if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION ( 12 0 ) # pragma GCC diagnostic pop # endif / / Re - generate seeds . seq_from_entropy . generate ( seeds_1 . begin ( ) seeds_1 . end ( ) ) ; another_seq . generate ( seeds_2 . begin ( ) seeds_2 . end ( ) ) ; / / Seeds generated by seed - sequences should now be equal . EXPECT_THAT ( seeds_1 Pointwise ( Eq ( ) seeds_2 ) ) ; } / / Move constructor . { / / Get seeds from seed - sequence constructed from entropy . std : : vector < uint32_t > seeds_1 ( 1000 0 ) ; seq_from_entropy . generate ( seeds_1 . begin ( ) seeds_1 . end ( ) ) ; / / Apply move - constructor move the sequence to another instance . absl : : random_internal : : ExplicitSeedSeq moved_seq ( std : : move ( seq_from_entropy ) ) ; std : : vector < uint32_t > seeds_2 ( 1000 1 ) ; moved_seq . generate ( seeds_2 . begin ( ) seeds_2 . end ( ) ) ; / / Verify that seeds produced by moved - instance are the same as original . EXPECT_THAT ( seeds_1 Pointwise ( Eq ( ) seeds_2 ) ) ; / / Verify that the moved - from instance now behaves like a / / default - constructed instance . EXPECT_EQ ( seq_from_entropy . size ( ) 0 ) ; seq_from_entropy . generate ( seeds_1 . begin ( ) seeds_1 . end ( ) ) ; EXPECT_THAT ( seeds_1 Each ( Eq ( 0 ) ) ) ; } } TEST ( ExplicitSeedSeq StdURBGGoldenTests ) { / / Verify that for std : : - URBG instances the results are stable across / / platforms ( these should have deterministic output ) . { ExplicitSeedSeq seed_sequence { 12 34 56 } ; std : : minstd_rand rng ( seed_sequence ) ; std : : minstd_rand : : result_type values [ 4 ] = { rng ( ) rng ( ) rng ( ) rng ( ) } ; EXPECT_THAT ( values testing : : ElementsAre ( 579252 43785881 464353103 1501811174 ) ) ; } { ExplicitSeedSeq seed_sequence { 12 34 56 } ; std : : mt19937 rng ( seed_sequence ) ; std : : mt19937 : : result_type values [ 4 ] = { rng ( ) rng ( ) rng ( ) rng ( ) } ; EXPECT_THAT ( values testing : : ElementsAre ( 138416803 151130212 33817739 138416803 ) ) ; } { ExplicitSeedSeq seed_sequence { 12 34 56 } ; std : : mt19937_64 rng ( seed_sequence ) ; std : : mt19937_64 : : result_type values [ 4 ] = { rng ( ) rng ( ) rng ( ) rng ( ) } ; EXPECT_THAT ( values testing : : ElementsAre ( 19738651785169348 1464811352364190456 18054685302720800 19738651785169348 ) ) ; } }
423d85f618559a1770ff6ef63216669c736d540a
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5658571765186560_0/C++/Gullesnuffs/D2.cpp
880179633b0e71cacbd014b367efd8d9be773f36
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
D2.cpp
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for(int i = (a); i < int(b); ++i) #define rrep(i, a, b) for(int i = (a) - 1; i >= int(b); --i) #define trav(it, v) for(typeof((v).begin()) it = (v).begin(); it != (v).end(); ++it) #define all(v) (v).begin(), (v).end() #define what_is(x) cerr << #x << " is " << x << endl; typedef double fl; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<pii> vpi; void solve(){ int X,R,C; scanf("%d%d%d", &X, &R, &C); if(X >= 7 || X > max(R,C) || (R*C)%X || X > 2*min(R,C)){ puts("RICHARD"); return; } if(X < 2*min(R,C)-1){ puts("GABRIEL"); return; } if(X == 2*min(R,C)){ if(X == 2){ puts("GABRIEL"); return; } puts("RICHARD"); return; } if(X == 2*min(R,C)-1){ if(X == 5 && max(R,C) == 5){ puts("RICHARD"); return; } puts("GABRIEL"); return; } } int main(){ int T; scanf("%d", &T); for(int t=1; t <= T; ++t){ printf("Case #%d: ", t); solve(); } }
c810d61fceeb79357d83051c56020c26f12ae498
9e476acb2fa198abb93d24957068221fcf647ed7
/06/format.h
bd600c1b4bfba34e5adf065aca6acaa5aafc048f
[]
no_license
DimaAndreev30/msu_cpp_autumn_2019
b6a44a08ed7523a055d598b133ff3fc2158d9a58
3686aeccaabd19cab184081a771c6154bc3065fc
refs/heads/master
2020-08-07T08:52:35.866834
2019-12-16T22:30:25
2019-12-16T22:30:25
213,365,113
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
h
format.h
#pragma once #include <vector> #include <string> #include <sstream> #include <cctype> #include <exception> template<class T> void collect_args(std::vector<std::string>& arr, const T& arg) { std::stringstream stream; stream << arg; arr.push_back(stream.str()); } template<class T, class... ArgsT> void collect_args(std::vector<std::string>& arr, const T& arg, const ArgsT&... args) { std::stringstream stream; stream << arg; arr.push_back(stream.str()); collect_args(arr, args...); } std::string format(const char* str) { return str; } template<class... ArgsT> std::string format(const char* str, const ArgsT&... args) { std::vector<std::string> arr; collect_args(arr, args...); std::stringstream stream; for (; *str; str++) { if (*str != '{') { if (*str != '}') stream << *str; else throw std::runtime_error("extra close brace"); } else { str++; if (std::isdigit(*str)) { uint8_t index = *str - '0'; for (str++; std::isdigit(*str); str++) index = 10*index + (*str - '0'); if (*str == '}') { if (index >= arr.size()) throw std::runtime_error("invalid argument"); stream << arr[index]; } else throw std::runtime_error("missing close brace"); } else throw std::runtime_error("missing argument index"); } } return stream.str(); }
8e6f1044689eba1d52bd1ccc0746c4090d8d22a3
d4a14d129e89ce0c9f3c76a5e0b39895753899e8
/src/RestMultipart.hh
2d5f8b743161c28a645e49989200dfbf328e7235
[ "Apache-2.0" ]
permissive
enotnadoske/drunos
1f2ffebb06ab11ad48a743814273c355a0e0f645
79b72078e613c9c5d4e5c37721b726ca3374299b
refs/heads/master
2021-06-19T07:47:18.787810
2021-05-23T16:17:13
2021-05-23T16:17:13
214,454,684
0
0
Apache-2.0
2019-10-11T14:17:26
2019-10-11T14:17:26
null
UTF-8
C++
false
false
4,508
hh
RestMultipart.hh
/* * Copyright 2016 Applied Research Center for Computer Networks * * 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. */ /** @file */ #pragma once #include <string> #include <vector> #include <unordered_map> #include "Common.hh" #include "Loader.hh" #include "Application.hh" #include "Rest.hh" #include "Switch.hh" #include "json11.hpp" #include "OFTransaction.hh" #include "SwitchConnection.hh" #include "oxm/field_set.hh" /** * That module allows REST users to get switch statistics that can be delivered by MultipleRequest messages. * None of Modify actions are implemented in RestFlowMod and StaticFlowPusher modules. * * Handling of each GET consists of the following steps: * - switching in handleGET method * - calling ``sendGetRequest(corresponding type, <params>)`` and turning in event loop * - waiting for the response from a switch and it's handling * - handler (`onResponse`) updated variable that corresponds to the reply type(of13::MultipartReplyFlow replyFlow, for example) * - handler wakes up `handleGET` method * - responding to the user */ class RestMultipart : public Application, RestHandler { Q_OBJECT SIMPLE_APPLICATION(RestMultipart, "rest-multipart") public: void init(Loader* loader, const Config& rootConfig) override; // rest bool eventable() override {return false;} AppType type() override { return AppType::None; } json11::Json handleGET(std::vector<std::string> params, std::string body) override; json11::Json handlePOST(std::vector<std::string> params, std::string body) override; protected slots: /// called on switch's response void onResponse(SwitchConnectionPtr conn, std::shared_ptr<OFMsgUnion> reply); signals: // emitted when response handling (in `onResponse`) is finished void ResponseHandlingFinished(); private: class Controller *ctrl_; class SwitchManager *sw_m_; OFTransaction *transaction_; // a set of sendRequest methods -- per one for each supported rest request void sendGetRequest(of13::MultipartRequestFlow &&req, uint64_t dpid); void sendGetRequest(of13::MultipartRequestPortStats &&req, uint64_t dpid, std::string port_number); void sendGetRequest(of13::MultipartRequestDesc &&req, uint64_t dpid); void sendGetRequest(of13::MultipartRequestAggregate &&req, uint64_t dpid); void sendGetRequest(of13::MultipartRequestTable &&req, uint64_t dpid); void sendGetRequest(of13::MultipartRequestPortDescription &&req, uint64_t dpid); void sendGetRequest(of13::MultipartRequestQueue &&req, uint64_t dpid, std::string port_number, std::string queue_id); void sendPostRequest(of13::MultipartRequestFlow &&mpReq, uint64_t dpid, json11::Json::object req); void sendPostRequest(of13::MultipartRequestAggregate &&mpReq, uint64_t dpid, json11::Json::object req); void processInfo(of13::MultipartRequestFlow &mpReq, const json11::Json::object &req); void processMatches(of13::MultipartRequestFlow &mpReq, const json11::Json::object &matches); void processInfo(of13::MultipartRequestAggregate &mpReq, const json11::Json::object &req); void processMatches(of13::MultipartRequestAggregate &mpReq, const json11::Json::object &matches); // a set of variables for switch's answer storing -- per one for each supported rest requests type std::vector<of13::FlowStats> responseFlow_; std::vector<of13::PortStats> responsePort_; fluid_msg::SwitchDesc responseSwitchDesc_; of13::MultipartReplyAggregate responseAggregate_; std::vector<of13::TableStats> responseTable_; std::vector<of13::Port> responsePortDesc_; std::vector<of13::QueueStats> responseQueue_; };
7042b23540fb21f97bc7b785f49c656e72a29789
0a27164b8baf9c57c6b8dc8c8ef6e61a34d6f3a3
/프로그래머스 문제풀이/서머코딩윈터코딩(~2018)/스킬트리.cpp
8da9c6736ee0afc91fb0981fb7127dbad2f3aa8e
[]
no_license
GyosunShin/ProblemSolving
56840196d3a49b57e50e49ff2fa2ddb4488d38db
4ddedf4b26d9124e10f4f4490834078d9701f750
refs/heads/master
2021-01-04T10:00:12.712086
2020-06-29T12:29:45
2020-06-29T12:29:45
240,494,077
1
0
null
null
null
null
UHC
C++
false
false
593
cpp
스킬트리.cpp
// 가능한 스킬트리 개수를 return #include <string> #include <vector> using namespace std; int alpa[26]; int ans; int solution(string skill, vector<string> skill_trees) { for(int i = 0 ; i < skill.size() ; ++i){ alpa[skill[i] - 'A'] = 1; } for(int i = 0 ; i < skill_trees.size() ; ++i){ bool tmp_flag = true; int idx = 0; for(int j = 0 ; j < skill_trees[i].size() ; ++j){ if(alpa[skill_trees[i][j] - 'A'] == 0) continue; if(skill_trees[i][j] != skill[idx]){ tmp_flag = false; break; } idx++; } if(tmp_flag) ++ans; } return ans; }
18e68c321b5e5b90bcf013557c47a550354a89c1
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/MuonSpectrometer/MuonCnv/MuonSimEventTPCnv/MuonSimEventTPCnv/MMSimHitCollection_p1.h
80eae8cd15a783f890d29585eb3223837e25f406
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
723
h
MMSimHitCollection_p1.h
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef MMSIMHITCOLLECTION_P1_H #define MMSIMHITCOLLECTION_P1_H #include <vector> #include "GeneratorObjectsTPCnv/HepMcParticleLink_p1.h" namespace Muon { class MMSimHitCollection_p1 { public: std::vector<int> m_MMId; std::vector<float> m_globalTime; //postStep std::vector<float> m_stX, m_stY, m_stZ; //!< Represents m_globalPosition in transient class std::vector<float> m_kineticEnergy; std::vector<int> m_particleEncoding; std::vector<float> m_ptX, m_ptY, m_ptZ; std::vector<float> m_depositEnergy; std::vector<HepMcParticleLink_p1> m_partLink; }; } #endif
0d88f9018b36d66629cb0f26a8eb03e59a245358
a0bcbe08ca9d03ed0b557e2703ee862196aa11b3
/src/mpu6050_calibration_node.cpp
77abdc66ce1706a437cb953937ee86468badc27a
[ "MIT" ]
permissive
Brazilian-Institute-of-Robotics/mpu6050_driver
aaf510d00cf6ccf4678d8be49206e0659954f158
1826c1435d4d4938157cccb686e3d56c6b1e268b
refs/heads/master
2023-03-11T02:41:21.531530
2023-03-03T11:12:43
2023-03-03T11:12:43
335,813,408
5
7
MIT
2023-08-21T15:23:58
2021-02-04T02:18:08
C++
UTF-8
C++
false
false
5,363
cpp
mpu6050_calibration_node.cpp
/* ============================================ MIT License // Copyright (c) 2020 Mateus Meneses Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ #include "ros/ros.h" #include "geometry_msgs/Vector3.h" #include "sensor_msgs/Imu.h" #include "mpu6050_driver/mpu6050_calibration_node.hpp" namespace mpu6050_driver { MPU6050CalibrationNode::MPU6050CalibrationNode() : MPU6050Node() , i_term_matrix_(3, 2) , p_term_matrix_(3, 2) , offset_matrix_(3, 2) , error_matrix_(3, 2) {} void MPU6050CalibrationNode::loadParameters() { ros::NodeHandle ph("~"); this->getParameterHelper<float>(ph, "kp", &kp_, 0.1); this->getParameterHelper<float>(ph, "ki", &ki_, 0.1); this->getParameterHelper<float>(ph, "delta", &delta_, 0.5); } void MPU6050CalibrationNode::init() { MPU6050Node::init(); this->loadParameters(); i_term_matrix_ = Eigen::Matrix<float, 3, 2>::Zero(); imu_offsets_pub_ = nh_.advertise<sensor_msgs::Imu>("imu_offsets", 1); ROS_INFO("MPU6050 Calibration Node has started"); } void MPU6050CalibrationNode::computeOffsets() { float dt = 1.0 / pub_rate_; // How it isn't a dynamic system, sample time doesn't must exactly computed IMUData<int16_t> imu_raw_data = mpu6050_.getRawMotion6(); imu_raw_data.accel.z -= 16384; // Remove gravity contribution /* The divisions here is beacause the offsets need to be set when the MPU is in the less sensitive mode (accel in 16g mode and gyro in 2000 degrees/sec mode). For more details, see https://forum.arduino.cc/index.php?topic=535717.0 Another thing, the minus sign is because the error is calculated as setpoint - plant_value, though all set point is always 0, then error = -plant_value */ error_matrix_ << -(imu_raw_data.accel.x / 8), -(imu_raw_data.gyro.x / 4), -(imu_raw_data.accel.y / 8), -(imu_raw_data.gyro.y / 4), -(imu_raw_data.accel.z / 8), -(imu_raw_data.gyro.z / 4); p_term_matrix_ = kp_ * error_matrix_; i_term_matrix_ += ki_ * error_matrix_ * dt; offset_matrix_ = p_term_matrix_ + i_term_matrix_; } void MPU6050CalibrationNode::adjustOffsets() { mpu6050_.setXAccelOffset(static_cast<int16_t>(offset_matrix_(0, 0))); mpu6050_.setYAccelOffset(static_cast<int16_t>(offset_matrix_(1, 0))); mpu6050_.setZAccelOffset(static_cast<int16_t>(offset_matrix_(2, 0))); mpu6050_.setXGyroOffset(static_cast<int16_t>(offset_matrix_(0, 1))); mpu6050_.setYGyroOffset(static_cast<int16_t>(offset_matrix_(1, 1))); mpu6050_.setZGyroOffset(static_cast<int16_t>(offset_matrix_(2, 1))); } void MPU6050CalibrationNode::publishOffsets() { sensor_msgs::Imu imu_offsets_msg; imu_offsets_msg.linear_acceleration.x = offset_matrix_(0, 0); imu_offsets_msg.linear_acceleration.y = offset_matrix_(1, 0); imu_offsets_msg.linear_acceleration.z = offset_matrix_(2, 0); imu_offsets_msg.angular_velocity.x = offset_matrix_(0, 1); imu_offsets_msg.angular_velocity.y = offset_matrix_(1, 1); imu_offsets_msg.angular_velocity.z = offset_matrix_(2, 1); imu_offsets_msg.header.frame_id = imu_frame_id_; imu_offsets_msg.header.stamp = ros::Time::now(); imu_offsets_pub_.publish(imu_offsets_msg); } bool MPU6050CalibrationNode::isCalibrationFinished() { return error_matrix_.isApprox(Eigen::Matrix<float, 3, 2>::Zero(), delta_) ? true : false; } void MPU6050CalibrationNode::printOffsets() { ROS_INFO("Final offset of Accel X axis = %d", static_cast<int16_t>(offset_matrix_(0, 0))); ROS_INFO("Final offset of Accel Y axis = %d", static_cast<int16_t>(offset_matrix_(1, 0))); ROS_INFO("Final offset of Accel Z axis = %d", static_cast<int16_t>(offset_matrix_(2, 0))); ROS_INFO("Final offset of Gyro X axis = %d", static_cast<int16_t>(offset_matrix_(0, 1))); ROS_INFO("Final offset of Gyro Y axis = %d", static_cast<int16_t>(offset_matrix_(1, 1))); ROS_INFO("Final offset of Gyro Z axis = %d", static_cast<int16_t>(offset_matrix_(2, 1))); ROS_INFO("Insert these value above in the config file"); } void MPU6050CalibrationNode::run() { ros::Rate loop_rate(pub_rate_); while (ros::ok()) { this->computeOffsets(); this->adjustOffsets(); this->publishMPUData(); this->publishOffsets(); if (this->isCalibrationFinished()) { this->printOffsets(); ros::shutdown(); } loop_rate.sleep(); } } } // namespace mpu6050_driver
bdbd7629c790670298882fdcfaa0c43df45b89d4
31e5bcb3684c08000e40590f3f8bb85aead12d87
/Complex.cpp
1aa2f90fb6fabae35c9b5c955be34aa5fe43c3c4
[]
no_license
CCCS-students/cpp-oop
512069f2a51a1bfcf5f654fc33584e2cce7fb6ef
de707646963c6e30439611c1a784bdce5554ed1e
refs/heads/master
2021-01-11T15:09:10.963770
2017-01-28T20:34:49
2017-01-28T20:34:49
80,301,210
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
Complex.cpp
#include "Complex.h" std::ostream & operator<<(std::ostream & cout, const Complex & c) { cout << '<' << c.a() << " + " << c.b() << "i" << '>'; return cout; } Complex::Complex(double a, double b) : a_(a), b_(b) { } double Complex::a() const { return a_; } double Complex::b() const { return b_; } Complex Complex::operator+(const Complex & c) const { return Complex(a_ + c.a_, b_+ c.b_); // Complex temp; // temp.a_ = a_ + c.a_; // temp.b_ = b_ + c.b_; // return temp; } // Complex & Complex::operator+=(
4c288b38afa7a3d88520e979060af2acd0be4d0b
f981a891f47e898b6e46c3175695c730dc482455
/plane_extraction_tracking/src/plane.cpp
354aa532053cec2f549617477c201c1b652e2e8e
[]
no_license
ChrisZzh/822-project
b3f4dd4e7051c70de64ff5b0ee13df42aa1d7771
9f2a6dad45a7974de52a03e538890c681a4a3caf
refs/heads/master
2020-04-01T19:12:27.110379
2018-12-10T21:35:16
2018-12-10T21:35:16
153,541,728
1
0
null
null
null
null
UTF-8
C++
false
false
8,181
cpp
plane.cpp
// ros #include <ros/ros.h> // opencv #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> // lidar plane extractor #include "../include/LidarPlaneExtractor.h" #include "../include/DataStructures.h" // Point Cloud Library (PCL) #include <pcl/io/pcd_io.h> #include <pcl/io/io.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/conversions.h> #include <pcl_ros/point_cloud.h> // c++ lib #include <iostream> #include <string> using namespace pcl; using namespace cv; using namespace std; // typedef pcl::PointCloud<pcl::PointXYZI> PointCloud; // global variables bool received_image = false; bool received_lidar = false; ros::Time camera_time = {}; ros::Time lidar_time = {}; PointCloud<PointXYZ> cloud; cv::Mat image; Matrix4d T_I_W = {}; bool load_point_cloud( const string & filename, const PointCloud<PointXYZ>::Ptr &point_cloud_pointer ) { if (io::loadPCDFile<PointXYZ> (filename, *point_cloud_pointer) == -1) //* load the file { PCL_ERROR ("Couldn't read file test_pcd.pcd \n"); return false; } std::cout << "Loaded " << point_cloud_pointer->width * point_cloud_pointer->height << " data points from test_pcd.pcd " << std::endl; return true; } void copy_point_cloud_xyz_to_rgbd( const PointCloud<PointXYZ> &point_cloud, const PointCloud<PointXYZRGB>::Ptr &point_cloud_rgb_ptr ) { point_cloud_rgb_ptr->points.resize( point_cloud.points.size() ); for( size_t i = 0; i < point_cloud.points.size(); i++ ) { point_cloud_rgb_ptr->points[i].x = point_cloud.points[i].x; point_cloud_rgb_ptr->points[i].y = point_cloud.points[i].y; point_cloud_rgb_ptr->points[i].z = point_cloud.points[i].z; point_cloud_rgb_ptr->points[i].r = 0; point_cloud_rgb_ptr->points[i].g = 255; point_cloud_rgb_ptr->points[i].b = 0; } } void init_visualizer( visualization::PCLVisualizer &visualizer, const PointCloud<PointXYZRGB>::Ptr &rgb_cloud_ptr ) { visualizer.setBackgroundColor( 0, 0, 0 ); visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb( rgb_cloud_ptr ); visualizer.addPointCloud<PointXYZRGB> ( rgb_cloud_ptr, rgb, "cloud"); visualizer.addCoordinateSystem( 3.0 ); visualizer.setPointCloudRenderingProperties ( visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud" ); visualizer.initCameraParameters(); } void plane_extraction( const PointCloud<PointXYZRGB>::Ptr &rgb_cloud_ptr, LidarPlaneExtractor &plane_extractor ) { plane_extractor.putPointsInCells(); plane_extractor.find_ground_plane_in_each_cell(); plane_extractor.labelGroundAndNonGroundPoints(); plane_extractor.computePlaneParameters(); plane_extractor.findPlaneInImage(T_I_W); } void print_cloud_rgb( const PointCloud<PointXYZRGB>::Ptr &rgb_cloud_ptr ) { for( const auto & point : rgb_cloud_ptr->points ) { cout << "x = " << point.x << ", y = " << point.y << ", z = " << point.z << endl; } } void labelGround(Mat &image, const MatrixXd &ground_pixel_indices) { Size s = image.size(); cout << s.height << " " << s.width << endl; for (size_t row = 0; row < ground_pixel_indices.rows(); row++) { if (ground_pixel_indices(row, 0) < 0.f || ground_pixel_indices(row, 1) < 0.f) { continue; } else { // cout << "j = " << ground_pixel_indices(row, 0) << " i = " << ground_pixel_indices(row, 1) << " w = " << ground_pixel_indices(row, 2) << endl; auto j = static_cast<size_t>(floor(ground_pixel_indices(row, 0))); auto i = static_cast<size_t>(floor(ground_pixel_indices(row, 1))); // cout << "i = " << i << " j = " << j << endl; if (i > s.height || j > s.width) { continue; } image.at<Vec3b>(i, j)[0] = 0; image.at<Vec3b>(i, j)[1] = 255; image.at<Vec3b>(i, j)[2] = 0; // cout << "ground labled." << endl; } } } void camBased_callback(const sensor_msgs::Image::ConstPtr &img_msg_L, const nav_msgs::Odometry::ConstPtr &odom_msg) { camera_time = odom_msg->header.stamp; received_image = true; cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(img_msg_L, sensor_msgs::image_encodings::BGR8); // image = cv_ptr->image; cv::resize(cv_ptr->image, image, cv::Size(), 0.5, 0.5); // get pose in Eigen, rotation matrix and translation Eigen::Quaterniond orient = Eigen::Quaternion<double>(odom_msg->pose.pose.orientation.w, odom_msg->pose.pose.orientation.x, odom_msg->pose.pose.orientation.y, odom_msg->pose.pose.orientation.z); // get Eigen transformation matrix T_I_W = Eigen::Matrix4d::Zero(); T_I_W(3,3) = 1; T_I_W.block<3,3>(0,0) = orient.normalized().toRotationMatrix(); T_I_W.block<3,1>(0,3) = Eigen::Matrix<double,3,1>(odom_msg->pose.pose.position.x, odom_msg->pose.pose.position.y, odom_msg->pose.pose.position.z); } // void lidar_callback(const sensor_msgs::PointCloud2::ConstPtr &point_cloud) { void lidar_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &point_cloud) { received_lidar = true; // lidar_time = point_cloud->header.stamp; // pcl::PCLPointCloud2 pcl_pc2; // pcl_conversions::toPCL(*point_cloud, pcl_pc2); // pcl::PointCloud<pcl::PointXYZI>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZI>); // pcl::fromPCLPointCloud2(pcl_pc2, *temp_cloud); // cloud = *temp_cloud; cloud = *point_cloud; } // main int main(int argc, char **argv) { ros::init(argc, argv, "plane"); ros::NodeHandle nh("~"); ros::Subscriber lidar_sub; message_filters::Subscriber<sensor_msgs::Image> img_sub_L; message_filters::Subscriber<nav_msgs::Odometry> odom_sub; img_sub_L.subscribe(nh, "/mapping/left/image_rect_color", 10000); odom_sub.subscribe(nh, "/smart_smoother/odom_imu", 10000); lidar_sub = nh.subscribe("/feature_points", 10, &lidar_callback); typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, nav_msgs::Odometry> sync_pol; message_filters::Synchronizer<sync_pol> sync(sync_pol(100), img_sub_L, odom_sub); sync.registerCallback(boost::bind(&camBased_callback, _1, _2)); while (true) { // check condition if (received_lidar && received_image) { std::clock_t start; double duration = 0.f; PointCloud<PointXYZRGB>::Ptr cloud_colored (new PointCloud<PointXYZRGB>); start = std::clock(); copy_point_cloud_xyz_to_rgbd( cloud, cloud_colored ); LidarPlaneExtractor plane_extractor( cloud_colored ); plane_extraction(cloud_colored, plane_extractor); // visualization::PCLVisualizer visualizer( "Visualizer" ); // init_visualizer( visualizer, cloud_colored ); duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; // visualizer.spinOnce( 100 ); // boost::this_thread::sleep( boost::posix_time::microseconds (100) ); start = std::clock(); if (!image.data) { cout << "Could not open or find the image" << std::endl ; return -1; } labelGround(image, plane_extractor.getGroundPointsPixelLocation()); imshow( "Image", image ); duration += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; cout << "Loading and processing one scan consumes: " << duration << " secs." << endl; waitKey(1); // cout << (double(lidar_time.toNSec())/1.0e9 - double(camera_time.toNSec())/1.0e9) << endl; received_image = false; received_lidar = false; } ros::spinOnce(); } return 0; }
6cf6c20754619022b2b3faa0526ef8e0c5af26d0
72e6bf3923659039dc284ca6f0c8d88a61b6c7ff
/src/global.h
213817295be6d5aedd1837dea345742bb7e88ed8
[]
no_license
DiogoCostaPT/PULSE_cpp
b0d525ca52ac8b1692707624bbf223c4407f0b55
4e97404be050d384338a2091a26ed3a63403f97a
refs/heads/2d_compaction
2023-03-25T22:18:45.725773
2021-03-11T21:16:42
2021-03-11T21:16:42
264,300,625
0
2
null
2021-03-29T22:02:57
2020-05-15T21:15:56
C++
UTF-8
C++
false
false
4,981
h
global.h
// Copyright 2021: Diogo Costa // This program, PULSE_cpp, is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) aNCOLS later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef GLOBALH_INCLUDED #define GLOBALH_INCLUDED #include<armadillo> #include<memory> /* ***** * Global Parameters ***** */ class globalpar { public: double Courant=0.8,aD, rho_ice=0, // kg.m-3 at 0 degrees rho_water=0, // kg.m-3 at 0 degrees rho_freshsnow = 320, wetfront_z,num_stblty_thrshld_prsity = 1E-6,alphaIE,Tsim,Tmeteofile,Tqmeltfile; int flag_sens,run_id,s,print_step, hydro_solver, // 0) Crank Nicholson, 1) Forward-time, Central-diff space; snowmodel; // 0) internal, 1) external //std::ofstream logPULSEfile; std::string start_time[1],end_time[1]; }; /* ***** * Global Variables ***** */ class globalvar { public: globalvar() { } globalvar(size_t nh, size_t nl,size_t n_qmelt_file,size_t n_meteo_file, size_t n_timExt, size_t n_maxLayerExt) { this->nh = nh; this->nl = nl; this->n_qmelt_file = n_qmelt_file; this->n_meteo_file = n_meteo_file; this->n_timExt = n_timExt; this->n_maxLayerExt = n_maxLayerExt; c_m = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); //c_i = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); c_s = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); // = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); exchange_is = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); velc_2d = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); disp_2d = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); vfrac2d_m = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); vfrac2d_s = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); v_liq = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); v_swe = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); v_air = std::unique_ptr<arma::Mat<double>>( new arma::mat(nl,nh)); // Depends on SNOWMODEL // For snowmodel = internal meteoall_int = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_meteo_file,5)); qcmel_int = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_qmelt_file,2)); // For snowmodel = external time_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,1)); preci_c_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,1)); v_liq_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,n_maxLayerExt)); v_swe_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,n_maxLayerExt)); v_ice2liq_1_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,n_maxLayerExt)); v_ice2liq_2_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,n_maxLayerExt)); fluxQ_ext = std::unique_ptr<arma::Mat<double>>( new arma::mat(n_timExt,n_maxLayerExt)); } size_t nh,nl,n_qmelt_file,n_meteo_file,n_timExt, n_maxLayerExt; std::unique_ptr<arma::Mat<double>> c_m,c_s,exchange_is,velc_2d,disp_2d,vfrac2d_m,vfrac2d_s; std::unique_ptr<arma::Mat<double>> v_swe,v_air,v_liq; std::unique_ptr<arma::Mat<double>> qcmel_int,meteoall_int; // SNOWMODEL = internal std::unique_ptr<arma::Mat<double>> time_ext, v_liq_ext, v_swe_ext, v_ice2liq_1_ext, v_ice2liq_2_ext, fluxQ_ext, preci_c_ext; // SNOWMODEL = external double snowH = 0.0f, // snowpack depth snowL = 0.0f, // snowpack horizontal lenght snowl = 0.0f, // grid h lenght snowh = 0.0f, // grid l lenght vfrac_m= 0.0f, vfrac_a = 0.0008f, //vfrac_i=0.001, vfrac_s= 1 - vfrac_m,// - vfrac_i, vfrac_m_prev=vfrac_m, //vfrac_i_prev=vfrac_i, vfrac_s_prev=vfrac_s, timstart = 0.0f, wetfront_z = 0.0f, //nh_change = 0.0f, qmelt_t = 0.0f, tempert_t = 0.0f, rainfall_t = 0.0f, snowfall_t = 0.0f, precip_c_t = 0.0f, v_swe_freshsnow_max = 0.0f, v_swe_comp_max = 0.0f, v_swe_comp_min = 0.0f, vfrac_air_frshsnow = 0.0f, compatfact = 0.0f; int wetfront_cell = 0, wetfront_cell_prev = 0; }; #endif
462b2054fedec0120206da1525923a0d10e0353c
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
/OJ - FZU/FZU Monthly/第十二届程序设计竞赛/D So Hard.cpp
81f4d64da4193e3fc03fd8406b2ddf19656fdb4b
[]
no_license
TaoSama/ICPC-Code-Library
f94d4df0786a8a1c175da02de0a3033f9bd103ec
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
refs/heads/master
2020-04-04T06:19:21.023777
2018-11-05T18:22:32
2018-11-05T18:22:32
54,618,194
0
2
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
D So Hard.cpp
// // Created by TaoSama on 2015-05-06 // Copyright (c) 2015 TaoSama. All rights reserved. // #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; const int N = 1e5 + 10; string s; long long n, m; long long tenpow(int x){ long long ret = 1; for(int i = 1; i <= x; ++i) ret *= 10; return ret; } int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); // freopen("out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); int t; cin >> t; while(t--) { cin >> s; int p = s.find('.'); n = atoll(s.substr(0, p).c_str()); m = atoll(s.substr(p + 1, s.size() - p + 1).c_str()); long long ten = tenpow(s.size() - p - 1); int gcd = __gcd(m, ten); n = n * ten / gcd + m / gcd; m = ten / gcd; cout << n << '/' << m << '\n'; } return 0; }
7fd3899b2f1226876c7633c593b218041f32c8c5
037619c654833af903aa780520db5b811fd4ae29
/GrowControl.ino
d0c5754fe2019110ef91cc6bf91c7c642a6376d5
[]
no_license
quixand/GrowControl
81bf8eff0291997df06fc37df49abc5a9ed9c97a
a510f8d62e5cfbc32cfdd0752433cf004b394216
refs/heads/master
2021-01-10T04:50:17.809878
2015-10-05T16:25:14
2015-10-05T16:25:14
43,697,853
0
1
null
null
null
null
UTF-8
C++
false
false
4,430
ino
GrowControl.ino
#include <LiquidCrystal.h> // include LCD library LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // Set LCD pins int menuPos = 0; // Value determines what is displayed and adjusted int menuPosLast = -1; // Value is compared to menuPos in order to prevent constant LCD clear and print int EC = 0; // EC value - variable will be used to set EC range int PH = 0; // PH value - variable will be used to set PH range void setup() { lcd.begin(16, 2); // Initialize LCD delay(20); // settle time lcd.clear(); // clear anything previously on LCD lcd.print("hello world!"); // lcd is alive and working delay(2000); // keep displaying "hello world" } void loop() { const int Select = 721; // analog read value of select button const int Left = 479; // analog read value of left button const int Right = 0; // analog read value of right button const int Up = 131; // analog read value of up button const int Down = 307; //analog read value of down button int Buttons = analogRead(0); // used to compare with button value int moist = analogRead(8); if (Buttons == Right){ // Increments up menuPos to change display if (menuPos >= 5){ // Takes menuPos back to 0 after 5 menuPos = 0; // } else{ menuPosLast = menuPos; // Sets menuPosLast to menuPos menuPos++ +1; // Increments up menuPos } delay(170); // delay to stop over pushing of button } if (Buttons == Left){ // Increments down menuPos to change display if (menuPos <= 0){ // Takes menuPos up to 5 if 0 menuPos = 5; // } else { menuPosLast = menuPos; // Sets menuPosLast to menuPos menuPos-- -1; // Increments down menuPos } delay(170); // delay to stop over pushing of button } if (menuPos == 0) { // If menuPos == 0 if (menuPos != menuPosLast) { // Compares menuPos and MenuPosLast lcd.clear(); // lcd.print("Set EC Value"); // lcd.setCursor(6,1); // Set cursor to second line lcd.print(EC); // Prints the current set value of EC menuPosLast = menuPos; // Sets menuPosLast to menuPos to prevent constant lcd clear / print } if (Buttons == Up){ EC++ +1; delay(170); lcd.clear(); lcd.print("Set EC Value"); lcd.setCursor(6,1); lcd.print(EC); } if (Buttons == Down){ EC-- -1; delay(170); lcd.clear(); lcd.print("Set EC Value"); lcd.setCursor(6,1); lcd.print(EC); } } if (menuPos == 1) { if (menuPos != menuPosLast){ lcd.clear(); lcd.print("Set PH Value"); lcd.setCursor(6,1); lcd.print(PH); menuPosLast = menuPos; } if (Buttons == Up){ PH++ +1; delay(150); lcd.clear(); lcd.print("Set PH Value"); lcd.setCursor(6,1); lcd.print(PH); } if (Buttons == Down){ PH-- -1; delay(150); lcd.clear(); lcd.print("Set PH Value"); lcd.setCursor(6,1); lcd.print(PH); } } if (menuPos == 2) { if (menuPos != menuPosLast){ lcd.clear(); lcd.print("Fill Mixing Res"); lcd.setCursor(0,1); lcd.print("Press Select = Yes"); menuPosLast = menuPos; } } if (menuPos == 3) { if (menuPos != menuPosLast){ lcd.clear(); lcd.print("Start Solution Management"); lcd.setCursor(0,1); lcd.print("Select = YES"); menuPosLast = menuPos; } } if (menuPos == 4) { if (menuPos != menuPosLast){ lcd.clear(); lcd.print("Menu 5"); lcd.setCursor(0,1); lcd.print("Test"); menuPosLast = menuPos; } } if (menuPos == 5) { if (menuPos != menuPosLast){ lcd.clear(); lcd.print("Menu 6"); lcd.setCursor(0,1); lcd.print("Test"); menuPosLast = menuPos; } lcd.clear(); lcd.print(moist); delay(50); } }
0d45bbac162937f78dfe3a38dbdd9d0eb57ab85b
c3054603074c74687797a2af47fff1c3ddb956f6
/Searching/subsequence.cpp
14836420a7d4dc5c4abde3021db08233a3a5b4be
[]
no_license
sanjaykazi/My-Random-Learnings
9953c0e8dc2015cdcf3b951fb959c31ae3e2a731
3f854c1687dc7a4830ce424242755e417c180c7e
refs/heads/main
2023-06-03T13:55:40.728568
2021-06-24T19:49:00
2021-06-24T19:49:00
368,593,484
1
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
subsequence.cpp
#include <iostream> #include<string> #include<vector> using namespace std; void sub_print(string input, string output, vector<string> &v){ if(input.length() == 0){ cout<<output<<" "<<endl; v.push_back(output); return; } sub_print(input.substr(1), output + input[0], v); sub_print(input.substr(1), output, v); } void sub_print1(char input[], char output[], int i){ if(input[0] == '\0'){ output[i] = '\0'; cout<<output<<" "<<endl; return; } sub_print1(input + 1, output, i); output[i] = input[0]; sub_print1(input + 1, output, i+1); } int main() { vector<string> vec; char san1[100]; char out1[10]; string san; string out = ""; cout << "Enter the character" << endl; cin >> san; cout<<"enter the char array:"<<endl; cin>>san1; cout << "below are the subsequence of: "<<san << endl; sub_print(san,out,vec); sub_print1(san1,out1,0); for(int i = 0; i<vec.size();i++){ cout<<vec[i]<<"->"; } return 0; }
92cc6df9070640d86089ca582e964a77f17ada11
695a9df8527fa0bd068c29c7be00c7b8a05df8c8
/lab_12/mainwindow.cpp
40b328832a4944f03ff043643d1e1c011393fb7c
[]
no_license
AntonGorielikov/ALG_Labs_2Year
c229e70507cc8bb9a3ff371307bf493ca78ff482
52226acf8b75eae21e4299844208c1f0a0cb891a
refs/heads/master
2021-08-29T10:51:15.550269
2017-12-13T19:30:28
2017-12-13T19:30:28
103,264,179
0
0
null
null
null
null
UTF-8
C++
false
false
3,464
cpp
mainwindow.cpp
#include "mainwindow.h" #include <QGridLayout> #include <QMessageBox> #include <QVector> #define MIN(x, y) ((x) < (y) ? (x) : (y)) MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QGridLayout *main_layout = new QGridLayout; text_edit_ = new QTextEdit; line_edit_ = new QLineEdit; label_ = new QLabel(tr("&Pattern")); label_->setBuddy(line_edit_); push_button_ = new QPushButton(tr("&Search")); main_layout->addWidget(text_edit_, 0, 0, 1, 2); main_layout->addWidget(label_, 1, 0, 1, 1); main_layout->addWidget(line_edit_, 1, 1, 1, 1); main_layout->addWidget(push_button_, 2, 0, 1, 2); QWidget *main_widget = new QWidget; main_widget->setLayout(main_layout); this->setCentralWidget(main_widget); connect(push_button_, &QPushButton::clicked, this, &MainWindow::do_stuff); } MainWindow::~MainWindow() { } #include <QDebug> void MainWindow::do_stuff() { QString text = text_edit_->toPlainText(), pattern = line_edit_->text(); int pattern_size = pattern.size(), text_size = text.size(); QVector<int> suffix_shift, z_vector, occurances_vector; suffix_shift.resize(pattern_size + 1); suffix_shift.fill(pattern_size); z_vector.resize(pattern_size); z_vector.fill(0); for (int j = 1, max_z_idx = 0, max_z = 0; j < pattern_size; ++j) { if (j <= max_z) z_vector[j] = MIN(max_z - j + 1, z_vector.at(j - max_z_idx)); while (j + z_vector.at(j) < pattern_size && pattern.at(pattern_size - 1 - z_vector.at(j)) == pattern.at(pattern_size - 1 - (j + z_vector.at(j)))) { z_vector[j]++; } if (j + z_vector.at(j) - 1 > max_z) { max_z_idx = j; max_z = j + z_vector.at(j) - 1; } } qDebug() << "Z-function"; for (int i = 0; i < z_vector.size(); i++) qDebug() << z_vector.at(i); for (int j = pattern_size - 1; j > 0; j--) suffix_shift[pattern_size - z_vector.at(j)] = j; for (int j = 1, r = 0; j <= pattern_size - 1; j++) { if (j + z_vector.at(j) == pattern_size) { for (; r <= j; r++) { if (suffix_shift.at(r) == pattern_size) suffix_shift[r] = j; } } } qDebug() << "Suffix shift vector"; for (int i = 0; i < suffix_shift.size(); i++) qDebug() << suffix_shift.at(i); for (int i = 0, j = 0; i <= text_size - pattern_size && j >= 0; i += suffix_shift.at(j+1)) { for (j = pattern_size - 1; j >= 0 && pattern.at(j) == text.at(i + j); j--); if (j < 0) occurances_vector.append(i); } if (occurances_vector.isEmpty()) { QMessageBox::information(this, tr("Search finished"), tr("No hits were found")); } else { QMessageBox::information(this, tr("Search finished"), tr(">=1 hits were found, first of them:\n%1") .arg(occurances_vector.at(0))); select_text(occurances_vector.at(0), pattern_size); } } void MainWindow::select_text(int start, int length) { QTextCursor cursor = text_edit_->textCursor(); cursor.setPosition(start); cursor.setPosition(start + length, QTextCursor::KeepAnchor); text_edit_->setTextCursor(cursor); }
043552ed4c033f79bae758406e52d96ae22077f4
8ae5b7001709dc6ede1776f6412091af55b77742
/algorithm/Regualar_Expression_Match.cpp
bb92434aa981a7184c2b7eb64be5ef908092250a
[]
no_license
bingai/leetcode-1
08fa4ef6319d95c2503d645c8ae28c337ff732dd
cef9b57bad4daba6661e0427e6ebd538c70c50ae
refs/heads/master
2020-04-27T02:03:56.789027
2017-06-16T14:51:16
2017-06-16T14:51:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
Regualar_Expression_Match.cpp
class Solution { public: bool isMatch(const char *s, const char *p) { if(*p == '\0') return *s == '\0'; // normal case if(p[1] != '*' || p[1] == '\0') { // no char to match if(*s == '\0') return false; if(*s==*p || *p=='.') return isMatch(s+1, p+1); else return false; } else { int i=-1; while(i==-1 || s[i] == p[0] || p[0] == '.') { if(isMatch(s+i+1, p+2)) return true; if(s[++i] == '\0') break; } return false; } return false; } };
7443a5c4be257f3943b2942daddcdf77ca98fb08
ef5741834d960cd3930b42f32e187dece4fbf71f
/include/o3d/core/evt.h
1f3c058c9f70964f43747ce4f73452eda1479b03
[]
no_license
dream-overflow/o3d
d893db752166c6e96f0886646643ae696b8a2af1
988956aae32a3956b314e1488385bb51c4409387
refs/heads/master
2023-06-22T03:12:20.291006
2023-06-08T20:56:08
2023-06-08T20:56:08
174,154,406
3
0
null
null
null
null
UTF-8
C++
false
false
24,157
h
evt.h
/** * @file evt.h * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2013-01-01 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #ifndef _O3D_EVT_H #define _O3D_EVT_H #include "evthandler.h" #include "evtlink.h" #include "evtfunction.h" /* //! Creation of a new connection. #define O3D_LINK_EVT(CLASS_, SENDER_, SIGNAL_, RECEIVER_, SLOT_) \ o3d::Link<decltype(CLASS_::SIGNAL_)>::make(SENDER_, SENDER_->SIGNAL_, RECEIVER_, &SLOT_) //! Creation of a new connection to a signal. #define O3D_LINK_EVT_SAFE(CLASS_, SENDER_, SIGNAL_, RECEIVER_, SLOT_) \ o3d::Link<decltype(CLASS_::SIGNAL_)>::make(SENDER_, ((CLASS_*)SENDER_)->SIGNAL_, RECEIVER_, &SLOT_) */ namespace o3d { ///** // * @brief Used on slot to define a parameter. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Usage : // * void mySlot(EvtType<String>::R name); // */ //template <typename T> //struct EvtType { // //! Result type. // typedef T const & R; //}; ///** // * @brief Helper used to connect a signal. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Usage : // * o3d::Link<className::signalType>::make( // * sender, // * sender->signal, // * receiver, // * &receiver::slot) // */ //template <class SGN> //struct Link //{ // typedef typename SGN::SignalType SignalType; // typedef typename SGN::ParamType ParamType; // typedef typename ParamType::T_FunctionParamPtr FunctionParamPtrType; // template <class FUNC_PTR> // static EvtLink<ParamType>* make( // EvtHandler *sender, // SignalType &signal, // EvtHandler *receiver, // FUNC_PTR slot) // { // return new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &signal.mContainer, // String(""), // new ParamType((FunctionParamPtrType)slot)); // } //}; ///** // * Make a signal link, used to connect a signal to a slot between an emiter and a // * receiver. The slot must be a function pointer to a class method. // * @param sender Sender event handler object // * @param signal Signal object on the sender // * @param receiver Receiver event handler object // * @param slot Pointer on a slot on the receiver (must be of the type of the signal) // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // */ //template <class SIGNAL_TYPE, class FUNC_PTR> //static EvtLinkBase* evtLink( // EvtHandler *sender, // SIGNAL_TYPE &signal, // EvtHandler *receiver, // FUNC_PTR slot) //{ // typedef typename SIGNAL_TYPE::ParamType ParamType; // typedef typename ParamType::T_FunctionParamPtr FunctionParamPtrType; // return new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &signal.mContainer, // String(""), // new ParamType((FunctionParamPtrType)slot)); //} ///** // * @brief Base template struct for signals definition. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // */ //template <class P0 = NullType, class P1 = NullType, class P2 = NullType, class P3 = NullType> //struct Signal1; ///** // * @brief A signal with 0 parameters and void as return. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Declaration usage : // * Signal1<> onMySignal; // * Call the signal : // * onMySignal(); // */ //template <> //struct Signal1 <NullType, NullType, NullType, NullType> //{ // typedef EvtFunction0Param ParamType; // typedef Signal1<NullType, NullType, NullType, NullType> SignalType; // mutable EvtContainer<ParamType> mContainer; // void operator ()() const // { // EvtContainer<ParamType>::T_FunctionArray lCallBacks; // mContainer.getCallBacks(lCallBacks); // for (EvtContainer<ParamType>::IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) // { // (*it)->call(); // } // } // typedef EvtFunction0Param::T_FunctionParamPtr Cast; // template <class FUNC_PTR> // void bind( // EvtHandler *sender, // EvtHandler *receiver, // FUNC_PTR slot, // EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) // { // EvtLinkBase *link = new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &this->mContainer, // String(""), // new ParamType((Cast)slot)); // receiver->connect(link, _type); // } //}; ///** // * @brief A signal with 1 parameters and void as return. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Declaration usage : // * Signal1<TYPE> onMySignal; // * Call the signal : // * onMySignal(VALUE); // */ //template <class P0> //struct Signal1 <P0, NullType, NullType, NullType> //{ // typedef EvtFunction1Param<P0> ParamType; // typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; // typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; // typedef Signal1<P0, NullType, NullType, NullType> SignalType; // mutable EvtContainer<ParamType> mContainer; // void operator ()(P0 const &_p0) const // { // T_FunctionArray lCallBacks; // mContainer.getCallBacks(lCallBacks); // for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) // { // (*it)->call(_p0); // } // } // typedef typename EvtFunction1Param<P0>::T_FunctionParamPtr Cast; // template <class FUNC_PTR> // void bind( // EvtHandler *sender, // EvtHandler *receiver, // FUNC_PTR slot, // EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) // { // EvtLinkBase *link = new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &this->mContainer, // String(""), // new ParamType((Cast)slot)); // receiver->connect(link, _type); // } //}; ///** // * @brief A signal with 2 parameters and void as return. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Declaration usage : // * Signal1<TYPE1, TYPE2> onMySignal; // * Call the signal : // * onMySignal(VALUE1, VALUE2); // */ //template <class P0, class P1> //struct Signal1 <P0, P1, NullType, NullType> //{ // typedef EvtFunction2Param<P0, P1> ParamType; // typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; // typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; // typedef Signal1<P0, P1, NullType, NullType> SignalType; // mutable EvtContainer<ParamType> mContainer; // void operator ()(P0 const &_p0, P1 const &_p1) const // { // T_FunctionArray lCallBacks; // mContainer.getCallBacks(lCallBacks); // for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) // { // (*it)->call(_p0, _p1); // } // } // typedef typename EvtFunction2Param<P0, P1>::T_FunctionParamPtr Cast; // template <class FUNC_PTR> // void bind( // EvtHandler *sender, // EvtHandler *receiver, // FUNC_PTR slot, // EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) // { // EvtLinkBase *link = new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &this->mContainer, // String(""), // new ParamType((Cast)slot)); // receiver->connect(link, _type); // } //}; ///** // * @brief A signal with 3 parameters and void as return. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Declaration usage : // * Signal1<TYPE1, TYPE2, TYPE3> onMySignal; // * Call the signal : // * onMySignal(VALUE1, VALUE2, VALUE3); // */ //template <class P0, class P1, class P2> //struct Signal1 <P0, P1, P2, NullType> //{ // typedef EvtFunction3Param<P0, P1, P2> ParamType; // typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; // typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; // typedef Signal1<P0, P1, P2, NullType> SignalType; // mutable EvtContainer<ParamType> mContainer; // void operator ()(P0 const &_p0, P1 const &_p1, P2 const &_p2) const // { // T_FunctionArray lCallBacks; // mContainer.getCallBacks(lCallBacks); // for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) // { // (*it)->call(_p0, _p1, _p2); // } // } // typedef typename EvtFunction3Param<P0, P1, P2>::T_FunctionParamPtr Cast; // template <class FUNC_PTR> // void bind( // EvtHandler *sender, // EvtHandler *receiver, // FUNC_PTR slot, // EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) // { // EvtLinkBase *link = new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &this->mContainer, // String(""), // new ParamType((Cast)slot)); // receiver->connect(link, _type); // } //}; ///** // * @brief A signal with 4 parameters and void as return. // * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) // * @date 2013-01-01 // * Declaration usage : // * Signal1<TYPE1, TYPE2, TYPE3, TYPE4> onMySignal; // * Call the signal : // * onMySignal(VALUE1, VALUE2, VALUE3, VALUE4); // */ //template <class P0, class P1, class P2, class P3> //struct Signal1 // <P0, P1, P2, P3> //{ // typedef EvtFunction4Param<P0, P1, P2, P3> ParamType; // typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; // typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; // typedef Signal1<P0, P1, P2, P3> SignalType; // mutable EvtContainer<ParamType> mContainer; // void operator ()(P0 const &_p0, P1 const &_p1, P2 const &_p2, P3 const &_p3) const // { // T_FunctionArray lCallBacks; // mContainer.getCallBacks(lCallBacks); // for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) // { // (*it)->call(_p0, _p1, _p2, _p3); // } // } // typedef typename EvtFunction4Param<P0, P1, P2, P3>::T_FunctionParamPtr Cast; // template <class FUNC_PTR> // void bind( // EvtHandler *sender, // EvtHandler *receiver, // FUNC_PTR slot, // EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) // { // EvtLinkBase *link = new EvtLink<ParamType>( // sender, // receiver, // //reinterpret_cast<void*>(receiver), // &this->mContainer, // String(""), // new ParamType((Cast)slot)); // receiver->connect(link, _type); // } //}; /** * @brief A signal with variadic parameters and void as return. * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2013-01-04 * Declaration usage : * Signal<TYPE1, TYPE2, ...> onMySignal{this}; * Call the signal : * onMySignal(VALUE1, VALUE2, ...); * @note Uses of the new {} constructor parameters in way to easily initiate * a signal to this parent as sender event handler. */ template <typename ...Params> struct Signal { EvtHandler *m_owner; template<class T> Signal(T *_this) : m_owner(static_cast<EvtHandler*>(_this)) { } typedef EvtStdFunction<Params...> ParamType; typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; typedef Signal<Params...> SignalType; mutable EvtContainer<ParamType> mContainer; void operator ()(Params... values) const { T_FunctionArray lCallBacks; mContainer.getCallBacks(lCallBacks); for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) { (*it)->call(values...); } } typedef void (EvtHandler::*T_FunctionParamPtr)(Params...); typedef typename EvtStdFunction<Params...>::T_StdFunction T_StdFunction; using placeholders_list = std::tuple<decltype(std::placeholders::_1) , decltype(std::placeholders::_2) , decltype(std::placeholders::_3) , decltype(std::placeholders::_4) , decltype(std::placeholders::_5) , decltype(std::placeholders::_6) , decltype(std::placeholders::_7) , decltype(std::placeholders::_8) , decltype(std::placeholders::_9) , decltype(std::placeholders::_10) >; static constexpr std::size_t value = sizeof...(Params); template <typename C, typename T, std::size_t... Ints> static auto binder(void (C::*funcPtr)(Params...), T t, std::index_sequence<Ints...>) { return std::bind(funcPtr, t, typename std::tuple_element<Ints, placeholders_list>::type{}...); } //! Connect with a class::method pointer. template <class C> void connect( EvtHandler *receiver, void (C::*funcPtr)(Params...), EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { //T_StdFunction func = std::bind((T_FunctionParamPtr)slot, std::ref(receiver), std::placeholders::_1); auto func = binder((T_FunctionParamPtr)funcPtr, receiver, std::make_index_sequence<value>{}); EvtLinkBase *link = new EvtLink<ParamType>( m_owner, receiver, //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); //new ParamType((T_FunctionParamPtr)slot)); receiver->connect(link, _type); } //! Connect with a class::method pointer and a specific thread. template <class C> void connect( EvtHandler *receiver, void (C::*funcPtr)(Params...), Thread *thread) { auto func = binder((T_FunctionParamPtr)funcPtr, receiver, std::make_index_sequence<value>{}); EvtLinkBase *link = new EvtLink<ParamType>( m_owner, receiver, //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, thread); } //! Connect with a std::function (bind or lambda expression) and a specified receiver. template<class T> void connect( T *receiver, T_StdFunction func, EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, static_cast<EvtHandler*>(receiver), //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, _type); } //! Connect with a std::function (bind or lambda expression), a specified receiver, //! on a specified thread. template<class T> void connect( T *receiver, T_StdFunction func, Thread *thread) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, static_cast<EvtHandler*>(receiver), //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, thread); } //! Connect with a std::function (bind or lambda expression) //! No need of receiver, it assume it is himself for conveniance. void connect( T_StdFunction func, EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, m_owner, //reinterpret_cast<void*>(m_owner), &this->mContainer, String(""), new ParamType(func)); m_owner->connect(link, _type); } //! Connect with a std::function (bind or lambda expression) //! No need of receiver, it assume it is himself for conveniance. void connect( T_StdFunction func, Thread *thread) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, m_owner, //reinterpret_cast<void*>(m_owner), &this->mContainer, String(""), new ParamType(func)); m_owner->connect(link, thread); } }; /** * @brief Specialization of the previous signe for 0 zero parameters and void as return. * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2013-01-04 * Declaration usage : * Signal<> onMySignal{this}; * Call the signal : * onMySignal(); * @note Uses of the new {} constructor parameters in way to easily initiate * a signal to this parent as sender event handler. */ template <> struct Signal <> { EvtHandler *m_owner; template<class T> Signal(T *_this) : m_owner(static_cast<EvtHandler*>(_this)) { } typedef EvtStdFunction0Param ParamType; typedef typename EvtContainer<ParamType>::T_FunctionArray T_FunctionArray; typedef typename EvtContainer<ParamType>::IT_FunctionArray IT_FunctionArray; typedef Signal<> SignalType; mutable EvtContainer<ParamType> mContainer; void operator ()() const { T_FunctionArray lCallBacks; mContainer.getCallBacks(lCallBacks); for (IT_FunctionArray it = lCallBacks.begin() ; it != lCallBacks.end() ; it++) { (*it)->call(); } } typedef void (EvtHandler::*T_FunctionParamPtr)(); typedef typename EvtStdFunction0Param::T_StdFunction T_StdFunction; //! Connect with a class::method pointer. template <class C> void connect( EvtHandler *receiver, void (C::*funcPtr)(), EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { T_StdFunction func = std::bind((T_FunctionParamPtr)funcPtr, receiver); EvtLinkBase *link = new EvtLink<ParamType>( m_owner, receiver, //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); //new ParamType((T_FunctionParamPtr)slot)); receiver->connect(link, _type); } //! Connect with a class::method pointer. template <class C> void connect( EvtHandler *receiver, void (C::*funcPtr)(), Thread *thread) { T_StdFunction func = std::bind((T_FunctionParamPtr)funcPtr, receiver); EvtLinkBase *link = new EvtLink<ParamType>( m_owner, receiver, //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, thread); } //! Connect with a std::function (bind or lambda expression) and a specified receiver. template<class T> void connect( T *receiver, T_StdFunction func, EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, static_cast<EvtHandler*>(receiver), //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, _type); } //! Connect with a std::function (bind or lambda expression) and a specified receiver. template<class T> void connect( T *receiver, T_StdFunction func, Thread *thread) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, static_cast<EvtHandler*>(receiver), //reinterpret_cast<void*>(receiver), &this->mContainer, String(""), new ParamType(func)); receiver->connect(link, thread); } //! Connect with a std::function (bind or lambda expression) //! No need of receiver, it assume it is himself for conveniance. void connect( T_StdFunction func, EvtHandler::ConnectionType _type=EvtHandler::CONNECTION_AUTO) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, m_owner, //reinterpret_cast<void*>(m_owner), &this->mContainer, String(""), new ParamType(func)); m_owner->connect(link, _type); } //! Connect with a std::function (bind or lambda expression) //! No need of receiver, it assume it is himself for conveniance. void connect( T_StdFunction func, Thread *thread) { EvtLinkBase *link = new EvtLink<ParamType>( m_owner, m_owner, //reinterpret_cast<void*>(m_owner), &this->mContainer, String(""), new ParamType(func)); m_owner->connect(link, thread); } }; } // end namespace o3d #endif // _O3D_EVT_H
89b0e9f18de1b4a4abbb6f71ecb794dda410931b
247da8766eb8175241efe6588a6372e1ebd1a13a
/LeetCode/Binary Tree Level Order Traversal II/main.cpp
604b7f4b050dd3a18f8be9303ab95657ec9c34ee
[]
no_license
Takechiyoo/C-Code
6b0549e950fd9ffdd8c708a37673941d29e4bcd6
bd3510968a0ae53642a6c7345cb71bf170ad5f47
refs/heads/master
2021-01-10T15:04:24.168996
2016-05-08T07:49:32
2016-05-08T07:49:32
48,311,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,934
cpp
main.cpp
#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL){} }; class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > result; queue<TreeNode*> q; stack<vector<int> > res_result; vector<int> temp; if(root == NULL) return result; TreeNode *m = new TreeNode(0); q.push(root); q.push(m); TreeNode *t; while(true) { t = q.front(); q.pop(); if(t == m) { res_result.push(temp); if(q.empty()) break; temp.clear(); q.push(m); continue; } temp.push_back(t->val); if(t->left != NULL) q.push(t->left); if(t->right != NULL) q.push(t->right); } while(!res_result.empty()) { result.push_back(res_result.top()); res_result.pop(); } return result; } vector<vector<int> > res; /* void DFS(TreeNode* root, int level) { if (root == NULL) return; if (level == res.size()) // The level does not exist in output { res.push_back(vector<int>()); // Create a new level } res[level].push_back(root->val); // Add the current value to its level DFS(root->left, level+1); // Go to the next level DFS(root->right,level+1); } vector<vector<int> > levelOrderBottom(TreeNode *root) { DFS(root, 0); return vector<vector<int> > (res.rbegin(), res.rend()); } */ }; int main() { TreeNode *root = new TreeNode(1); Solution s; cout << s.levelOrderBottom(root).size() << endl; cout << "Hello world!" << endl; return 0; }
33e4b470040aae8c55c032bd862f9b1d48647ddc
d5c650155fa58724918629f22fa53f1b0881543a
/GameEngine/src/GameObjectRigid.cpp
793acd1882661f723ff542cc0b18fc2a49390d16
[]
no_license
Orbayd/Game-Engine-Development
6f45ef7c0b63503633ede52fb05337460fa86824
0f3e2b801ead91b218417343bc67f3f4f90f1ef0
refs/heads/master
2021-01-10T15:55:28.934944
2016-03-19T23:48:49
2016-03-19T23:48:49
54,291,593
1
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
GameObjectRigid.cpp
#include <assert.h> #include <math.h> #include "PCSNode.h" #include "MathEngine.h" #include "GameObject.h" #include "GraphicsObject.h" #include "Anim.h" #include "FrameBucket.h" #include "GameObjectRigid.h" GameObjectRigid::GameObjectRigid( GraphicsObject *graphicsObject ) : GameObject(graphicsObject) { this->scale.set(1.0f,1.0f,1.0f); this->pos.set(0.0f,0.0f,0.0f); } GameObjectRigid::~GameObjectRigid() { } Matrix &GameObjectRigid::getWorld() { return this->world; } void GameObjectRigid::update( Time ) { Matrix T = Matrix( TRANS, this->pos); Matrix S = Matrix( SCALE, this->scale); Matrix M = S * T; this->world = M; //this->pGraphicsObject->setWorld( M ); }
cb8433d28462514042fc22503295b45c3a5e1ba5
f5ce006619bf414a9f30fdfeabaaa21260e1c5b6
/C++/area.cpp
4e4df08c3dd9b6ba5669aad74254ae07aab12b2c
[ "MIT" ]
permissive
mahisara10/OpenSource-Sathyabama
b253a9237d2f68e475e25835d5ba438e703803ca
a675d4348d964c65f081a6d6a405fa0d1668fb93
refs/heads/master
2020-08-24T04:48:10.241918
2019-10-22T08:41:14
2019-10-22T08:41:14
216,764,637
0
0
MIT
2019-10-22T08:40:14
2019-10-22T08:40:14
null
UTF-8
C++
false
false
420
cpp
area.cpp
#include <iostream> using namespace std; class Rectangle { int width, height; public: Rectangle(int x,int y); int area() { return width*height; } }; Rectangle::Rectangle (int x, int y) { width = x; height = y; } int main () { Rectangle rect1(3,4); Rectangle rect2(30,23); cout<< "\narea of first rect: " << rect1.area(); cout<< "\narea of second rect: " << rect2.area(); return 0; }
1b17ee9d103d0ec0132548f9be979bb7f2a8a5d6
be7df324d5509c7ebb368c884b53ea9445d32e4f
/MutualInformation/SimilarityMeasures.h
b5cb12da7dbe3e6cb3cbb3b7bdd5c8688b2af264
[]
no_license
shadimsaleh/thesis.code
b75281001aa0358282e9cceefa0d5d0ecfffdef1
085931bee5b07eec9e276ed0041d494c4a86f6a5
refs/heads/master
2021-01-11T12:20:13.655912
2011-10-19T13:34:01
2011-10-19T13:34:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,621
h
SimilarityMeasures.h
/** * @file SimilarityMeasures.h * @brief Computes various similarity measures for 2-dimensional images. * @author Hari Sundar * @date 9/13/2003 * * * So far those measures are only tested using the template type unsigned char. * Using more precise data may result in overflow of certain sums, as I am still * using long variables for summation due to higher speed. Changing all long * variables to double should solve this problem. Note that the gradient images * are saved as int, i.e. 32 bit signed values. Therefore it makes no sense to * use gradient-based measures with template data of a higher precision. * * Stereo Images are supported, i.e. two images appended horizontally. Using the * respective mode with SetStereo(true) takes care of excluding the border in the * middle of the combined image out of the measure computation. * * A Region of Interest may be specified with SetMask(mask) and SetUseMask(true), * mask is unsigned char ftk image, with all non-zero values regarded as included * in the ROI. * * Before the class instance is initialized with InitInternalBuffer(...), both * images have to be supplied with SetFirstImage(...) and SetSecondImage(...) in * order to have the size information. The image data may be changed later, though. **/ #ifndef SBIA_SIMILARITYMEASURES_H #define SBIA_SIMILARITYMEASURES_H #include <vector> #include "array1d.h" #include "array2d.h" #include "image/Image.h" #include "image/IteratorPosition.h" #include "image/Iterator.h" template <typename T> class SimilarityMeasures { public: /** * @brief Constructor * * Resets all variables to their initial values, no allocation is done yet. * **/ SimilarityMeasures(); /** * @brief Destructor * * Frees all the allocated memory. * **/ virtual ~SimilarityMeasures(); /** * @brief Enables or disables the stereo mode * @param flag true=stereo, false=mono * * In stereo mode, the images consist of two parts, appended * horizontally. Therefore the gradient- and neighborhood-based * measures have to omit some columns in the middle of the image, * where the border between the two single images lies. * **/ void SetStereo(bool flag) {m_stereo = flag;}; /** * @brief Enables or disables the ROI mask. * @param flag true=on, false=off * * If enabled, a binary region of interest mask has to be supplied * earlier with the SetMask method. * **/ void SetUseMask(bool flag) {m_useMask = flag;}; /** * @brief Set the intensity threshold * @param value the threshold value * * If set to any value greater zero, all pixels whose intensity is smaller * are being ignored in the measure computation. This is so far only implemented * for the histogram-based measures, MI and CR. Further extension is probably * not necessary, as this is only for testing purposes and any region of interest * may be defined via the binary mask anyway. * **/ void SetIgnoreIntensitiesBelow(T value) {m_ignoreIntensitiesBelow = value;} /** * @brief To initialize the internal buffers. * @param Number of bits for the histogram. * @return False if there is a problem allocating the buffers. **/ bool InitInternalBuffer(int histBits = 8); /** * @brief Computes the measures. * @return returns false if some error happens. * * The input has to be provided already, also the type of the measure should * be specified in advance. **/ bool CalculateMeasures(); /** @name Specify the input data **/ //@{ void SetFirstImage(image::Image<T, 2>& rImage1, T image1MinValue, int image1BitsUsed); void SetSecondImage(image::Image<T, 2>& rImage2, T image2MinValue, int image2BitsUsed); void SetMask(image::Image<unsigned char, 2>& rMask); //@} /** @name Set the type of measures to be computed **/ //@{ void SetMutualInformation(bool flag) {m_calculateMI = flag;}; void SetMutualInformationNorm(bool flag){m_normalizeMI = flag;}; void SetSumofSquareDifference(bool flag){m_calculateSSD = flag;}; void SetSumofAbsoluteDifference(bool flag){m_calculateSAD = flag;}; void SetNormalizedCrossCorr(bool flag){m_calculateNCC = flag;}; void SetLocalNormalizedCorr(bool flag){m_calculateLNC = flag;}; void SetVarianceWeightedCorr(bool flag){m_calculateVWC = flag;}; void SetPatternIntensity(bool flag){m_calculatePI = flag;}; void SetGradientCorrelation(bool flag){m_calculateGC = flag;}; void SetGradientDifference(bool flag){m_calculateGD = flag;}; void SetCorrelationRatio(bool flag){m_calculateCR = flag;}; //@} /** @name Access the results of the computation **/ //@{ double GetMutualInformation(){return m_similarityMI;}; double GetSumofSquareDifference(){return m_similaritySSD;}; double GetSumofAbsoluteDifference(){return m_similaritySAD;}; double GetNormalizedCrossCorr(){return m_similarityNCC;}; double GetLocalNormalizedCorr(){return m_similarityLNC;}; double GetVarianceWeightedCorr(){return m_similarityVWC;}; double GetPatternIntensity(){return m_similarityPI;}; double GetGradientCorrelation(){return m_similarityGC;}; double GetGradientDifference(){return m_similarityGD;}; double GetCorrelationRatio(){return m_similarityCR;}; double GetFirstEntropy(){return m_entropy1;}; double GetSecondEntropy(){return m_entropy2;}; double GetJointEntropy(){return m_entropy3;}; //@} /** @name Access histogram information */ //@{ hs::array1d<unsigned int>* GetFirstHistogram() { return m_phist1; } hs::array1d<unsigned int>* GetSecondHistogram() { return m_phist2; } hs::array2d<unsigned int>* GetJointHistogram() { return m_pDistribution; } //@} double m_lncError; // for validation of LNC: occurrences of zero variance private: // Cut out of the main routine: computes Gradient Correlation for existing gradient images double CalculateGradientCorrelation(); // The same for Gradient Difference double CalculateGradientDifference(); /** @name Results of the measure computation */ //@{ double m_similarityMI; // Mutual Information double m_similaritySSD; // Sum of Squared Differences double m_similaritySAD; // Sum of Absolute Differences double m_similarityNCC; // Normalized Cross Correlation double m_similarityLNC; // Local Normalized Correlation double m_similarityVWC; // Variance Weighted Local Normalized Correlation double m_similarityPI; // Pattern Intensity double m_similarityGC; // Gradient Correlation double m_similarityGD; // Gradient Difference double m_similarityCR; // Correlation Ratio double m_entropy1; // Entropy of the first image double m_entropy2; // Entropy of the second image double m_entropy3; // Joint entropy of both images //@} /** @name Flags which measures to compute */ //@{ bool m_calculateMI; bool m_calculateSSD; bool m_calculateSAD; bool m_calculateNCC; bool m_calculateLNC; bool m_calculateVWC; bool m_calculatePI; bool m_calculateGC; bool m_calculateGD; bool m_calculateCR; //@} /** @name Variances of the gradient images */ //@{ double m_varH1; double m_varH2; double m_varV1; double m_varV2; //@} bool m_normalizeMI; // compute Mutual Information normalized or not bool m_stereo; // use two images attached to each other bool m_useMask; // we are using a binary ROI mask T m_image1MinValue; // lowest value in first image T m_image2MinValue; // lowest value in second image int m_image1BitsUsed; // number of used bits in first image int m_image2BitsUsed; // number of used bits in second image hs::array1d<unsigned int>* m_phist1; // pointer to the first histogram hs::array1d<unsigned int>* m_phist2; // pointer to the second histogram hs::array2d<unsigned int>* m_pDistribution; // 2D integer array containing the distribution hs::image::Image<T, 2>* m_pImage1; // data of first (moving) image hs::image::Image<T, 2>* m_pImage2; // data of second (fixed) image hs::image::Image<int, 2>* m_pGradientH1; // horizontal gradient of first image hs::image::Image<int, 2>* m_pGradientH2; // horizontal gradient of second image hs::image::Image<int, 2>* m_pGradientV1; // vertical gradient of first image hs::image::Image<int, 2>* m_pGradientV2; // vertical gradient of second image hs::image::Image<int, 2>* m_pDiffImage; // difference image for PI hs::image::Image<unsigned char,2>* m_pMask; // binary ROI mask hs::image::Image<unsigned char,2>* m_pMaskGradient;// eroded mask for gradient calculation int m_histBits; // number of bits used for histograms double m_sigmaPI; // square of sigma for pattern intensity int m_radiusPI; // radius for pattern intensity int m_windowLNC; // window size for LNC (half of the width!) int m_gradSize; // number of used pixels in the gradient images T m_ignoreIntensitiesBelow; // for testing strategies to omit dark image regions }; /* ----------- End of class definition. Here comes the implementation. ---------- */ template <typename T> SimilarityMeasures<T>::SimilarityMeasures() { m_phist1 = NULL; m_phist2 = NULL; m_pDistribution = NULL; m_pGradientH1 = NULL; m_pGradientH2 = NULL; m_pGradientV1 = NULL; m_pGradientV2 = NULL; m_pDiffImage = NULL; m_pMask = NULL; m_pMaskGradient = NULL; m_histBits = 0; m_sigmaPI = 100; m_radiusPI = 3; m_windowLNC = 3; m_gradSize = 0; m_lncError = 0; m_ignoreIntensitiesBelow = 0; m_similarityMI = 0.0; m_similaritySSD = 0.0; m_similaritySAD = 0.0; m_similarityNCC = 0.0; m_similarityLNC = 0.0; m_similarityVWC = 0.0; m_similarityPI = 0.0; m_similarityGC = 0.0; m_similarityGD = 0.0; m_similarityCR = 0.0; m_entropy1 = 0.0; m_entropy2 = 0.0; m_entropy3 = 0.0; m_calculateMI = true; m_calculateSSD = false; m_calculateSAD = false; m_calculateNCC = false; m_calculateLNC = false; m_calculateVWC = false; m_calculatePI = false; m_calculateGC = false; m_calculateGD = false; m_calculateCR = false; m_normalizeMI = true; m_stereo = false; m_useMask = false; } template <typename T> SimilarityMeasures<T>::~SimilarityMeasures() { if (m_phist1) delete m_phist1; if (m_phist2) delete m_phist2; if (m_pDistribution) delete m_pDistribution; if (m_pGradientH1) delete m_pGradientH1; if (m_pGradientH2) delete m_pGradientH2; if (m_pGradientV1) delete m_pGradientV1; if (m_pGradientV2) delete m_pGradientV2; if (m_pDiffImage) delete m_pDiffImage; if (m_pMaskGradient) delete m_pMaskGradient; } template <typename T> void SimilarityMeasures<T>::SetFirstImage(image::Image<T, 2>& rImage1, T image1MinValue, int image1BitsUsed) { m_pImage1 = &rImage1; m_image1MinValue = image1MinValue; m_image1BitsUsed = image1BitsUsed; } template <typename T> void SimilarityMeasures<T>::SetSecondImage(image::Image<T, 2>& rImage2, T image2MinValue, int image2BitsUsed) { m_pImage2 = &rImage2; m_image2MinValue = image2MinValue; m_image2BitsUsed = image2BitsUsed; } template <typename T> void SimilarityMeasures<T>::SetMask(image::Image<unsigned char, 2>& rMask) { m_pMask = &rMask; if (m_pMaskGradient) delete m_pMaskGradient; hs::Size<hs::IndexType, 2> size( m_pImage1->getSize(0)-2, m_pImage1->getSize(1)-2 ); m_pMaskGradient = hs::image::Image<unsigned char, 2> (size); // Perform the erosion for the gradient mask for (int y = 1; y < m_pImage1->getSize(1)-1; y++) { for (int x = 1; x < m_pImage1->getSize(0)-1; x++) { (*m_pMaskGradient)(x-1, y-1) = ( ((*m_pMask)(x-1,y-1)) && ((*m_pMask)(x ,y-1)) && ((*m_pMask)(x+1,y-1)) && ((*m_pMask)(x-1,y )) && ((*m_pMask)(x ,y )) && ((*m_pMask)(x+1,y )) && ((*m_pMask)(x-1,y+1)) && ((*m_pMask)(x ,y+1)) && ((*m_pMask)(x+1,y+1)) ); } } } template <typename T> bool SimilarityMeasures<T>::InitInternalBuffer(int histBits) { // delete existing buffers if (m_phist1) { delete m_phist1; m_phist1 = NULL; } if (m_phist2) { delete m_phist2; m_phist2 = NULL; } if (m_pDistribution) { delete m_pDistribution; m_pDistribution = NULL; } if (m_pGradientH1) { delete m_pGradientH1; m_pGradientH1 = NULL; } if (m_pGradientV1) { delete m_pGradientV1; m_pGradientV1 = NULL; } if (m_pGradientH2) { delete m_pGradientH2; m_pGradientH2 = NULL; } if (m_pGradientV2) { delete m_pGradientV2; m_pGradientV2 = NULL; } if (m_pDiffImage) { delete m_pDiffImage; m_pDiffImage = NULL; } // buffers for histogram based measures if ((m_calculateMI) || (m_calculateCR)) { m_phist1 = new hs::array1d<unsigned int>(1 << histBits); if (m_phist1 == NULL) return false; m_phist2 = new hs::array1d<unsigned int>(1 << histBits); if (m_phist2 == NULL) return false; m_pDistribution = new hs::array2d<unsigned int>(1 << histBits,1 << histBits); if (m_pDistribution == NULL) return false; } // buffers for gradient based measures if ((m_calculateGC) || (m_calculateGD)) { hs::Size<hs::IndexType, 2> size1( m_pImage1->getSize(0)-2, m_pImage1->getSize(1)-2 ); hs::Size<hs::IndexType, 2> size2( m_pImage2->getSize(0)-2, m_pImage2->getSize(1)-2 ); m_pGradientH1 = new hs::image::Image<int, 2> (size1); if (m_pGradientH1 == NULL) return false; m_pGradientV1 = new hs::image::Image<int, 2> (size1); if (m_pGradientV1 == NULL) return false; m_pGradientH2 = new hs::image::Image<int, 2> (size2); if (m_pGradientH2 == NULL) return false; m_pGradientV2 = new hs::image::Image<int, 2> (size2); if (m_pGradientV2 == NULL) return false; } if (m_calculatePI) { hs::Size<hs::IndexType, 2> size( m_pImage1->getSize(0), m_pImage1->getSize(1)); m_pDiffImage = new hs::image::Image<int, 2> (size); } m_histBits = histBits; return true; } template <typename T> bool SimilarityMeasures<T>::CalculateMeasures() { // reset the similarity measures m_similarityMI = 0.0; m_similaritySSD = 0.0; m_similaritySAD = 0.0; m_similarityNCC = 0.0; m_similarityLNC = 0.0; m_similarityPI = 0.0; m_similarityGC = 0.0; m_similarityGD = 0.0; m_similarityCR = 0.0; m_entropy1 = 0.0; m_entropy2 = 0.0; m_entropy3 = 0.0; m_gradSize = 0; // clear histograms if ((m_calculateMI) || (m_calculateCR)) { m_phist1->fill(0); m_phist2->fill(0); m_pDistribution->fill(0); } int height = m_pImage1->getSize(1); int width = m_pImage1->getSize(0); int size = 0; // I compute the size by summing up the used pixels later // helper variables // I have no idea why long values are 32 bit here, same as int??? // So I have to use double for some of the sums. long sum1 = 0, sum2 = 0, sum6 = 0, sum7 = 0; double sad = 0, ssd = 0, sum3 = 0, sum4 = 0, sum5 = 0; double countLNC = (2*m_windowLNC+1)*(2*m_windowLNC+1); double sumVWC = 0.0; // find the largest bit number used in the two images int bitsUsed = (m_image1BitsUsed > m_image2BitsUsed)? m_image1BitsUsed: m_image2BitsUsed; // first pass throught the images for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { T pixel1 = ((*m_pImage1)(x,y) -m_image1MinValue) << (bitsUsed - m_image1BitsUsed); T pixel2 = ((*m_pImage2)(x,y) -m_image2MinValue) << (bitsUsed - m_image2BitsUsed); int diff = pixel2 - pixel1; if (m_calculatePI) (*m_pDiffImage)(x,y) = diff; if ((!m_useMask) || ((*m_pMask)(x,y))) { sum1 += pixel1; sum2 += pixel2; if (m_calculateNCC) { sum3 += pixel1 * pixel1; sum4 += pixel2 * pixel2; sum5 += pixel1 * pixel2; } if (m_calculateSAD) sad += abs(diff); if (m_calculateSSD) ssd += diff * diff; // we need histograms for both MI and CR if ((m_calculateMI) || (m_calculateCR)) { // scale values for histogram indexing unsigned int histIndex1; unsigned int histIndex2; if (bitsUsed - m_histBits > 0) { histIndex1 = pixel1 >> (bitsUsed - m_histBits); histIndex2 = pixel2 >> (bitsUsed - m_histBits); } else { histIndex1 = pixel1 << (m_histBits - bitsUsed); histIndex2 = pixel2 << (m_histBits - bitsUsed); } if ((pixel1 >= m_ignoreIntensitiesBelow) && (pixel2 >= m_ignoreIntensitiesBelow)) { // increase respective pixel in PDF m_pDistribution->fastGet(histIndex2, histIndex1)++; // increase histogram pixels m_phist1->fastGet(histIndex1)++; m_phist2->fastGet(histIndex2)++; } } size++; } // create gradient images if ((m_calculateGC) || (m_calculateGD)) { // we do not consider the border pixels if ((x) && (y) && (x < width-1) && (y < height-1) && ((!m_stereo) || (x < width/2 - 1) || (x > width/2)) && ((!m_useMask) || ((*m_pMaskGradient)(x-1,y-1)))) { // we can neglect adding the minimum value, and shift the bits at the end (*m_pGradientH1)(x-1,y-1) = ( -(*m_pImage1)(x-1,y-1) -2*(*m_pImage1)(x,y-1) -(*m_pImage1)(x+1,y-1) +(*m_pImage1)(x-1,y+1) +2*(*m_pImage1)(x,y+1) +(*m_pImage1)(x+1,y+1)) << (bitsUsed - m_image1BitsUsed); (*m_pGradientH2)(x-1,y-1) = ( -(*m_pImage2)(x-1,y-1) -2*(*m_pImage2)(x,y-1) -(*m_pImage2)(x+1,y-1) +(*m_pImage2)(x-1,y+1) +2*(*m_pImage2)(x,y+1) +(*m_pImage2)(x+1,y+1)) << (bitsUsed - m_image2BitsUsed); (*m_pGradientV1)(x-1,y-1) = ( -(*m_pImage1)(x-1,y-1) +(*m_pImage1)(x+1,y-1) -2*(*m_pImage1)(x-1,y) +2*(*m_pImage1)(x+1,y) -(*m_pImage1)(x-1,y+1) +(*m_pImage1)(x+1,y+1)) << (bitsUsed - m_image1BitsUsed); (*m_pGradientV2)(x-1,y-1) = ( -(*m_pImage2)(x-1,y-1) +(*m_pImage2)(x+1,y-1) -2*(*m_pImage2)(x-1,y) +2*(*m_pImage2)(x+1,y) -(*m_pImage2)(x-1,y+1) +(*m_pImage2)(x+1,y+1)) << (bitsUsed - m_image2BitsUsed); m_gradSize++; } } // Local normalized correlation // Does not respect the bitmask yet, I still need to think about that... if ((m_calculateLNC) || (m_calculateVWC)) { if ((x >= m_windowLNC) && (x < width - m_windowLNC) && (y >= m_windowLNC) && (y < height - m_windowLNC) && ((!m_stereo) || (x < width/2 - m_windowLNC) || (x >= width/2 + m_windowLNC))) { int s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0; for (int yy = y - m_windowLNC; yy <= y + m_windowLNC; yy++) { for (int xx = x - m_windowLNC; xx <= x + m_windowLNC; xx++) { int p1 = ((*m_pImage1)(xx,yy) -m_image1MinValue) << (bitsUsed - m_image1BitsUsed); int p2 = ((*m_pImage2)(xx,yy) -m_image2MinValue) << (bitsUsed - m_image2BitsUsed); s1 += p1; s2 += p2; s3 += p1 * p1; s4 += p2 * p2; s5 += p1 * p2; } } double co = ((double)s5) - ((double)(s1 * s2)) / countLNC; double v1 = ((double)s3) - ((double)(s1 * s1)) / countLNC; double v2 = ((double)s4) - ((double)(s2 * s2)) / countLNC; // We omit the window if one of the variances is zero, as the // correlation value is undefined then. See my thesis for a further // description why this is allowed :-) if ((v2 != 0) && (v1 != 0)) { if (m_calculateLNC) m_similarityLNC += co / (sqrt(v1) * sqrt(v2)); if (m_calculateVWC) m_similarityVWC += v1 * co / (sqrt(v1) * sqrt(v2)); sumVWC += v1; sum7++; } } } } } // end of first run through the images // Pattern Intensity // If we're talkin' about stereo images, we run over the // left and right part of them separately. if (m_calculatePI){ for (int s = 0; s < (m_stereo? 2: 1); s++) { int w = m_stereo? width/2: width; for (int y = 0; y < height; y++) { for (int x = 0; x < w; x++) { for (int yy = y - m_radiusPI; yy <= y + m_radiusPI; yy++) { for (int xx = x - m_radiusPI; xx <= x + m_radiusPI; xx++) { if ((xx >= 0) && (xx < w) && (yy >= 0) && (yy < height) && ((x-xx)*(x-xx)+(y-yy)*(y-yy) <= m_radiusPI*m_radiusPI)) { if ((!m_useMask) || (((*m_pMask)(s*w+x,y)) && ((*m_pMask)(s*w+xx,yy)))) { double denom = (*m_pDiffImage)(s*w+x,y) - (*m_pDiffImage)(s*w+xx,yy); m_similarityPI += m_sigmaPI / (m_sigmaPI + denom*denom); sum6++; } } } } } } } } double mean1 = (double)sum1/(double)size; double mean2 = (double)sum2/(double)size; if (m_calculatePI) m_similarityPI /= (double)sum6; if (m_calculateLNC) m_similarityLNC /= (double)sum7; if (m_calculateVWC) m_similarityVWC /= sumVWC; if (m_calculateSSD) m_similaritySSD = (double)ssd/(double)size; if (m_calculateSAD) m_similaritySAD = (double)sad/(double)size; if (m_calculateNCC) { double var1 = 0, var2 = 0, corr = 0; /* image::Iterator<T, 2> it1( *m_pImage1 ); image::Iterator<T, 2> it2( *m_pImage2 ); for (it1.goToBegin(); !it1.isAtEnd(); it1++, it2++) { T pixel1 = (*it1 -m_image1MinValue) << (bitsUsed - m_image1BitsUsed); T pixel2 = (*it2 -m_image2MinValue) << (bitsUsed - m_image2BitsUsed); corr += (pixel1-mean1)*(pixel2-mean2); var1 += (pixel1-mean1)*(pixel1-mean1); var2 += (pixel2-mean2)*(pixel2-mean2); } */ corr = ((double)sum5) - ((double)(sum1 * sum2)) / (double)size; var1 = ((double)sum3) - ((double)(sum1 * sum1)) / (double)size; var2 = ((double)sum4) - ((double)(sum2 * sum2)) / (double)size; m_similarityNCC = corr / (sqrt(var1) * sqrt(var2)); } int histSize = 1 << m_histBits; // calculate mutual information if (m_calculateMI){ double p; for (int y = 0; y < histSize; y++) { p = ((double) m_phist1->fastGet(y)) / ((double) size); if (p > 0.0) m_entropy1 -= p * log(p); p = ((double) m_phist2->fastGet(y)) / ((double) size); if (p > 0.0) m_entropy2 -= p * log(p); for (int x = 0; x < histSize; x++) { p = ((double) m_pDistribution->fastGet(y,x)) / ((double) size); if (p > 0.0) m_entropy3 -= p * log(p); } } if (m_normalizeMI) { if (m_entropy1 + m_entropy2 > 0.0) m_similarityMI = 2 - 2 * m_entropy3 / (m_entropy1 + m_entropy2); } else m_similarityMI = m_entropy1 + m_entropy2 - m_entropy3; } /* calculate correlation ratio This measure is not symetric, therefore it makes a difference if the images are swapped! In this implementation, the first image is always the template image, i.e. it is seen as a base for the estimation of the second image. */ if (m_calculateCR) { int i, j; // calculate variance and expectation out of the second histogram double var = 0, exp = 0; for (j = 0; j < histSize; j++) exp += j * m_phist2->fastGet(j); exp /= (double)size; for (j = 0; j < histSize; j++) var += j * j * m_phist2->fastGet(j); var = (var / (double)size) - exp * exp; // variance of expectation of conditional probability of a certain intensity :-) double v1 = 0, v2, px, ex; for (i = 0; i < histSize; i++) { ex = 0; v2 = 0; px = m_phist1->fastGet(i) / (double)size; if (px > 0.0) { for (j = 0; j < histSize; j++) ex += j * m_pDistribution->fastGet(j, i); ex /= (px * (double)size); for (j = 0; j < histSize; j++) v2 += j * j * m_pDistribution->fastGet(j, i); v2 = (v2 / (px * (double)size)) - ex * ex; v1 += v2 * m_phist1->fastGet(i); } } v1 /= (var * (double)size); m_similarityCR = 1 - v1; } // gradient difference needs values from the correlation, too if ((m_calculateGC) || (m_calculateGD)) m_similarityGC = CalculateGradientCorrelation(); if (m_calculateGD) m_similarityGD = CalculateGradientDifference(); return true; // This is a totally weird idea that I have to try. Rank correlation. Let's go... double R[256], S[256]; double mean_r = 0, mean_s = 0, var1 = 0, var2 = 0, corr = 0; int sumh1 = 0, sumh2 = 0; // Omit black pixels for (int i = 1; i < histSize; i++) { int h1 = m_phist1->fastGet(i); int h2 = m_phist2->fastGet(i); R[i] = 0.5 * (double)(h1 + 1) + sumh1; S[i] = 0.5 * (double)(h2 + 1) + sumh2; sumh1 += h1; sumh2 += h2; mean_r += R[i] * (double)h1; mean_s += S[i] * (double)h2; } mean_r /= (double)histSize; mean_s /= (double)histSize; // And now run through the images! hs::image::Iterator<hs::image::Image<T, 2> > it1( *m_pImage1 ); hs::image::Iterator<hs::image::Image<T, 2> > it2( *m_pImage2 ); for (it1.goToBegin(); !it1.isAtEnd(); it1++, it2++) { T p1 = (*it1 - m_image1MinValue) << (bitsUsed - m_image1BitsUsed); T p2 = (*it2 - m_image2MinValue) << (bitsUsed - m_image2BitsUsed); if ((p1) && (p2)) { corr += (R[p1] - mean_r) * (S[p2] - mean_s); var1 += (R[p1] - mean_r) * (R[p1] - mean_r); var2 += (S[p2] - mean_s) * (S[p2] - mean_s); } } var1 = sqrt(var1) * sqrt(var2); m_similarityMI = 1.0 - (100000.0 * (var1 - corr) / var1); // End of this stupid experiment :-) return true; } template <typename T> double SimilarityMeasures<T>::CalculateGradientCorrelation() { int width = m_pGradientH1->getSize(0); int height = m_pGradientH1->getSize(1); // Same problem, long is 32 bit only. long sum1 = 0, sum2 = 0; double sum3 = 0, sum4 = 0, sum5 = 0; double corr, var1, var2; // set iterators image::IteratorPosition<image::Image<int, 2> > itH1( *m_pGradientH1 ); image::IteratorPosition<image::Image<int, 2> > itH2( *m_pGradientH2 ); image::IteratorPosition<image::Image<int, 2> > itV1( *m_pGradientV1 ); image::IteratorPosition<image::Image<int, 2> > itV2( *m_pGradientV2 ); // correlation of horizontal gradients for (; !itH1.isAtEnd(); itH1++, itH2++) { int x = itH1.getIndex()[0]; int y = itH1.getIndex()[1]; if (((!m_stereo) || (x < width/2 - 1) || (x > width/2)) && ((!m_useMask) || ((*m_pMaskGradient)(x,y)))) { sum1 += *itH1; sum2 += *itH2; sum3 += (*itH1) * (*itH1); sum4 += (*itH2) * (*itH2); sum5 += (*itH1) * (*itH2); } } corr = ((double)sum5) - ((double)(sum1 * sum2)) / (double)m_gradSize; var1 = ((double)sum3) - ((double)(sum1 * sum1)) / (double)m_gradSize; var2 = ((double)sum4) - ((double)(sum2 * sum2)) / (double)m_gradSize; m_varH1 = var1 / m_gradSize; m_varH2 = var2 / m_gradSize; double nccH = corr / (sqrt(var1) * sqrt(var2)); sum1 = 0; sum2 = 0; sum3 = 0; sum4 = 0; sum5 = 0; // correlation of vertical gradients for (; !itV1.isAtEnd(); itV1++, itV2++) { int x = itV1.getIndex()[0]; int y = itV1.getIndex()[1]; if (((!m_stereo) || (x < width/2 - 1) || (x > width/2)) && ((!m_useMask) || ((*m_pMaskGradient)(x,y)))) { sum1 += *itV1; sum2 += *itV2; sum3 += (*itV1) * (*itV1); sum4 += (*itV2) * (*itV2); sum5 += (*itV1) * (*itV2); } } corr = ((double)sum5) - ((double)(sum1 * sum2)) / (double)m_gradSize; var1 = ((double)sum3) - ((double)(sum1 * sum1)) / (double)m_gradSize; var2 = ((double)sum4) - ((double)(sum2 * sum2)) / (double)m_gradSize; m_varV1 = var1 / m_gradSize; m_varV2 = var2 / m_gradSize; double nccV = corr / (sqrt(var1) * sqrt(var2)); return (nccH + nccV) / 2; } template <typename T> double SimilarityMeasures<T>::CalculateGradientDifference() { int width = m_pGradientH1->getSize(0); int height = m_pGradientH1->getSize(1); double sum = 0; image::IteratorPosition<image::Image<int, 2> > itH1( *m_pGradientH1 ); image::IteratorPosition<image::Image<int, 2> > itH2( *m_pGradientH2 ); image::IteratorPosition<image::Image<int, 2> > itV1( *m_pGradientV1 ); image::IteratorPosition<image::Image<int, 2> > itV2( *m_pGradientV2 ); for (; !itH1.isAtEnd(); itH1++, itH2++) { int x = itH1.getIndex()[0]; int y = itH1.getIndex()[2]; if (((!m_stereo) || (x < width/2 - 1) || (x > width/2)) && ((!m_useMask) || ((*m_pMaskGradient)(x,y)))) { int diff = *itH1 - *itH2; sum += m_varH2 / (m_varH2 + diff*diff); } } for (; !itV1.isAtEnd(); itV1++, itV2++) { int x = itV1.getIndex()[0]; int y = itV1.getIndex()[1]; if (((!m_stereo) || (x < width/2 - 1) || (x > width/2)) && ((!m_useMask) || ((*m_pMaskGradient)(x,y)))) { int diff = *itV1 - *itV2; sum += m_varV2 / (m_varV2 + diff*diff); } } return sum / (2 * m_gradSize); } } } #endif
0369b709facf49cb4e60b4c9f086a9a1f385952f
3ab772f14d995b4f510590f9a27a71286b11152c
/GravityForce.cpp
bea44129d6e55b35f88fccf8e810e0d4d63a3e2e
[]
no_license
rveens/SICG-project2
381f432de50272fe291f6d48a4869126160ed681
57b0db578aad7334c9cb0dfc4564d8a3accbc14f
refs/heads/master
2021-03-24T12:35:31.437247
2016-07-30T04:26:20
2016-07-30T04:26:20
60,340,537
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
GravityForce.cpp
#include "GravityForce.h" #include "RigidBody.h" #include "Particle.h" #include "./Eigen/Dense" GravityForce::GravityForce(std::shared_ptr<SolverInterface> obj) : m_obj(obj) { } GravityForce::~GravityForce() { } void GravityForce::calculateForce() { // test: std::shared_ptr<RigidBody> rb = std::dynamic_pointer_cast<RigidBody>(m_obj); if (rb != nullptr) { rb->m_Force[1] += -rb->m_Mass * m_g * 2; } std::shared_ptr<Particle> p = std::dynamic_pointer_cast<Particle>(m_obj); if (p != nullptr) { p->m_Force[1] += -p->m_Mass * m_g; } } void GravityForce::draw() { // TODO }
011b19eff8de4767145ee0bad525893f32414657
8cce470b76f4e5d3cf6cdd734050aae6a938f71d
/headerfilesZZ/Electron.cc
0abba56d8783ecee1e49061244c25e5277acb58b
[]
no_license
daniSchaefer/AdditionToExoDiBosonAnalysis-
fab54c77688fcd4d1bbd62b236ec46148b247a4f
1bbafa7756c88200738cb0f1e1dbbf5396e83964
refs/heads/master
2021-01-20T22:29:13.135101
2016-07-20T11:00:46
2016-07-20T11:00:46
61,705,799
0
0
null
null
null
null
UTF-8
C++
false
false
3,629
cc
Electron.cc
#include "TMath.h" #include "ZZtree.h" #include "RecParticle.h" #include <iostream> #include "Electron.h" #include "ZZConstants.h" Electron::Electron(int index, ZZtree* tree) { int indexRange = tree->nEle; Set_IndexMax(indexRange); Set_EventID(tree->eventId); Set_Index(index); Set_pdgId(11); hlt_nTrigs_ = tree->hlt_nTrigs; hlt_trigResult_ = tree->hlt_trigResult; hlt_trigName_ = tree->hlt_trigName; Init(index,tree); } Electron::Electron(ZZtree* tree) { Set_EventID( tree->eventId); Set_pdgId(11); Set_IndexMax(tree->nEle); hlt_nTrigs_ = tree->hlt_nTrigs; hlt_trigResult_ = tree->hlt_trigResult; hlt_trigName_ = tree->hlt_trigName; } Electron::~Electron() { } void Electron::Init(int index, ZZtree* tree) { Set_Index( index); int indexRange = Get_IndexMax(); if(index<indexRange) { TLorentzVector *v = dynamic_cast<TLorentzVector*>(tree->eleP4->At(index)); SetLV(*v); Set_Charge(tree->eleCharge->at(index)); miniIso_ = tree->eleMiniIsoEA->at(index); HoverE_ = tree->eleHoverE->at(index); isHEEPNoIso_ = tree->eleIsPassHEEPNoIso->at(index); isHEEP_ = tree->eleIsPassHEEP->at(index); isLoose_ = tree->eleIsPassLoose->at(index); isLooseNoIso_ = tree->eleIsPassLooseNoIso->at(index); SuperClusterEta_ = tree->eleScEta->at(index); } else { std::cout << "in electron constructor in " << Get_EventID() <<" index out of range "<< std::endl; } } // void ~Electron(); void Electron::Set_Trigger(const char* trigger_name){trigger_ = trigger_name;} void Electron::Set_TrackIso(Double_t iso){trackIso_ = iso;} void Electron::Set_miniIso(Double_t iso){miniIso_ = iso;} void Electron::Set_HoverE(Double_t HoverE){HoverE_ = HoverE;} void Electron::Set_HEEPNoIso(bool isHEEP){isHEEPNoIso_ = isHEEP;} void Electron::Set_HEEP(bool isHEEP){isHEEP_ = isHEEP;} void Electron::Set_LooseNoIso(bool isTrue){isLooseNoIso_ = isTrue;} void Electron::Set_Loose(bool isTrue){isLoose_ = isTrue;} void Electron::Set_SuperClusterEta(Double_t eta){SuperClusterEta_ = eta;} const char* Electron::Get_Trigger() const{return trigger_;} Double_t Electron::Get_TrackIso() const {return trackIso_;} Double_t Electron::Get_miniIso() const {return miniIso_;} Double_t Electron::Get_HoverE() const {return HoverE_;} bool Electron::Get_HEEPNoIso() const {return isHEEPNoIso_;} bool Electron::Get_HEEP() const {return isHEEP_;} bool Electron::Get_LooseNoIso() const {return isLooseNoIso_;} bool Electron::Get_Loose() const {return isLoose_;} Double_t Electron::Get_SuperClusterEta() const {return SuperClusterEta_;} int Electron::passedID() { int isPassed =0; //if(isHEEPNoIso_) {isPassed = 1;} if(Get_LooseNoIso()){isPassed =1;} return isPassed; } int Electron::passedTrigger() { bool passedTrig = 0; //debug if(hlt_nTrigs_ != hlt_trigResult_->size()) std::cout <<" look at function passedTrigger "<< endl; for(int i=0;i<hlt_nTrigs_;i++) { if((hlt_trigName_->at(i)).find(trigger_)== std::string::npos) continue; passedTrig = hlt_trigResult_->at(i); break; } return passedTrig; } int Electron::passedKinematicCuts() { Double_t pt = (GetLV()).Pt(); Double_t eta = Get_SuperClusterEta(); bool passedKin = 0; if(((TMath::Abs(eta)< ZZELEETA /*and TMath::Abs(eta)> ZZELEECALGAPMAX) or (TMath::Abs(eta)<ZZELEECALGAPMIN*/ and TMath::Abs(eta)>0)) and pt> ZZELEPT) passedKin=1; return passedKin; } //value here from Eikos function ! int Electron::passedIsolation() { bool passedIso = 0; if(miniIso_<=0.1) passedIso =1; return passedIso; }
ae3bc758ac9b3036d24fae743ffbaafa0e9cc486
e096e1c0b12ed91c673e0bb280ec161e4e495db4
/nRF52832/arduino/arduino-1.8.0/hardware/RBL/RBL_nRF52832/cores/RBL_nRF52832/wiring_analog.cpp
54d6fb395696424ff25f84a84e147e48c6e018d7
[]
no_license
MicaiahReid/nRF5x
177d44cd019b87c7e3c421704a7684c4ee97880a
13553908e45e622d60433ca08be5904c9a10ba4e
refs/heads/master
2021-08-21T20:58:56.350288
2017-11-27T12:29:34
2017-11-27T12:29:34
115,740,965
1
0
null
2017-12-29T17:20:37
2017-12-29T17:20:37
null
UTF-8
C++
false
false
11,360
cpp
wiring_analog.cpp
/************************************************************************//** * @file wiring_analog.c * * @version 1.0.0 * * @author RedBearLab * * @date 2016/11/10 * * @brief Main body of the project. * * @copyright Copyright (c) 2012-2016 RedBearLab * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /**************************************************************************** * HEADER FILES ****************************************************************************/ #include <math.h> #include "Arduino.h" #include "wiring_analog.h" /**************************************************************************** * MACRO DEFINITIONS ****************************************************************************/ #define PWM_MAX_NUM 3 #define PWM_PERIOD_US 100 /**************************************************************************** * GLOBAL VARIABLES ****************************************************************************/ /**************************************************************************** * LOCAL VARIABLES ****************************************************************************/ /** * @brief DMA RAM, store the ADC value */ static int16_t saadc_value; /** * @brief Resolution */ static uint8_t readResolution = DEFAULT_READ_RESOLUTION; static uint8_t writeResolution = DEFAULT_WRITE_RESOLUTION; /** * @brief Reference */ static uint32_t saadReference = SAADC_CH_CONFIG_REFSEL_VDD1_4; /** * @brief PWM */ static pwmout_t pwm_instance[PWM_MAX_NUM] = { {(PWMName)0, (PinName)NC, 0, NULL}, {(PWMName)0, (PinName)NC, 0, NULL}, {(PWMName)0, (PinName)NC, 0, NULL} }; /**************************************************************************** * LOCAL FUNCTION PROTOTYPES ****************************************************************************/ static uint8_t getMatchChannel(PinName pin); static uint8_t getFreeChannel(void); /**************************************************************************** * FUNCTION ACHIEVMENT ****************************************************************************/ static inline uint32_t conversionResolution(uint32_t value, uint32_t from, uint32_t to) { if (from == to) return value; if (from > to) return value >> (from-to); else return value << (to-from); } void analogReadResolution(uint8_t resolution) { readResolution = resolution; } void analogWriteResolution(uint8_t resolution) { writeResolution = resolution; } void analogReference(eAnalogReference_t type) { switch(type) { case REFSEL_INTERNAL: saadReference = SAADC_CH_CONFIG_REFSEL_Internal; break; case REFSEL_VDD1_4: saadReference = SAADC_CH_CONFIG_REFSEL_VDD1_4; break; default: saadReference = SAADC_CH_CONFIG_REFSEL_VDD1_4; break; } } uint32_t analogRead(uint8_t pin) { PinName nrf_pin; uint32_t saadcResolution; uint32_t resolution; uint32_t config_gain = SAADC_CH_CONFIG_GAIN_Gain1_4; uint32_t pselp = SAADC_CH_PSELP_PSELP_NC; nrf_pin = Pin_Arduino_to_nRF52(pin); switch( nrf_pin ) { case 2 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput0; break; case 3 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput1; break; case 4 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput2; break; case 5 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput3; break; case 28 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput4; break; case 29 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput5; break; case 30 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput6; break; case 31 : pselp = SAADC_CH_PSELP_PSELP_AnalogInput7; break; default : return 0; } // if(readResolution <= 8) { resolution = 8; saadcResolution = SAADC_RESOLUTION_VAL_8bit; } else if(readResolution <= 10) { resolution = 10; saadcResolution = SAADC_RESOLUTION_VAL_10bit; } else if(readResolution <= 12) { resolution = 12; saadcResolution = SAADC_RESOLUTION_VAL_12bit; } else { resolution = 14; saadcResolution = SAADC_RESOLUTION_VAL_14bit; } // Set the resolution NRF_SAADC->RESOLUTION = saadcResolution; // Bypass oversampling NRF_SAADC->OVERSAMPLE = (SAADC_OVERSAMPLE_OVERSAMPLE_Bypass << SAADC_OVERSAMPLE_OVERSAMPLE_Pos); // Disable all interrupts NRF_SAADC->INTENCLR = 0xFFFFFFFF; // Clear event flag NRF_SAADC->EVENTS_END = 0; NRF_SAADC->EVENTS_DONE = 0; // Enable NRF_SAADC. NRF_SAADC->ENABLE = (SAADC_ENABLE_ENABLE_Enabled << SAADC_ENABLE_ENABLE_Pos); for (int i = 0; i < 8; i++) { NRF_SAADC->CH[i].PSELN = SAADC_CH_PSELP_PSELP_NC; NRF_SAADC->CH[i].PSELP = SAADC_CH_PSELP_PSELP_NC; } // Input range = (+- 0.6 V or +-VDD/4)/Gain // RESULT = [V(P) – V(N) ] * GAIN/REFERENCE * 2^(RESOLUTION - m) // If CONFIG.MODE=SE,m=0 or if CONFIG.MODE=Diff,m=1. if(saadReference == SAADC_CH_CONFIG_REFSEL_Internal) { // Reference is Internal 0.6V, Input valtage is 0~3.6V config_gain = SAADC_CH_CONFIG_GAIN_Gain1_6; } else if(saadReference == SAADC_CH_CONFIG_REFSEL_VDD1_4) { // Reference is VDD, Input valtage is 0~VDD config_gain = SAADC_CH_CONFIG_GAIN_Gain1_4; } NRF_SAADC->CH[0].CONFIG = ( (SAADC_CH_CONFIG_RESP_Bypass << SAADC_CH_CONFIG_RESP_Pos) | //Positive channel resistor control:Bypass resistor ladder. (SAADC_CH_CONFIG_RESP_Bypass << SAADC_CH_CONFIG_RESN_Pos) | //Negative channel resistor control:Bypass resistor ladder. (config_gain << SAADC_CH_CONFIG_GAIN_Pos) | //Gain control (saadReference << SAADC_CH_CONFIG_REFSEL_Pos) | //Reference (SAADC_CH_CONFIG_TACQ_10us << SAADC_CH_CONFIG_TACQ_Pos) | //Acquisition time:ADC uses to sample the input voltage. (SAADC_CH_CONFIG_MODE_SE << SAADC_CH_CONFIG_MODE_Pos) | //Single ended, PSELN will be ignored, negative input to ADC shorted to GND. (SAADC_CH_CONFIG_BURST_Disabled << SAADC_CH_CONFIG_BURST_Pos) //Disable burst mode(normal operation). ); NRF_SAADC->CH[0].PSELN = SAADC_CH_PSELP_PSELP_NC; NRF_SAADC->CH[0].PSELP = pselp; // Set DMA RAM. saadc_value = 0; NRF_SAADC->RESULT.PTR = (uint32_t)&saadc_value; NRF_SAADC->RESULT.MAXCNT = 1; //Only one sample. // Start SAADC. NRF_SAADC->TASKS_START = 1; while(!NRF_SAADC->EVENTS_STARTED); NRF_SAADC->EVENTS_STARTED = 0; // Start sample. NRF_SAADC->TASKS_SAMPLE = 1; while(!NRF_SAADC->EVENTS_END); NRF_SAADC->EVENTS_END = 0; // Stop SAADC. NRF_SAADC->TASKS_STOP = 1; while(!NRF_SAADC->EVENTS_STOPPED); NRF_SAADC->EVENTS_STOPPED = 0; // If value < 0, set value to zero. if(saadc_value < 0) saadc_value = 0; // Disable SAADC. NRF_SAADC->ENABLE = (SAADC_ENABLE_ENABLE_Disabled << SAADC_ENABLE_ENABLE_Pos); return conversionResolution(saadc_value, resolution, readResolution); } void analogWrite(uint8_t pin, uint32_t value) { uint8_t index; PinName nrf_pin; nrf_pin = Pin_Arduino_to_nRF52(pin); MBED_ASSERT(nrf_pin != (PinName)NC); // Check channel index = getMatchChannel(nrf_pin); if(index < 3) { // if(value == 0) { ////Free pwm // core_util_critical_section_enter(); // pwmout_free(&pwm_instance[index]); // core_util_critical_section_exit(); // pwm_instance[index].pin = (PinName)NC; // pinMode(pin, OUTPUT); // digitalWrite(pin, LOW); // return; // } // This pin has been attached to PWM uint32_t value_8bit; float duty; value_8bit = conversionResolution(value, writeResolution, 8); duty = (float)value_8bit / 255; // Update duty core_util_critical_section_enter(); pwmout_write(&pwm_instance[index], duty); core_util_critical_section_exit(); } else { uint8_t ch; // Get a free channel ch = getFreeChannel(); if(ch >= 3) return; // If value=0, set pin to LOW // if(value == 0) { // pinMode(pin, OUTPUT); // digitalWrite(pin, LOW); // return; // } // Init pwm module core_util_critical_section_enter(); pwmout_init(&pwm_instance[ch], nrf_pin); pwmout_period_us(&pwm_instance[ch], PWM_PERIOD_US); core_util_critical_section_exit(); // Update duty uint32_t value_8bit; float duty; value_8bit = conversionResolution(value, writeResolution, 8); duty = (float)value_8bit / 255; core_util_critical_section_enter(); pwmout_write(&pwm_instance[ch], duty); core_util_critical_section_exit(); } } void analogFree(uint8_t pin) { uint8_t index; PinName nrf_pin; nrf_pin = Pin_Arduino_to_nRF52(pin); MBED_ASSERT(nrf_pin != (PinName)NC); index = getMatchChannel(nrf_pin); if(index < 3) { //Free pwm core_util_critical_section_enter(); pwmout_free(&pwm_instance[index]); core_util_critical_section_exit(); pwm_instance[index].pin = (PinName)NC; pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } } static uint8_t getMatchChannel(PinName pin) { uint8_t index; for(index=0; index<PWM_MAX_NUM; index++) { if(pwm_instance[index].pin == pin) return index; } return 0xFF; } static uint8_t getFreeChannel(void) { uint8_t index; for(index=0; index<PWM_MAX_NUM; index++) { if(pwm_instance[index].pin == (PinName)NC) return index; } return 0xFF; } /**************************************************************************** * END OF FILE ****************************************************************************/
def7dbf1f3750d49483f79035ca1e9cf76c7da7a
a7d2ea3da40fc0590218acdf14286a0553102e97
/algorithm/洛谷/1616.cpp
9b28face42be90b46063f200b891b192d6e4fb2e
[]
no_license
wust-lzy/vscode_project
58855bb4aa9ee5699f02c88ee6ad08eaa00459f9
8f6d8e661e284c7f2c3164dd39730404e7a02d58
refs/heads/master
2023-03-23T10:52:26.238726
2021-03-23T03:46:57
2021-03-23T03:46:57
331,944,454
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
1616.cpp
#include<iostream> using namespace std; typedef long long ll; ll n, v, w[10005], val[10005], i, j; ll f[10000005]; int main() { cin >> v >> n; for (i = 1; i <= n;i++) cin >> w[i] >> val[i]; for (i = 1; i <= n;i++) { for (j = w[i]; j <= v;j++) { f[j] = max(f[j], f[j - w[i]] + val[i]); } } cout << f[v]; return 0; }
3e11ca5a63dfedd47c6007862cce6205bdfbfbc0
9c82da9c4dc99441ac3b760e8578dd14ae15584b
/XPSLib.CPP/XPSLib.cpp
0295aa1bb3a0512a5fe96af8ecc5048d01688db8
[]
no_license
saifkhan04/XPSEditor
cd4dddc1694dce668e7434ce5f865464c621fb55
682cb57dbb776a85bc60fc74228d8765dbc66e45
refs/heads/master
2022-09-28T01:08:00.534974
2020-04-25T02:15:56
2020-04-25T02:15:56
258,664,333
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
XPSLib.cpp
#include "stdafx.h" #include "XPSLib.h" HRESULT XPSLib::Cpp::XPSApi::CreateDefaultXPSFile() const { HRESULT hr = S_OK; IXpsOMObjectFactory1_t xpsFactory(NULL); IXpsOMPackage1_t xpsPackage(NULL); hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { hr = CoCreateInstance( __uuidof(XpsOMObjectFactory), NULL, CLSCTX_INPROC_SERVER, __uuidof(IXpsOMObjectFactory1_t), reinterpret_cast<LPVOID*>(&xpsFactory)); } hr = xpsFactory->CreatePackageFromFile1( L"C:\\Users\\khansai\\Desktop\\test.xps", FALSE, &xpsPackage); hr = xpsPackage->WriteToFile( L"C:\\Users\\khansai\\Desktop\\output.xps", NULL, // LPSECURITY_ATTRIBUTES FILE_ATTRIBUTE_NORMAL, FALSE // Optimize Markup Size ); return hr; }
816c066203413da362aa3d7d3d95bdfdab0e14a7
31fd0e5c214734ad9be2caf48c8bd7af3e7cbb2d
/STL_GENERATOR/main.cpp
78d3de5717919d571f2d6511e2048d7062119ad2
[ "MIT" ]
permissive
the-astronot/Project-Icarus
9d6b4c67553dc5a7d867ebf6740086af97ee8b40
a821f3ec1add745d014ec5b3c32a46a6064e4fda
refs/heads/master
2022-12-24T18:11:47.507127
2020-09-29T06:44:58
2020-09-29T06:44:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,263
cpp
main.cpp
#include <fstream> #include <iostream> #include <vector> #include <cmath> #include <algorithm> #include "Triangle.h" #include "Plane.h" #include "Vertex.h" #include "Model.h" #include "MultiModel.h" #include "Shapes.h" typedef unsigned int uint; Model* ReadIn(std::string infile); void slicer(Model* &model, bool sliceY); void meshGen(Model* &model); void stlWriter(Model* first_model, std::string fileName); void printUpdate(int num, float den); int main(int argc, char* argv[]) { // BASIC SHAPES GENERATOR Model* first_model; bool answer; uint n, m; n=1; m=2; std::vector<Model*> models; std::string fileName = argv[1]; std::string input = argv[2]; first_model = ReadIn(input); Model* main_model = first_model; Model* current_model = main_model->next; while(main_model->next != NULL) { while (current_model != NULL) { answer = checkForCollision(main_model, current_model); if (answer) {std::cout << n << "," << m << std::endl;} current_model = current_model->next; m++; } main_model = main_model->next; current_model = main_model->next; n++; m = n+1; } // MULTIMODEL ATTEMPT MultiModel* mmodel = new MultiModel(first_model); mmodel->removeUnnecessary(); mmodel->slicer(); mmodel->simplifyGeometry(); mmodel->meshGen(); mmodel->stlWriter(fileName); std::cout << "================== " << std::endl; std::cout << "Writing to File... " << std::endl; stlWriter(first_model, fileName); std::cout << "Completed " << std::endl; main_model = first_model; while(main_model->next != NULL) { current_model = main_model; main_model = main_model->next; delete current_model; } delete main_model; } Model* ReadIn(std::string infile) { double x, y, z, delta, radius, delx, dely, delz; bool hole; Model* first = NULL; Model* current = NULL; Model* last = NULL; Vertex origin; std::string job_num; std::ifstream INFILE("../Input_files/" + infile); INFILE >> job_num; INFILE >> job_num; std::cout << "======================" << std::endl; std::cout << "/// PROJECT_ICARUS \\\\\\" << std::endl; std::cout << "======================" << std::endl; std::cout << "= JOB_" << job_num << " =" << std::endl; std::cout << "======================" << std::endl; // Load in all the shapes from the file std::string name, hole_str; while (INFILE >> name && name != "END") { // SPHERE CREATION if (name == "SPHERE") { std::cout << name << " \n===========" << std::endl; INFILE >> x >> y >> z >> radius >> delta >> hole_str; if (hole_str == "false" || hole_str == "FALSE") {hole = false;} else {hole = true;} origin = Vertex(x, y, z); current = new Model(origin, hole); std::cout << "Generating Vertices... " << std::endl; sphereGen(current, radius, delta); std::cout << "Slicing... " << std::endl; slicer(current, false); std::cout << "Generating Mesh... " << std::endl; meshGen(current); if (first == NULL) {first = current;} if (last != NULL) {last->next = current;} last = current; // CUBE CREATION } if (name == "CUBE") { std::cout << name << " \n===========" << std::endl; INFILE >> x >> y >> z >> delx >> delta >> hole_str; if (hole_str == "false" || hole_str == "FALSE") {hole = false;} else {hole = true;} origin = Vertex(x, y, z); current = new Model(origin, hole); std::cout << "Generating Vertices... " << std::endl; cubeGen(current, delx, delta); std::cout << "Slicing... " << std::endl; slicer(current, true); std::cout << "Generating Mesh... " << std::endl; meshGen(current); if (first == NULL) {first = current;} if (last != NULL) {last->next = current;} last = current; // RECTANGLE CREATION } if (name == "RECT") { std::cout << name << " \n===========" << std::endl; INFILE >> x >> y >> z >> delx >> dely >> delz >> delta >> hole_str; if (hole_str == "false" || hole_str == "FALSE") {hole = false;} else {hole = true;} origin = Vertex(x, y, z); current = new Model(origin, hole); std::cout << "Generating Vertices... " << std::endl; rectGen(current, delx, dely, delz, delta); std::cout << "Slicing... " << std::endl; slicer(current, true); std::cout << "Generating Mesh... " << std::endl; meshGen(current); if (first == NULL) {first = current;} if (last != NULL) {last->next = current;} last = current; } } return first; } void slicer(Model* &model, bool sliceY) { int first = 0; int last = 0; uint p = 0; // Slice X Plane cur_plane; model->sortByX(); uint size = model->getNumVertices(); double x = model->getVertices(0)->getX(); for(uint i=1; i<=size; i++) { if (i == size) { std::vector<Vertex*> current; for (int j=first; j<=last; j++) { current.push_back(model->getVertices(j)); } cur_plane = Plane(current, p); model->addXPlane(cur_plane); } else if (model->getVertices(i)->getX() == x) { last = i; } else { std::vector<Vertex*> current; for (int j=first; j<=last; j++) { current.push_back(model->getVertices(j)); } cur_plane = Plane(current, p); p++; model->addXPlane(cur_plane); first = i; last = i; x = model->getVertices(i)->getX(); } printUpdate(i, size); } if (sliceY) { // Now Slice Y model->sortByY(); double y = model->getVertices(0)->getY(); first = 0; last = 0; for(uint i=1; i<=size; i++) { if (i == size) { std::vector<Vertex*> current; for (int j=first; j<=last; j++) { current.push_back(model->getVertices(j)); } cur_plane = Plane(current, p); model->addYPlane(cur_plane); } else if (model->getVertices(i)->getY() == y) { last = i; } else { std::vector<Vertex*> current; for (int j=first; j<=last; j++) { current.push_back(model->getVertices(j)); } cur_plane = Plane(current, p); p++; model->addYPlane(cur_plane); first = i; last = i; y = model->getVertices(i)->getY(); } } } } void meshGen(Model* &model) { Triangle newT; Vertex *nextHigh, *nextLow; bool endLow, endHigh, nextIsLow; int num1, num2; int tot = 0; uint size = model->getNumXPlanes(); for (uint i=1; i<size; i++) { Plane p1 = model->getPlaneX(i-1); Plane p2 = model->getPlaneX(i); endLow = false; endHigh = false; num1 = 1; num2 = 1; if (p1.getNumVert() > 1) {nextLow = p1.getVertex(1);} else {endLow = true;} if (p2.getNumVert() > 1) {nextHigh = p2.getVertex(1);} else {endHigh = true;} // Choose next Vertex for Triangle while (!endLow || !endHigh) { if (!endLow && !endHigh) { if (nextLow->getTheta() >= nextHigh->getTheta()) { nextIsLow=true; } else { nextIsLow=false; } } else if (!endLow) { nextIsLow=true; } else { nextIsLow=false; } // Create New Triangle if (nextIsLow) { if (!model->isAHole()) { newT = Triangle(nextLow, p1.getVertex(num1-1), p2.getVertex(num2-1), tot); } else { newT = Triangle(nextLow, p2.getVertex(num1-1), p1.getVertex(num2-1), tot); } num1++; } else { if (!model->isAHole()) { newT = Triangle(nextHigh, p1.getVertex(num1-1), p2.getVertex(num2-1), tot); } else { newT = Triangle(nextHigh, p2.getVertex(num1-1), p1.getVertex(num2-1), tot); } num2++; } model->addTriangle(newT); tot++; if (p1.getNumVert() > num1) {nextLow = p1.getVertex(num1);} else {endLow = true;} if (p2.getNumVert() > num2) {nextHigh = p2.getVertex(num2);} else {endHigh = true;} } // Clean Up Last 2 Triangles if (p1.getNumVert() > 1) { if (!model->isAHole()) { newT = Triangle(p1.getVertex(0), p1.getVertex(num1-1), p2.getVertex(num2-1), tot); } else { newT = Triangle(p1.getVertex(0), p2.getVertex(num1-1), p1.getVertex(num2-1), tot); } tot++; num1 = 1; model->addTriangle(newT); } if (p2.getNumVert() > 1) { if (!model->isAHole()) { newT = Triangle(p2.getVertex(0), p1.getVertex(num1-1), p2.getVertex(num2-1), tot); } else { newT = Triangle(p2.getVertex(0), p2.getVertex(num1-1), p1.getVertex(num2-1), tot); } tot++; num2 = 1; model->addTriangle(newT); } printUpdate(i, size); } // Y Mesh Gen if (model->getNumYPlanes() != 0) { size = model->getNumYPlanes(); for (uint i=1; i<size; i++) { Plane p1 = model->getPlaneY(i-1); Plane p2 = model->getPlaneY(i); //std::cout << p2.getVertex(0)->getY() << std::endl; endLow = false; endHigh = false; num1 = 1; num2 = 1; if (p1.getNumVert() > 1) {nextLow = p1.getVertex(1);} else {endLow = true;} if (p2.getNumVert() > 1) {nextHigh = p2.getVertex(1);} else {endHigh = true;} // Choose next Vertex for Triangle while (!endLow || !endHigh) { if (!endLow && !endHigh) { if (nextLow->getOmega() >= nextHigh->getOmega()) { nextIsLow=true; } else { nextIsLow=false; } } else if (!endLow) { nextIsLow=true; } else { nextIsLow=false; } // Create New Triangle if (nextIsLow) { newT = Triangle(nextLow, p1.getVertex(num1-1), p2.getVertex(num2-1), tot); num1++; } else { newT = Triangle(nextHigh, p1.getVertex(num1-1), p2.getVertex(num2-1), tot); num2++; } model->addTriangle(newT); tot++; if (p1.getNumVert() > num1) {nextLow = p1.getVertex(num1);} else {endLow = true;} if (p2.getNumVert() > num2) {nextHigh = p2.getVertex(num2);} else {endHigh = true;} } // Clean Up Last 2 Triangles if (p1.getNumVert() > 1) { newT = Triangle(p1.getVertex(0), p1.getVertex(num1-1), p2.getVertex(num2-1), tot); tot++; num1 = 1; model->addTriangle(newT); } if (p2.getNumVert() > 1) { newT = Triangle(p2.getVertex(0), p1.getVertex(num1-1), p2.getVertex(num2-1), tot); tot++; num2 = 1; model->addTriangle(newT); } } } } void stlWriter(Model* first_model, std::string fileName){ std::ofstream STLFILE("../STLs/" + fileName + ".stl"); Model* current_model = first_model; Triangle triangle; Vertex* vertex; uint size; bool end = false; uint total_size = 0; uint m = 0; if (current_model == NULL) {end=true;} while (!end) { total_size += current_model->getMeshSize(); if (current_model->next == NULL) {end=true;} current_model = current_model->next; } std::cout << total_size << std::endl; current_model = first_model; end = false; if (current_model == NULL) {end=true;} //STLFILE << "solid Sphere_Model\n"; while (!end) { STLFILE << "solid Sphere_Model\n"; size = current_model->getMeshSize(); // Add all Triangles for(uint i=0; i<size; i++,m++) { triangle = current_model->getMesh(i); STLFILE << "\tfacet normal " << triangle.getNx() << " " << triangle.getNy() << " " << triangle.getNz() << "\n"; STLFILE << "\t\touter loop \n"; for (int j=0; j<3; j++) { vertex = current_model->getMesh(i).get(j); STLFILE << "\t\t\tvertex " << vertex->getX() << " " << vertex->getY() << " " << vertex->getZ() << "\n"; } STLFILE << "\t\tendloop\n"; STLFILE << "\tendfacet\n"; printUpdate(m, total_size); } STLFILE << "endsolid Sphere_Model\n"; if (current_model->next == NULL) {end=true;} current_model = current_model->next; } STLFILE.close(); }
acde785fb85061cab4a988b0de9576bd400951f6
190b0c992b9564cf090033feab46c560924c5405
/stackNqueue/reverseQueue.cpp
72a38bbfaad0dc94de3e3a461ebb739d3e05f92f
[]
no_license
mjcmd/dsAlgoCpp
456a954083214e4e19120a01508cde35550a5832
79ca90f3a1049cce416064860289f4411580f913
refs/heads/main
2022-12-28T11:37:27.244701
2020-10-09T14:02:49
2020-10-09T14:02:49
302,645,732
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
reverseQueue.cpp
#include<bits/stdc++.h> #include<queue> #include<stack> using namespace std; void reverseQueueUsingStack(queue<int>&q); void reverseQueueRec(queue<int>& q); void input(queue<int>& q) { int k; cin>>k; while(k!=-1) { q.push(k); cin>>k; } } void print(queue<int> q) { while(!q.empty()) { cout<<q.front()<<" "; q.pop(); } } int main() { queue<int> q; input(q); reverseQueueRec(q); //reverseQueueUsingStack(q); print(q); return 0; } void reverseQueueRec(queue<int>& q) { if(q.empty()) { return; } int f=q.front(); q.pop(); reverseQueueRec(q); q.push(f); } void reverseQueueUsingStack(queue<int>&q) //using a stack { stack<int> s; while(!q.empty()) { s.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } }
3dcbe6da2a5b8daf5aa4eb4adb0e872f425f165e
3e67673040276a495235bb704e73738db44cea04
/uva00524.cpp
5ad6f4d3ca53aa9218b1e2d79ddb82d2582eacce
[]
no_license
f26401004/UVA_practice
33e6a31c73a8707a6f7668da91de5d8dd43f1c3b
f141c5b6d1b7aaaa74d338db647a27185d74d3f5
refs/heads/master
2018-09-10T21:08:08.102288
2018-06-20T10:06:14
2018-06-20T10:06:14
104,219,982
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
uva00524.cpp
#include <iostream> #include <cstring> using namespace std; bool prime[17]; int N; bool visited[17]; void makePrime() { memset(prime, false, sizeof(prime)); prime[2] = prime[3] = prime[5] = prime[7] = prime[11] = prime[13] = prime[17] = prime[19] = prime[23] = prime[29] = prime[31] = prime[37] = prime[41] = prime[43] =true; } void backtracking(int *array, int index, int num) { array[index] = num; if (index == N - 1) { if (!prime[array[0] + array[index]]) return; cout << array[0]; for(int i = 1 ; i < N ; ++i) cout << " " << array[i]; cout << endl; } for(int i = 2 ; i < N + 1 ; ++i) { if (visited[i]) continue; if (prime[i + array[index]]) { visited[i] = true; backtracking(array, index + 1, i); visited[i] = false; } } } int main() { int case_num = 0; makePrime(); while(cin >> N) { int array[N]; if (case_num++) cout << endl; memset(array, 0, sizeof(array)); memset(visited, false, sizeof(visited)); cout << "Case " << case_num << ":" << endl; backtracking(array, 0, 1); } return 0; }
79e8f7fcfc96c43e958022c541628969bfb60714
62079794dc63cfef35f4762af4c9cec1de4f3be8
/sample/source/ui_ctrl_ex/value_sub_ctrl.cpp
7890dcc24745567d557e76c2963cc55eb84a0638
[ "Apache-2.0", "MIT" ]
permissive
Crawping/GuiLiteAll
a5f23b7e880b8d2be618bcc5f7d5ac18c5ba29e8
fc993203476e3987bb4d820ce8d09cb19651ed05
refs/heads/master
2021-07-11T14:56:28.235055
2017-10-16T02:38:29
2017-10-16T02:38:29
107,769,779
2
0
null
2017-10-21T10:03:17
2017-10-21T10:03:17
null
UTF-8
C++
false
false
1,653
cpp
value_sub_ctrl.cpp
#include "../core_include/api.h" #include "../core_include/rect.h" #include "../core_include/cmd_target.h" #include "../core_include/wnd.h" #include "../core_include/surface.h" #include "../core_include/resource_type.h" #include "../core_include/word.h" #include "../gui_include/shape_resource.h" #include "../source/manager/value_manager.h" #include "value_ctrl.h" #include "value_sub_ctrl.h" void c_value_sub_ctrl::on_paint(void) { c_rect rect; get_screen_rect(rect); fill_rect(rect.m_left,rect.m_top,rect.m_right,rect.m_bottom,m_bg_color); c_word *p = c_word::get_instance(m_z_order, m_surface); //show name p->set_font(m_name_font_type); p->set_color(m_name_color, m_bg_color); p->draw_string(m_name_id, rect.m_left + 1, rect.m_top); //show value p->set_font(m_value_font_type); p->set_color(m_name_color, m_bg_color); m_value_rect.m_left = rect.m_left + 32; m_value_rect.m_top = rect.m_top + (rect.Height() - p->get_font_ysize(m_value_font_type)) / 2; if (m_value_rect.m_top < rect.m_top) { m_value_rect.m_top = rect.m_top + 2; } int strLen = p->get_str_pixel_length(p->get_string(m_high_limit, m_limit_dot_position)); m_value_rect.m_right = m_value_rect.m_left + strLen; if (m_value_rect.m_right > rect.m_right) { m_value_rect.m_right = rect.m_right - 2; } m_value_rect.m_bottom = m_value_rect.m_top + p->get_font_ysize(m_value_font_type); if (m_value_rect.m_bottom > rect.m_bottom) { m_value_rect.m_bottom = rect.m_bottom - 2; } value_2_string(m_value, m_value_in_str, m_limit_dot_position); m_max_value_rect = m_value_rect; p->draw_string_in_rect(m_value_in_str, m_value_rect, m_value_align_type); }
58a4920c50c08b8800bc5a95bd13e17bb2a93cd5
d4949a195e39c57bc9d67bd7ced80a4227cce63e
/cpp/dice.cpp
3db2e040591986e91681a2b394acea4324d5fdf9
[ "Unlicense" ]
permissive
crithead/misc-tools
cce2f6f637ad5e0ab2ab06079db1597494bcdb3d
a260501fe1dbce0aae258ca3d7ac1d8fe47455d3
refs/heads/master
2023-08-06T17:48:36.262072
2023-07-28T18:06:18
2023-07-28T18:06:18
25,878,863
0
0
null
null
null
null
UTF-8
C++
false
false
4,180
cpp
dice.cpp
// // Dice -- Generate and print random numbers // #include <cassert> #include <cctype> #include <iostream> #include <random> #include <string> using namespace std; struct Options; static void Generate(const Options&); static void GetOptions(int, char **, Options&); static void PrintHelp(void); static int RandInt(int, int); struct Options { Options() : perLine(false), printHelp(false), verbose(false), multiple(1), number(1), sides(6), adjustment(0) {} void Check(void) { assert(multiple > 0); assert(number > 0); assert(sides > 0); } void Print(void) { cerr << "perLine : " << (perLine ? "true" : "false") << endl; cerr << "printHelp : " << (printHelp ? "true" : "false") << endl; cerr << "verbose : " << (verbose ? "true" : "false") << endl; cerr << "adjustment : " << adjustment << endl; cerr << "multiple : " << multiple << endl; cerr << "number : " << number << endl; cerr << "sides : " << sides << endl; } bool perLine; bool printHelp; bool verbose; int multiple; // number of dice to roll int number; // number of times to roll the dice int sides; // number of sides per die int adjustment; // add per roll }; static const char SPACE = ' '; void Generate( const Options& opts ) { for (int n = 0; n < opts.number; n++) { int sum = opts.adjustment; for (int m = 0; m < opts.multiple; m++) sum += RandInt( 1, opts.sides ); cout << sum; if (opts.perLine) cout << endl; else if (n < opts.number - 1) cout << SPACE; } } void GetOptions( int argc, char **argv, Options& opts) { bool ok = false; int adjustment = 0; int multiple = 0; int sides = 0; size_t pos = string::npos; for (int i = 1; i < argc; i++ ) { string value( argv[i] ); if (value == "--help" || value == "-h") { opts.printHelp = true; } else if (value == "--line" || value == "-l") { opts.perLine = true; } else if (value == "--verbose" || value == "-v") { opts.verbose = true; } else if (value.find('x') != string::npos) { opts.number = stoi(value); } else { // Parse MdS+A // TODO Handle missing M pos = value.find('d'); if (pos != string::npos) { multiple = stoi(value.substr(0, pos), nullptr, 10); sides = stoi(value.substr(pos + 1), nullptr, 10); ok = true; } pos = value.find('+'); if (pos != string::npos) { adjustment = stoi(value.substr(pos), nullptr, 10); } else { pos = value.find('-'); if (pos != string::npos) adjustment = stoi(value.substr(pos), nullptr, 10); } } } if (ok) { opts.adjustment = adjustment; opts.multiple = multiple; opts.sides = sides; } opts.Check(); } void PrintHelp(void ) { cout << endl; cout << "dice [--help] | [--line] [Nx] MdS [+-A]" << endl; cout << " -h, --help Print help and exit" << endl; cout << " -l, --line Print one value per line" << endl; cout << " -v, --verbose Print debugging information" << endl; cout << " Nx Roll the dice N times" << endl; cout << " MdS+A Roll [1, S] M times and add A" << endl; cout << " Default: 1x 1d6+0" << endl; cout << endl; } int RandInt( int a, int b ) { static random_device generator; if (a > b) { int t = b; b = a; a = t; } uniform_int_distribution<int> distribution(a, b); return distribution(generator); } // // // int main( int argc, char **argv ) { Options opts; GetOptions( argc, argv, opts ); if (opts.verbose) opts.Print(); if ( opts.printHelp) { PrintHelp(); return 0; } Generate( opts ); return 0; }
7b93eee030f413c7bb99d8fe66c2e761e15df344
d9a50abfe2b0a1adf655048ddba8ef302d750d53
/DERAS-Server/include/ieee_sep/RPLInstanceList.h
0f6f2d5547c2b54b97c98278f50d5accbe44271a
[ "BSD-2-Clause" ]
permissive
psu-powerlab/DERAS-Server
f7ed520ee6885a77ac5d3b2f672d8a6502004c97
5b41f35148aa1ff45c1f6b3a96f94ce443a72d0f
refs/heads/master
2022-11-29T15:01:50.874535
2020-06-18T20:06:10
2020-06-18T20:06:10
261,805,865
0
0
BSD-2-Clause
2020-07-06T18:53:10
2020-05-06T15:44:56
C++
UTF-8
C++
false
false
702
h
RPLInstanceList.h
/////////////////////////////////////////////////////////// // RPLInstanceList.h // Implementation of the Class RPLInstanceList // Created on: 13-Apr-2020 2:51:41 PM // Original author: svanausdall /////////////////////////////////////////////////////////// #if !defined(EA_ED43C9A8_4008_4df7_9DFD_6E36ECB5B988__INCLUDED_) #define EA_ED43C9A8_4008_4df7_9DFD_6E36ECB5B988__INCLUDED_ #include "List.h" #include "RPLInstance.h" /** * List of RPLInstances associated with the IPinterface. */ class RPLInstanceList : public List { public: RPLInstanceList(); virtual ~RPLInstanceList(); RPLInstance *m_RPLInstance; }; #endif // !defined(EA_ED43C9A8_4008_4df7_9DFD_6E36ECB5B988__INCLUDED_)
25b7a3509a1311db91ee183f274aa43639142a60
f6b1d777dc8f423326ec62073d417afc5d3048db
/src/cargui/src/ControlQNode.cpp
d8097a80b86c107b82c0ae8585ff061b7fa27396
[]
no_license
WuTUT/roscar
1ae433c703adbd32bf426bf7cbcad593f3c01f90
1fb2b435ea57ef3b326d4781bfb948674e5d95c5
refs/heads/master
2021-09-10T21:25:23.738367
2018-04-02T13:06:59
2018-04-02T13:06:59
114,250,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
ControlQNode.cpp
#include "../include/cargui/ControlQNode.hpp" ControlQNode::ControlQNode(){ this->directioninfo=""; cout<<"one thread is created"<<endl; } ControlQNode::~ControlQNode() { if(ros::isStarted()) { ros::shutdown(); // explicitly needed since we use ros::start(); ros::waitForShutdown(); } wait(); cout<<"one thread is deleted"<<endl; } bool ControlQNode::init(const std::string &master_url, const std::string &host_url) { std::map<std::string,std::string> remappings; remappings["__master"] = master_url; remappings["__hostname"] = host_url; ros::init(remappings,"guicontrol"); if ( ! ros::master::check() ) { return false; } ros::start(); // explicitly needed since our nodehandle is going out of scope. ros::NodeHandle n; control_publisher = n.advertise<std_msgs::String>("direction", 1000); start(); return true; } void ControlQNode::setDirectioninfo(string direction){ this->directioninfo=direction; } void ControlQNode::run() { ros::Rate loop_rate(1); std_msgs::String msg; while ( ros::ok() ) { if(this->directioninfo!=""){ msg.data = directioninfo; control_publisher.publish(msg); cout<<directioninfo<<"!"<<endl; this->directioninfo=""; ros::spinOnce(); loop_rate.sleep(); } } std::cout << "Ros shutdown, proceeding to close the gui." << std::endl; }
6a95a15c9036e6853b966c17c1cb2dfc2f75815e
6a3890b734797641a0e45dc2d882da370de63e49
/subroutines/read_cnstrn_parms.cpp
c325aabe2226bed05e16720a3dff048ae2e65232
[]
no_license
SysSynBio/StoichiometricBalance
f85222fd4bf650dbe0872dd29db10fd4b6ff30f6
2a9d3aac66bf5fc9ea1e29cb782afa4ae034983b
refs/heads/master
2023-03-16T13:22:54.631650
2020-10-29T21:49:13
2020-10-29T21:49:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
read_cnstrn_parms.cpp
#include "pro_classes.h" #include "constrainParms.h" #include "ProteinClass.h" #include "read_proinput.h" void read_cnstrn_parms(ifstream &parmfile, constrainParms &plist) { parmfile >>plist.nwhole; parmfile.ignore(400,'\n'); parmfile >>plist.Nedge; parmfile.ignore(400,'\n'); parmfile >>plist.min_complex; parmfile.ignore(400,'\n'); parmfile >>plist.Nconstrain; parmfile.ignore(400,'\n'); parmfile >>plist.flagread; parmfile.ignore(400,'\n'); parmfile >>plist.Ncsets; parmfile.ignore(400,'\n'); parmfile >>plist.nruns_rand; parmfile.ignore(400,'\n'); parmfile >>plist.ascale; parmfile.ignore(400,'\n'); parmfile >>plist.nstepMC; parmfile.ignore(400,'\n'); parmfile >>plist.mut_change; parmfile.ignore(400,'\n'); parmfile >>plist.Tone; parmfile.ignore(400,'\n'); parmfile >>plist.Nt; parmfile.ignore(400,'\n'); parmfile >>plist.scaleT; parmfile.ignore(400,'\n'); parmfile >>plist.Nruns; parmfile.ignore(400,'\n'); }
8896c0cfa8e520525a23a5500c75bd65a610a8eb
dfb67ecba4625c045cd9edde2e82a0117fc1797a
/src/dialogs/FormatsDlg.h
5f55571a81ca391ac5a9ab0a6f1d4dc29fc6c2b9
[ "MIT" ]
permissive
dragons4life/BatchEncoder
250c29215e5ebb526b3e935c3c3b33b2e4ea5ce7
7e25df3373b5b93d79967197fde965c4c7e91054
refs/heads/master
2021-08-26T09:46:52.920787
2017-11-22T16:31:11
2017-11-22T16:31:11
108,954,503
0
0
null
2017-10-31T07:17:21
2017-10-31T06:26:09
C++
UTF-8
C++
false
false
4,608
h
FormatsDlg.h
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <afxcmn.h> #include <afxwin.h> #include "..\controls\MyListCtrl.h" #include "..\controls\MyButton.h" #include "..\controls\MyComboBox.h" #include "..\controls\MyEdit.h" #include "..\controls\MyStatic.h" #include "..\controls\MyResizeDialog.h" #include "..\configuration\FormatsList.h" #include "..\configuration\Configuration.h" #define FORMAT_COLUMN_NAME 0 #define FORMAT_COLUMN_TEMPLATE 1 class CFormatsDlg; typedef struct tagFormatsDlgDropContext { CFormatsDlg *pDlg = NULL; HDROP hDrop = NULL; HANDLE hThread = NULL; DWORD dwThreadID = -1; volatile bool bHandled = true; } FormatsDlgDropContext; class CFormatsDlg : public CMyResizeDialog { DECLARE_DYNAMIC(CFormatsDlg) public: CFormatsDlg(CWnd* pParent = NULL); virtual ~CFormatsDlg(); enum { IDD = IDD_DIALOG_FORMATS }; protected: virtual void DoDataExchange(CDataExchange* pDX); DECLARE_MESSAGE_MAP() protected: HICON m_hIcon; afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); public: virtual BOOL OnInitDialog(); public: FormatsDlgDropContext m_DD; CConfiguration *pConfig; CString szFormatsDialogResize; CString szFormatsListColumns; volatile bool bUpdate; int nSelectedFormat; CFormatsList m_Formats; public: CMyStatic m_GrpPipes; CMyStatic m_GrpTypes; CMyStatic m_StcId; CMyStatic m_StcName; CMyStatic m_StcExtension; CMyStatic m_StcFormats; CMyStatic m_StcCode; CMyStatic m_StcDefault; CMyStatic m_StcPath; CMyStatic m_StcTemplate; CMyStatic m_StcProgress; CMyListCtrl m_LstFormats; CMyComboBox m_CmbDefault; CMyEdit m_EdtId; CMyEdit m_EdtName; CMyEdit m_EdtExtension; CMyEdit m_EdtFormats; CMyEdit m_EdtCode; CMyEdit m_EdtPath; CMyEdit m_EdtTemplate; CMyEdit m_EdtFunction; CMyButton m_BtnOK; CMyButton m_BtnCancel; CMyButton m_BtnImport; CMyButton m_BtnExport; CMyButton m_BtnDuplicate; CMyButton m_BtnRemoveAll; CMyButton m_BtnRemove; CMyButton m_BtnAdd; CMyButton m_BtnMoveUp; CMyButton m_BtnMoveDown; CMyButton m_BtnUpdate; CMyButton m_BtnLoad; CMyButton m_BtnSave; CMyButton m_BtnEditPresets; CMyButton m_BtnBrowsePath; CMyButton m_BtnBrowseFunction; public: afx_msg void OnDropFiles(HDROP hDropInfo); afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); afx_msg void OnLvnItemchangedListFormats(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedButtonImport(); afx_msg void OnBnClickedButtonExport(); afx_msg void OnBnClickedButtonDuplicate(); afx_msg void OnBnClickedButtonRemoveAllFormats(); afx_msg void OnBnClickedButtonRemoveFormat(); afx_msg void OnBnClickedButtonAddFormat(); afx_msg void OnBnClickedButtonFormatUp(); afx_msg void OnBnClickedButtonFormatDown(); afx_msg void OnBnClickedButtonUpdateFormat(); afx_msg void OnBnClickedRadioTypeEncoder(); afx_msg void OnBnClickedRadioTypeDecoder(); afx_msg void OnBnClickedCheckPipesInput(); afx_msg void OnBnClickedCheckPipesOutput(); afx_msg void OnEnChangeEditFormatId(); afx_msg void OnEnChangeEditFormatName(); afx_msg void OnEnChangeEditFormatExtension(); afx_msg void OnEnChangeEditFormatFormats(); afx_msg void OnCbnSelchangeComboDefault(); afx_msg void OnEnChangeEditFormatPath(); afx_msg void OnEnChangeEditFormatTemplate(); afx_msg void OnEnChangeEditFormatFunction(); afx_msg void OnBnClickedButtonLoadFormats(); afx_msg void OnBnClickedButtonSaveFormats(); afx_msg void OnBnClickedButtonEditPresets(); afx_msg void OnBnClickedButtonBrowsePath(); afx_msg void OnBnClickedButtonBrowseProgress(); afx_msg void OnClose(); public: void LoadWindowSettings(); void SaveWindowSettings(); void SetLanguage(); void AddToList(CFormat &format, int nItem); void InsertFormatsToListCtrl(); void HandleDropFiles(HDROP hDropInfo); void UpdateFields(CFormat &format); void UpdateDefaultComboBox(CFormat &format); void ListSelectionChange(); void LoadFormat(CString szFileXml); void SaveFormat(CString szFileXml, CFormat &format); void LoadFormats(CString szFileXml); void SaveFormats(CString szFileXml); bool BrowseForPath(CString szDefaultFName, CEdit *pEdit, int nID); bool BrowseForFunction(CString szDefaultFName, CEdit *pEdit, int nID); };
f05455f13d3f028fb6fdb960373fec80f7816a92
542eb7c90fb4b3563b10e3bf4e2d0ffe61e2b6f1
/src/ModelDynamic.h
0f520a97919030a0508c8c9b12a5ab559eeaaebc
[]
no_license
kasmar00/PUT-INF4-GKW-Projekt
6caa1ef70d351fb3760fd248e3263e7383b67704
38a356974b5953310fc0112fe9956debba6c3bc1
refs/heads/master
2023-07-30T03:09:28.644870
2021-10-04T11:07:34
2021-10-04T11:07:34
358,049,753
0
0
null
2021-10-04T11:07:34
2021-04-14T21:43:54
C++
UTF-8
C++
false
false
890
h
ModelDynamic.h
#ifndef __MODELDYNAMIC_H__ #define __MODELDYNAMIC_H__ #include <GL/glew.h> #include <glm/glm.hpp> #include <utility> #include <vector> #include "Model.h" class ModelDynamic : public Model { private: float locationX; float locationY; float height; int direction; float rotation; unsigned long int mapIterator; float timer; public: std::vector<float>* verts; std::vector<float>* texCoords; std::vector<float>* normals; int vertexCount; GLuint tex; std::vector<std::pair<float, float>> map; int bodyVertexCount, wheelVertexCount; ModelDynamic(glm::vec2 pos, GLuint texture, std::vector<float>* verts, std::vector<float>* texCoords, std::vector<float>* normals); ~ModelDynamic(){}; void draw(glm::mat4 M); void setHeight(float height); void setDirection(int direction); }; #endif // __MODELDYNAMIC_H__
41018c43266444301a4b24947b6ea5b4928429f2
c3f09fdce1afe96b50809b6e8e6d803329a5b438
/2013-05-27-note/logic/src/NotifySystem_Android_Handler.cpp
a8434d3f05531262ff15d06f1c584b754b673642
[]
no_license
xiaoxiaoyi/windows2linuxnote
7e219f6e58d8b5eeb5c67c9d5d6d717e793da964
35ba4b305cb3bc0fe58e4429078d91b6bdb63616
refs/heads/master
2021-01-10T20:04:51.806084
2013-08-12T13:01:48
2013-08-12T13:01:48
10,140,640
0
1
null
null
null
null
UTF-8
C++
false
false
257
cpp
NotifySystem_Android_Handler.cpp
#include "../include/NotifySystem.h" #include "../include/LoggerSystem.h" #include <cocos2d.h> #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) void NotifySystem::ClearAllNotification() { } void NotifySystem::RegisterAllNotification() { } #endif
ed1cbc23ddbabb203038a4840930ca269c01764d
2953868456602b71391eeae06d2d1dc0d74cb223
/xrm-unittest/src/common_mock_ut.cpp
ec1e14a9bf2497f9b88dd855db93c3a23e4c4c2e
[ "Zlib" ]
permissive
M-griffin/Oblivion2-XRM
653357bc9056c8d2b25fde9eb59d3dfa1c991623
7b4147f34fcde18ba75a46fdb5aa5f460bb7a887
refs/heads/develop
2023-09-04T06:24:40.364355
2023-04-26T07:27:33
2023-04-26T07:27:33
43,869,148
90
12
NOASSERTION
2022-06-13T07:28:10
2015-10-08T07:10:42
C++
UTF-8
C++
false
false
2,189
cpp
common_mock_ut.cpp
/** * @brief Oblivion/2 XRM Unit Tests for CommonIO. * @return */ #include "common_io.hpp" #include <UnitTest++.h> // C++ Standard #include <iostream> #include <string> #include <stdexcept> /** * @brief Test Suit for CommonIO Class. * @return */ SUITE(XRM_MockUTTestClass) { /** * @brief Test Number of Characters with High ASCII mix-ins. * @return */ TEST(numberOfCharsWithHighAscii) { CommonIO common; std::string temp = std::string(1, static_cast<unsigned char>(148)); temp += std::string(1, static_cast<unsigned char>(126)); temp += std::string(1, static_cast<unsigned char>(155)); int result = common.numberOfChars(temp); CHECK_EQUAL(result, 3); } TEST(numberOfCharsWithHighAsciiAndUtf8BeforeAndAfter) { // 21 Bytes, should be 9 separate characters CommonIO common; std::string temp = "あにま"; // 3 + 3 + 3 = 9 bytes temp += std::string(1, static_cast<unsigned char>(148)); // 1 byte temp += std::string(1, static_cast<unsigned char>(126)); // 1 byte temp += std::string(1, static_cast<unsigned char>(155)); // 1 byte temp += "あにま"; // 3 + 3 + 3 = 9 bytes int result = common.numberOfChars(temp); CHECK_EQUAL(result, 9); } /* This was remove from the code. TEST(parseAnsiScreenTestHighAscii) { CommonIO common; std::string temp = std::string(1, static_cast<unsigned char>(148)); temp += std::string(1, static_cast<unsigned char>(126)); temp += std::string(1, static_cast<unsigned char>(155)); common.testUnicode(temp); }*/ /** No Longer a Valid Test. * @brief Erase Data in a String w/ start, end range. w/ High Ascii * @return * TEST(EraseStringWithHighAscii) { CommonIO common; std::string temp = std::string(1, static_cast<unsigned char>(155)); temp += " Linux----"; std::string trim_temp = common.eraseString(temp, 6); std::string result = std::string(1, static_cast<unsigned char>(155)); result += " Li"; CHECK_EQUAL(trim_temp, result); }*/ }
9fdb48880700773266fd1ed7cfc8477146ec5adc
418aa6c4486e255f482b6c9bee12a08cda829503
/CamCommon/dxcapture.h
8d9042596aa3e5288acfd21e7cb97adf7f4dc4a7
[ "MIT" ]
permissive
jjuiddong/Common
b21c9a98474fc45aa30b316808498381c2030ad3
3097b60988464000e2885a07cdd6e433e43de386
refs/heads/master
2023-08-31T07:35:31.425468
2023-08-29T11:38:29
2023-08-29T11:38:29
77,737,521
3
8
null
null
null
null
UHC
C++
false
false
2,355
h
dxcapture.h
// // DirectShow를 이용해 카메라 영상을 가져오는 기능을 한다. // // Thread Safe Version // // 이 객체를 사용한 후, 마지막에 CoUninitialize(); 함수를 호출하자. // #pragma once #include "dxcaptureutil.h" namespace Gdiplus { class Bitmap; } namespace cvproc { class cDxCapture { public: cDxCapture(); virtual ~cDxCapture(); bool Init(const int cameraIndex, const int width, const int height, const bool isThreadMode = false); void UpdateCurrentBuffer(); BYTE* GetCurrentBuffer(long &size); BYTE* GetCloneBuffer(long &size); cv::Mat& GetCloneBufferToImage(const bool cpyImage = true); Gdiplus::Bitmap* GetCloneBufferToBitmap(); void WriteBitmapFromCurrentBuffer(const char* fileName); HRESULT WriteBitmapFromBuffer(const char* fileName, const BYTE *buffer, const long bufferSize); HRESULT HandleGraphEvent(void); void Close(); protected: HRESULT GetInterfaces(void); HRESULT CaptureVideo(const int cameraIndex = 0); HRESULT FindCaptureDevice(const int cameraIndex, IBaseFilter ** ppSrcFilter); HRESULT SetupVideoWindow(void); HRESULT ChangePreviewState(int nShow); void Msg(TCHAR *szFormat, ...); void CloseInterfaces(void); void ResizeVideoWindow(void); // Remote graph viewing functions HRESULT AddGraphToRot(IUnknown *pUnkGraph, DWORD *pdwRegister); void RemoveGraphFromRot(DWORD pdwRegister); public: enum PLAYSTATE { STOPPED, PAUSE, RUNNING, INIT }; int m_cameraIndex; int m_width; int m_height; bool m_isThreadMode; bool m_isUpdateBuffer; // 버퍼가 업데이트 되면 true가 된다. GetCloneBuffer() 호출시 초기화 된다. bool m_isUnpluggedInit; // 카메라와 연결이 끊어진 후, 다시 연결되었을 때, true 가 된다. DWORD m_dwGraphRegister; IVideoWindow * m_pVW; IMediaControl * m_pMC; IMediaEventEx * m_pME; IGraphBuilder * m_pGraph; ICaptureGraphBuilder2 * m_pCapture; IBaseFilter *m_pGrabberF; ISampleGrabber *m_pGrabber; IBaseFilter *m_pNullF; PLAYSTATE m_psCurrent; AM_MEDIA_TYPE m_mt; BYTE *m_pFrameBuffer; long m_frameBufferSize; BYTE *m_pCloneFrameBuffer; cv::Mat m_iplImage; cv::Mat m_matImage; Gdiplus::Bitmap *m_gdiBitmap; HANDLE m_handle; DWORD m_threadId; bool m_threadLoop; CRITICAL_SECTION m_criticalSection; // debug bool m_showFrame; }; }
8f788fcc95e93e2485c524b51e96e03bdb116e71
d1edd8127319588271f409af417a3cb87c9aa84a
/Lecture-8/InbuiltFuncStrings.cpp
4da766f5f39e2851adf255175461caa05410da80
[]
no_license
zhcet19/LPNMSUMMERS19
35b60868916af294def6a33866fd1d6488dd89a7
0999c39ba6d70a2df8ee963479152d0e6863c099
refs/heads/master
2022-01-16T19:41:36.237289
2019-07-03T06:56:16
2019-07-03T06:56:16
286,501,549
1
0
null
2020-08-10T14:44:23
2020-08-10T14:44:22
null
UTF-8
C++
false
false
546
cpp
InbuiltFuncStrings.cpp
// InbuiltFuncStrings #include <iostream> #include <cstring> // - header file using namespace std; int length(char *ch){ int i; for(i=0;ch[i]!='\0';i++){ } return i; } int main(){ char ch[100] = "Hello World"; char ch1[100]; cout<<strlen(ch)<<endl; strcpy(ch1,ch); strcat(ch1,ch); cout<<ch<<endl; cout<<ch1<<endl; char words[][100]={ "Hello", "World", "Coding", "Blocks" }; char ch[100]; cin.getline(ch,100); // Whether this exists in words or not cout<<endl; return 0; }
0cb9047c502075f47ea71032cd67d6d23bc1cecf
f59e13370eecd0487138da60f36175ae8d3b3f68
/9.tetel/beugro/map.cpp
92b10efe51f7c8545bfec7106b7589aab491c461
[]
no_license
sanyi9305/C-t-telek
3107ad9be6189bf385a4d54161b56e813ced6ccd
4708de923cf1387700a55bfd4ccfd76184fa8d5f
refs/heads/master
2021-07-12T09:27:08.591527
2017-10-13T17:04:31
2017-10-13T17:04:31
106,851,410
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
map.cpp
#include <iostream> #include <map> #include <vector> #include <string> #include <algorithm> using namespace std; class sort_map { public: string key; int val; }; bool Sort_by(const sort_map& a ,const sort_map& b) { return a.val < b.val; } int main() { map<string,int> d; map<string,int>::iterator it; vector< sort_map > v; vector< sort_map >::iterator itv; sort_map sm; d["a"] = 5; d["b"] = 3; d["c"] = 9; d["d"] = 7; d["e"] = 1; d["f"] = 13; d["g"] = 11; for (it = d.begin(); it != d.end(); ++it) { sm.key = (*it).first; sm.val = (*it).second; v.push_back(sm); } for (itv = v.begin(); itv != v.end(); ++itv) { cout << (*itv).key << " : " << (*itv).val << endl; } sort(v.begin(),v.end(),Sort_by); cout << "sorted" << endl; for (itv = v.begin(); itv != v.end(); ++itv) { cout << (*itv).key << " : " << (*itv).val << endl; } return 0; }
c9ca3fc412ee63fe5ff9ecbb28be1fcd8c42c283
010179cb58314ff19aa883db3b76340724680d61
/src/Heimdall/impl/ChangeMonitor.win.cpp
bc4908c3ac0a46d8facb6214221486855e205597
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
tido64/rainbow
1c97aefdba6bf80a28a00769d4920829a5a63f01
b54b84860979eca86e7d32ab61f92d9745fecfaa
refs/heads/master
2023-07-25T13:04:04.730635
2021-08-16T07:01:37
2021-08-16T07:01:37
20,939,716
49
7
MIT
2021-09-06T18:46:58
2014-06-17T21:10:46
C
UTF-8
C++
false
false
3,533
cpp
ChangeMonitor.win.cpp
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #include "Heimdall/ChangeMonitor.h" #ifdef USE_HEIMDALL # include "Common/Logging.h" using heimdall::ChangeMonitor; using rainbow::czstring; ChangeMonitor::ChangeMonitor(czstring directory) : monitoring_(false), callback_([](czstring) {}) { hDirectory_ = CreateFileA(directory, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (hDirectory_ == INVALID_HANDLE_VALUE) return; LOGI("Monitoring '%s'", directory); monitoring_ = true; worker_ = std::async(std::launch::async, [this]() { char lpPath[MAX_PATH * 4]; const DWORD nBufferLength = 8192; auto buffer = std::make_unique<DWORD[]>(nBufferLength); do { std::this_thread::sleep_for(std::chrono::seconds(1)); DWORD dwBytesReturned = 0; ReadDirectoryChangesW( hDirectory_, buffer.get(), nBufferLength, TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION, &dwBytesReturned, nullptr, nullptr); if (dwBytesReturned == 0) continue; const uint8_t* lpBuffer = reinterpret_cast<uint8_t*>(buffer.get()); const FILE_NOTIFY_INFORMATION* lpInfo = nullptr; do { if (!monitoring_) return; lpInfo = reinterpret_cast<const FILE_NOTIFY_INFORMATION*>(lpBuffer); if (lpInfo->Action != FILE_ACTION_MODIFIED) continue; const int cchWideChar = lpInfo->FileNameLength / sizeof(lpInfo->FileName[0]); const int length = WideCharToMultiByte(CP_UTF8, 0, lpInfo->FileName, cchWideChar, nullptr, 0, nullptr, nullptr); if (length == 0) continue; WideCharToMultiByte(CP_UTF8, 0, lpInfo->FileName, cchWideChar, lpPath, length, nullptr, nullptr); lpPath[length] = '\0'; on_modified(lpPath); lpBuffer += lpInfo->NextEntryOffset; } while (lpInfo->NextEntryOffset > 0); } while (monitoring_); }); } ChangeMonitor::~ChangeMonitor() { if (!monitoring_) return; monitoring_ = false; CancelIoEx(hDirectory_, nullptr); CloseHandle(hDirectory_); } #endif // USE_HEIMDALL
81ae323063ab40a0ebfa8ecbad64415dcb3d1b7e
5e9a0f199af19d9ee0ad76918cd0eaf627912bcc
/2004/samples/entity/DblClick/AcDbDoubleClickCircle.cpp
73c5bac3467917a7b378ed36a4f49e0edd98278a
[ "MIT" ]
permissive
Amazing95/ObjectARXMod
c9473da0db6600edb9cb63730e4cb4fd07a61f18
ef4c87db803a451c16213a7197470a3e9b40b1c6
refs/heads/master
2021-05-28T05:55:12.243947
2014-05-05T07:00:58
2014-05-05T07:00:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,021
cpp
AcDbDoubleClickCircle.cpp
// // (C) Copyright 2001 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // AcDbDoubleClickCircle.cpp: implementation of the AcDbDoubleClickCircle class. #include "stdafx.h" #include "resource.h" #include "AcDbDoubleClickCircle.h" #include "dbents.h" #include "aced.h" #include "acdocman.h" #include "actrans.h" #include "dbtrans.h" #include "geassign.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// AcDbDoubleClickCircle::AcDbDoubleClickCircle() { } AcDbDoubleClickCircle::~AcDbDoubleClickCircle() { } extern Adesk::Boolean acedPostCommand(const char *); void AcDbDoubleClickCircle::startEdit(AcDbEntity *pEnt, AcGePoint3d pt) { // Implement the startEdit notification handler to catch when // a user double-clicks a 'CIRCLE' entity // Get the Current Document AcApDocument *pDoc=acDocManager->curDocument(); AcDbCircle *pCircle; // Cast the AcDbEntity pointer to AcDbPolyline if(pEnt->isKindOf(AcDbCircle::desc()) == Adesk::kTrue) pCircle=AcDbCircle::cast(pEnt); else { acutPrintf("Error: Invalid AcDbCircle Object"); return; } acDocManager->lockDocument(pDoc,AcAp::kWrite); // Upgrade to write if(pCircle->upgradeOpen()!=Acad::eOk) { acutPrintf("Error: Could Not open AcDbCircle Object"); return; } // Get the current Color Adesk::UInt16 color=pCircle->colorIndex(); // Modify the color if(pCircle->setColorIndex((color+1)%10)!=Acad::eOk) { acutPrintf("Error: Could Not Modify AcDbCircle Object"); return; } pCircle->close(); acDocManager->unlockDocument(pDoc); // clear the pickfirst selection set. acedSSSetFirst(NULL,NULL); // Update the graphics... pCircle->draw(); actrTransactionManager->flushGraphics(); acedUpdateDisplay(); } void AcDbDoubleClickCircle::finishEdit() { // No need to implement for this example }
4661b9006849c543658ce3a53b2ca6945f824a53
a5f720e9019d535a3d745d9900d4b8480963aa60
/Logger.h
43441f086ff14ebbedd177f7950333b296587ecb
[ "MIT" ]
permissive
dsackinger/drinking-philosophers
a0a8dc054394ea2e59677141e0632ab6488e0ca1
87ef243510025a1518a4d9ba693266f0c8c36e9d
refs/heads/master
2022-02-21T16:12:40.786943
2019-09-28T20:07:30
2019-09-28T20:07:30
125,369,306
0
0
null
null
null
null
UTF-8
C++
false
false
1,495
h
Logger.h
////////////////////////////////////////////////////////////////////////// // Logger.h // // Copyright (C) 2018 Dan Sackinger - All Rights Reserved // You may use, distribute and modify this code under the // terms of the MIT license. // // Logger declaration: // This is a simple logger that unpacks arguments and // dumps them to cout // #if !defined(__LOGGER_H__) #define __LOGGER_H__ #include <mutex> #include <sstream> class Logger { public: struct entry { const std::chrono::system_clock::time_point time; const std::string line; entry * next; }; public: Logger() = default; virtual ~Logger() = default; public: // Public logging function that takes any arguments as long as they output to a stream template<typename... Args> void log(Args... args) { std::stringstream ss; log(ss, args...); log(ss.str()); } private: // Final type for ending the recursion template<typename T> void log(std::stringstream& os, T final) { os << final; } // Expands to account for all types that can be output to a stream template<typename T, typename... Args> void log(std::stringstream& os, T current, Args... next) { os << current; log(os, next...); } // Logs the final message void log(const std::string& message); private: std::mutex lock_; private: // Disable assign / copy Logger(const Logger& rhs) = delete; Logger& operator =(const Logger& rhs) = delete; }; #endif // #if !defined(__LOGGER_H__)
2f1596f55e2769f86ee099e07004e86bc3fe8bd5
290c3c0c93db33f31fc44c307c58a8a43f7193a4
/source/model/handactionmodel.cpp
fb75c78769c078a02c56672a90ff03c0f4a70a96
[]
no_license
yisea123/megarobostudio
d16364087296eeaa1ae90b1178875379bcdbca34
efb2ae438e2a73635619611232522a012e1921f8
refs/heads/master
2022-12-11T10:14:06.889822
2018-12-04T00:33:47
2018-12-04T00:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,008
cpp
handactionmodel.cpp
#include "../../include/mcstd.h" #include "handactionmodel.h" static QString _headers[]= { QStringLiteral("Name"), QString("Value(" + QString( char_deg ) + ")"), QStringLiteral("Comment"), }; int handAction::columns() { return sizeof_array( _headers ); } QString handAction::header( int col ) { Q_ASSERT( col >= 0 && col <= sizeof_array(_headers) ); return _headers[ col ]; } //! action handAction::handAction() { mValue = 0.0; } handAction::~handAction() { } void handAction::set( const QString &name, double value, const QString &comment ) { setName( name ); setValue( value ); setComment( comment ); } void handAction::setName( const QString &name ) { mName = name; } QString handAction::name() { return mName; } void handAction::setValue( double value ) { mValue = value; } double handAction::value() { return mValue; } void handAction::setComment( const QString &comment ) { mComment = comment; } QString handAction::comment() { return mComment; } //! model handActionModel::handActionModel() { } handActionModel::~handActionModel() { delete_all( mItems ); } int handActionModel::rowCount(const QModelIndex &parent) const { return mItems.count(); } int handActionModel::columnCount(const QModelIndex &parent) const { return handAction::columns(); } QVariant handActionModel::data(const QModelIndex &index, int role) const { if ( !index.isValid() ) { return QVariant(); } //! index int col = index.column(); int row = index.row(); if ( role != Qt::DisplayRole && role != Qt::EditRole ) { return QVariant(); } if ( col == 0 ) { return QVariant( mItems[ row ]->name() ); } else if ( col == 1 ) { return QVariant( mItems[ row ]->value() ); } else if ( col == 2 ) { return QVariant( mItems[ row ]->comment() ); } else { return QVariant(); } } bool handActionModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { int col = index.column(); int row = index.row(); if ( col == 0 ) { mItems[ row ]->setName( value.toString() ); } else if ( index.column() == 1 ) { mItems[ row ]->setValue( value.toDouble() ); } else if ( index.column() == 2 ) { mItems[ row ]->setComment( value.toString() ); } else {} emit dataChanged(index, index); return true; } else { return false; } } Qt::ItemFlags handActionModel::flags(const QModelIndex &index) const { if (!index.isValid()) { return Qt::ItemIsEnabled; } return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } bool handActionModel::insertRows(int position, int rows, const QModelIndex &parent) { if ( position < 0 || rows < 0 ) { return false; } beginInsertRows(QModelIndex(), position, position+rows-1); handAction *pItem; for (int row = 0; row < rows; ++row) { pItem = new handAction(); mItems.insert( position+row, pItem ); } endInsertRows(); return true; } bool handActionModel::removeRows(int position, int rows, const QModelIndex &parent) { if ( position < 0 || rows < 1 ) { return false; } beginRemoveRows(QModelIndex(), position, position+rows-1); for (int row = 0; row < rows; ++row) { delete mItems[position]; mItems.removeAt(position); } endRemoveRows(); return true; } QVariant handActionModel::headerData(int section, Qt::Orientation orientation, int role ) const { if ( role != Qt::DisplayRole ) { return QVariant(); } if ( orientation == Qt::Horizontal ) { return QVariant( handAction::header(section)); } else { return QVariant(section);} } int handActionModel::save( const QString &fileName ) { QFile fileOut( fileName ); if ( !fileOut.open( QIODevice::WriteOnly) ) { return ERR_FILE_OPEN_FAIL; } QXmlStreamWriter writer( &fileOut ); int ret; writer.writeStartDocument(); writer.writeStartElement("hand_action"); ret = serialOut( writer ); writer.writeEndElement(); writer.writeEndDocument(); fileOut.close(); return ret; } int handActionModel::load( const QString &fileName ) { //! check ver QFile fileIn(fileName); if ( !fileIn.open( QIODevice::ReadOnly) ) { return ERR_FILE_OPEN_FAIL; } QXmlStreamReader reader( &fileIn ); int ret = 0; while( reader.readNextStartElement() ) { if ( reader.name() == "hand_action" ) { ret = serialIn( reader ); } else { reader.skipCurrentElement(); } } fileIn.close(); return ret; } int handActionModel::serialOut( QXmlStreamWriter & writer ) { foreach( handAction *pAction, mItems ) { Q_ASSERT( NULL != pAction ); writer.writeStartElement( "action" ); writer.writeTextElement( "name", pAction->name() ); writer.writeTextElement( "value", QString::number( pAction->value() ) ); writer.writeTextElement( "comment", pAction->comment() ); writer.writeEndElement(); } return 0; } int handActionModel::serialIn( QXmlStreamReader & reader ) { //! item handAction *pItem; QList< handAction * > localItems; while( reader.readNextStartElement() ) { if ( reader.name() == "action" ) { pItem = new handAction(); Q_ASSERT( NULL != pItem ); while( reader.readNextStartElement() ) { if ( reader.name() == "name" ) { pItem->setName( reader.readElementText() ); } else if ( reader.name() == "value" ) { pItem->setValue( reader.readElementText().toDouble() ); } else if ( reader.name() == "comment" ) { pItem->setComment( reader.readElementText() ) ; } else { reader.skipCurrentElement(); } } localItems.append( pItem ); } else { reader.skipCurrentElement(); } } //! assign delete_all( mItems ); mItems = localItems; endResetModel(); return 0; } QMap< QString, double > handActionModel::actionMap() { QMap<QString, double > map; foreach ( handAction *pAction, mItems) { Q_ASSERT( NULL != pAction ); if ( pAction->name().length() < 1 ) { continue; } if ( map.contains( pAction->name()) ) { continue; } map.insert( pAction->name(), pAction->value() ); } return map; }
f09ec9b98729599cdd4d01e2abaf1bec14ca3a93
95abe4d4e92247a05e63c134e5e5f39c84cdad25
/FlightComputer/FlightComputer/b1_states.h
67fc305e312f49381895895412622e871877a75b
[]
no_license
ColeEdwards97/LRL-Avionics-2018-2019
a4b92c7776da18e72b1a34292634f066d2ce1aea
30f18a03da0f7f635f6db042031cf4202fb2f207
refs/heads/master
2020-03-30T11:47:36.992993
2019-03-22T18:29:16
2019-03-22T18:29:16
151,193,203
1
0
null
2019-08-30T18:08:57
2018-10-02T03:04:24
C++
UTF-8
C++
false
false
2,319
h
b1_states.h
// // _ ___ _ _ __ __ ___ ___ _ _ ___ ___ ___ // | | | _ \ | | /_\ \ \ / / |_ _| / _ \ | \| | |_ _| / __| / __| // | |__ | / | |__ / _ \ \ V / | | | (_) | | .` | | | | (__ \__ \ // |____| |_|_\ |____| /_/ \_\ \_/ |___| \___/ |_|\_| |___| \___| |___/ // // Organization: Liquid Bi-Propellant Rocket Project // University: California State Polytechnic University, Pomona // Author: Cole Edwards // Date Created: 11 October 2018 // Date Revised: 12 October 2018 // Description: Bronco 1 States definition // // // GENERAL TODOS // // INCLUDES #pragma once #include <iostream> #include "b1_hardware.h" class b1_states { public: // SINGLETON static b1_states& getInstance() { static b1_states instance; return instance; } b1_states(b1_states const&) = delete; void operator=(b1_states const&) = delete; // ENUMS // B1 States enum b1_state { ST_ANY = -1, ST_INIT = 0, ST_IDLE = 1, ST_FILL = 2, ST_DRAIN = 3, ST_IGNITION = 4, ST_CRUISE = 5, ST_BURN_OUT = 6, ST_VENT = 7, ST_EMERGENCY = 8001, ST_TERM = 9999 }; // B1 Events enum b1_event { EV_ANY = -1, EV_NOMINAL = 0, EV_OVR_PR = 1, EV_FULL_TEMP = 2 }; // STRUCTS typedef struct { b1_hardware::sol_state ss1; b1_hardware::sol_state ss2; b1_hardware::vent_state vs1; b1_hardware::vent_state vs2; b1_hardware::pyro_state ps1; b1_hardware::pyro_state ps2; } MPS_CONFIG; b1_states::MPS_CONFIG conf[1] { { b1_hardware::sol_state::CLOSED, b1_hardware::sol_state::CLOSED, b1_hardware::vent_state::CLOSED, b1_hardware::vent_state::CLOSED, b1_hardware::pyro_state::INTACT, b1_hardware::pyro_state::INTACT } }; typedef struct { b1_state st; b1_event ev; MPS_CONFIG conf; b1_state(*fn)(void); } tTransition; b1_states::tTransition trans[3] = { { ST_ANY, EV_FULL_TEMP, conf[1], fn1 }, { ST_ANY, EV_OVR_PR, conf[1], fn2 }, { ST_ANY, EV_NOMINAL, conf[1], fn2 } }; // METHODS b1_state getState(void); b1_event getEvent(void); void setState(b1_state newState); void setEvent(b1_event newEvent); static b1_state fn1(void); static b1_state fn2(void); int transCount(void); private: // CONSTRUCTOR b1_states(); b1_state currentState; b1_event currentEvent; };
85bb9e8fd224959c999e652369a5239fc884426b
00cc864f4e5922d43785a1465e8d8e99d5437555
/src/library/SpinLock.hpp
c4a96bcec541ac9f4117b28fb6d21ca01ae70a4d
[]
no_license
evanbowman/sge
630d037e633de2b733e53ceb9e74982918aa990c
a5ea167f5ce5761be6d2a8cfbfc563263f17548a
refs/heads/master
2021-01-21T14:35:28.658139
2017-08-06T05:00:33
2017-08-06T05:00:33
95,306,498
3
0
null
null
null
null
UTF-8
C++
false
false
181
hpp
SpinLock.hpp
#pragma once #include <atomic> #include <mutex> class SpinLock { public: void lock(); void unlock(); private: std::atomic_flag m_lockFlag = ATOMIC_FLAG_INIT; };
ec555119094b14587f17b2844d9b0a229816dd5b
7a4326a6fffc766fb3c126e01b2ff8cd811a7986
/code/bluebeard/src/SoundManager.cpp
4d5b39b9fe7ea83d02cc0692aaee186ae638fb56
[]
no_license
zhangchenghgd/zeroballistics
c326351f537d5a657e1441b978a3111441e1d8f2
34bb5f294b032ad025e3b4f5d82b86ac62245a10
refs/heads/master
2021-05-31T01:30:25.977219
2011-01-16T21:28:41
2011-01-16T21:28:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,411
cpp
SoundManager.cpp
#include "SoundManager.h" #include "SoundSource.h" #include "ParameterManager.h" #include "GameObjectVisual.h" #include "OsgNodeWrapper.h" // method of device enumeration, ALC_ENUMERATE_ALL_EXT seems // to be implemented only on win platforms #ifdef _WIN32 #define DEVICES_SPECIFIER ALC_ALL_DEVICES_SPECIFIER #define DEFAULT_DEVICES_SPECIFIER ALC_DEFAULT_ALL_DEVICES_SPECIFIER #else #define DEVICES_SPECIFIER ALC_DEVICE_SPECIFIER #define DEFAULT_DEVICES_SPECIFIER ALC_DEFAULT_DEVICE_SPECIFIER #endif const float DOPPLER_FACTOR = 0.02f; const float SOUND_SPEED = 1.0f; //------------------------------------------------------------------------------ SoundManager::SoundManager() : ResourceManager<SoundBuffer>("sounds"), current_device_(NULL), current_context_(NULL), sounds_enabled_(false) { s_console.addFunction("toggleSoundEnabled", Loki::Functor<void>(this, &SoundManager::toggleSoundEnabled), &fp_group_); alutInitWithoutContext(NULL,NULL); try { initSoundDevices(); createALSoundSources(); alDopplerFactor(DOPPLER_FACTOR); alSpeedOfSound(SOUND_SPEED); } catch (Exception & e) { e.addHistory("SoundManager::SoundManager"); current_context_ = NULL; current_device_ = NULL; s_log << e << "\n"; } } //------------------------------------------------------------------------------ SoundManager::~SoundManager() { if (!current_device_) return; // actually free all allocated Sound Sources ALuint src_id; SoundSourceMap::iterator it; for(it = sound_src_in_use_.begin();it != sound_src_in_use_.end(); it++) { src_id = it->first; alDeleteSources(1, &src_id); // delete sound source } sound_src_in_use_.clear(); // Free Sound Buffers as long as the context is still valid unloadAllResources(); alcMakeContextCurrent(NULL); alcDestroyContext(current_context_); alcCloseDevice (current_device_); current_context_ = NULL; current_device_ = NULL; alutExit(); } //------------------------------------------------------------------------------ void SoundManager::setListenerTransform(const Matrix & transform) { // check if a sound device has been initialized if(!current_device_) { return; } listener_.position_ = transform.getTranslation(); listener_.direction_ = -transform.getZ(); listener_.up_ = transform.getY(); Vector orientation[2]; orientation[0] = listener_.direction_; orientation[1] = listener_.up_; alListenerfv(AL_ORIENTATION, (ALfloat*)&orientation); alListenerfv(AL_POSITION, (float*)&listener_.position_); } //------------------------------------------------------------------------------ void SoundManager::setListenerVelocity(const Vector & vec) { // check if a sound device has been initialized if(!current_device_) { return; } listener_.velocity_ = vec; alListenerfv(AL_VELOCITY, (float*)&vec); } //------------------------------------------------------------------------------ void SoundManager::setListenerGain(float volume) { // check if a sound device has been initialized if(!current_device_) { return; } listener_.gain_ = volume; alListenerf(AL_GAIN, (ALfloat)volume); } //------------------------------------------------------------------------------ const SoundListenerInfo & SoundManager::getListenerInfo() const { return listener_; } //------------------------------------------------------------------------------ bool SoundManager::checkForErrors(const std::string & context) { ALenum errorNr; bool ret = false; // check for alut errors if ((errorNr = alutGetError ()) != ALUT_ERROR_NO_ERROR) { s_log << Log::error << "Sound ALut: " << alutGetErrorString(errorNr) << "\n\tcontext: " << context << "\n"; ret = true; } // check for AL errors if ((errorNr = alGetError()) != AL_NO_ERROR) { s_log << Log::error << "Sound OpenAL: " << alGetString(errorNr) << "\n\tcontext: " << context << "\n"; ret = true; } // check for ALC errors if ((errorNr = alcGetError(current_device_)) != ALC_NO_ERROR) { s_log << Log::error << "Sound OpenAL Context: " << getALCErrorString(errorNr) << "\n\tcontext: " << context << "\n"; ret = true; } return ret; } //------------------------------------------------------------------------------ void SoundManager::toggleSoundEnabled() { sounds_enabled_ = !sounds_enabled_; } //------------------------------------------------------------------------------ bool SoundManager::isSoundEnabled() { return sounds_enabled_; } //------------------------------------------------------------------------------ bool SoundManager::existsDevice() const { return current_device_; } //------------------------------------------------------------------------------ /** * \brief returns true and gives the id of a free sound source or * returns false if no free sound source was available */ ALuint SoundManager::getFreeAlSoundSource() { SoundSourceMap::iterator it; for(it = sound_src_in_use_.begin();it != sound_src_in_use_.end(); it++) { if(!it->second) // if sound source is free { it->second = true; return it->first; } } s_log << Log::debug('S') << "Tried to create Sound Source, but no free Sources were available!!\n"; return 0; } //------------------------------------------------------------------------------ const SoundManager::SoundDeviceMap & SoundManager::getAvailableSoundDevices() const { return available_sound_devices_; } //------------------------------------------------------------------------------ /** * \brief "frees" a sound source inside sound manager to make it available * for use again. */ void SoundManager::releaseAlSoundSource(ALuint id) { SoundSourceMap::iterator it = sound_src_in_use_.find(id); if (it != sound_src_in_use_.end()) { it->second = false; } else { s_log << Log::warning << "SoundManager::releaseAlSoundSource: unknown source " << id << "\n"; } } //------------------------------------------------------------------------------ SoundSource * SoundManager::playSimpleEffect(const std::string & name, const Vector & pos, float rolloff_factor) { SoundSource * effect = new SoundSource(name); effect->setRolloffFactor(rolloff_factor); effect->setPosition(pos); s_scene_manager.getRootNode()->addChild(effect); effect->play(); return effect; } //------------------------------------------------------------------------------ SoundSource * SoundManager::playLoopingEffect(const std::string & name, osg::Group * parent) { SoundSource * effect = new SoundSource(name, SSCF_LOOP); parent->addChild(effect); effect->play(); return effect; } //------------------------------------------------------------------------------ /** * \brief Initializes a sound device selected with device_index from config file * Also prints out all devices available if parameter list_available_devices is set */ void SoundManager::initSoundDevices() { char *devices = (char *)alcGetString(NULL, DEVICES_SPECIFIER); // openal 0.8 - device enumeration is not implemented... // ignore error, default device will be selected afterwards ALenum error = alcGetError(NULL); if (error != ALC_INVALID_DEVICE && error != ALC_NO_ERROR) { s_log << Log::error << "Sound OpenAL Context: " << getALCErrorString(error) << "\n\tcontext: SoundManager::initSoundDevices\n"; } // copy for use below (alcGetString returns the full list only once) char *devices_selection = devices; bool device_initialized = false; const char *actual_device_name; unsigned index = 0; std::string actual_devices; while (*devices != '\0') { // try to open device ALCdevice *device = alcOpenDevice(devices); if(device != NULL) { // read device info for usable devices actual_device_name = alcGetString(device, DEVICES_SPECIFIER); std::string device_name; if(actual_device_name) { device_name = actual_device_name; } else { device_name = "Unknown sound device"; } actual_devices += "OpenAL device available: " + device_name + " with device index: " + toString(index) + "\n"; // store in map for available sound devices, used in options menu available_sound_devices_.insert(std::make_pair(index, device_name)); index++; alcCloseDevice(device); } // get next device from devices devices += strlen(devices) + 1; } // if a device has been manually selected with index number // try to open the selected device and create a context for the device index = 0; while (*devices_selection != '\0') { ALCdevice *device = alcOpenDevice(devices_selection); if(device != NULL) { // if device is the selected device, open context if(index == s_params.get<unsigned>("client.sound.device_index")) { ALCcontext *context = alcCreateContext(device, NULL); if (context) { alcMakeContextCurrent(context); device_initialized = true; break; } } index++; } devices_selection += strlen(devices_selection) + 1; } // if no devices have been found, try to make a fallback to default device if(actual_devices.empty() && device_initialized == false) { devices = (char *)alcGetString(NULL, DEFAULT_DEVICES_SPECIFIER); ALCdevice *device = alcOpenDevice(devices); if(device != NULL) { ALCcontext *context = alcCreateContext(device, NULL); if (context) { alcMakeContextCurrent(context); device_initialized = true; s_log << "Fallback to default sound device.\n"; available_sound_devices_.insert(std::make_pair(0, toString(alcGetString(device, DEVICES_SPECIFIER)))); } } } checkForErrors("after initializing devices"); if(!device_initialized && actual_devices.empty()) { s_log << Log::error << "OpenAL was not able to find any sound device on this computer!!\n"; return; } // print device info if(s_params.get<bool>("client.sound.list_available_devices")) { s_log << actual_devices; } // if no device could be initialized until now, something is terribly wrong // either an OpenAL error or the given device_index was wrong if(!device_initialized) { s_log << Log::error << "Error initializing sound device, check for OpenAL error or invalid device index!\n"; return; } current_context_ = alcGetCurrentContext(); current_device_ = alcGetContextsDevice(current_context_); sounds_enabled_ = s_params.get<bool>("client.sound.enabled"); // list all available device info for the currently selected device if(s_params.get<bool>("client.sound.show_device_info")) { int major, minor; actual_device_name = alcGetString(current_device_, DEVICES_SPECIFIER); alcGetIntegerv(current_device_, ALC_MAJOR_VERSION, sizeof(int), &major); alcGetIntegerv(current_device_, ALC_MINOR_VERSION, sizeof(int), &minor); s_log << " Sound device used: " << actual_device_name << ", Version: " << major << "." << minor <<"\n"; s_log << " Sound device vendor: " << alGetString(AL_VENDOR) << "\n"; s_log << " Sound device renderer: " << alGetString(AL_RENDERER) << "\n"; s_log << " Sound device version: " << alGetString(AL_VERSION) << "\n"; const char* exten = alcGetString(current_device_, ALC_EXTENSIONS); if(exten != NULL) { s_log << " Sound device (context specific) extensions: " << exten << "\n"; } s_log << " Sound device available extensions: " << alGetString(AL_EXTENSIONS) << "\n"; } } //------------------------------------------------------------------------------ /** * \brief this method creates the maximum number of sound sources * available on the target implementation and populates a * map that further on manages free sound sources. * This is done to avoid generating OpenAL sources on the * fly, because this may lead to OpenAL troubles. */ void SoundManager::createALSoundSources() { const unsigned MIN_NUMBER_SOUCRES_WARNING = 8; checkForErrors("SoundManager::createALSoundSources"); // try to create as much sources as possible for(unsigned s=0; s<MAX_NUMBER_SOURCES; s++) { ALuint src_id = 0; alGenSources(1, &src_id); if ((alGetError() == AL_NO_ERROR) && (alIsSource(src_id))) { sound_src_in_use_.insert(std::make_pair(src_id, false)); continue; } // sound source creation went wrong, stop creating break; } if(sound_src_in_use_.size() < MIN_NUMBER_SOUCRES_WARNING) { s_log << Log::warning << " There are less than " << MIN_NUMBER_SOUCRES_WARNING << " sound sources available! Available sources: " << sound_src_in_use_.size() << "\n"; } else { s_log << Log::debug('i') << "Available Sound Sources: " << sound_src_in_use_.size() << "\n"; } if(sound_src_in_use_.empty()) { throw Exception("Unable to create any OpenAL Sound Source!!"); } } //------------------------------------------------------------------------------ std::string SoundManager::getALCErrorString(ALenum err) { switch(err) { case ALC_NO_ERROR: return std::string("AL_NO_ERROR"); break; case ALC_INVALID_DEVICE: return std::string("ALC_INVALID_DEVICE"); break; case ALC_INVALID_CONTEXT: return std::string("ALC_INVALID_CONTEXT"); break; case ALC_INVALID_ENUM: return std::string("ALC_INVALID_ENUM"); break; case ALC_INVALID_VALUE: return std::string("ALC_INVALID_VALUE"); break; case ALC_OUT_OF_MEMORY: return std::string("ALC_OUT_OF_MEMORY"); break; default: return std::string("unkown ALC Error"); } }
f707b2f35253ffe5774741beed693c76fe396e5c
4f5691998e1e55451b17fe6c0d35f294cc38c405
/TR_List_Reorder_Testing.hpp
84bae971f00016f276a8586e30012ffb9843a31b
[ "BSD-3-Clause" ]
permissive
PankeyCR/aMonkeyEngine
9bb3c3f89ec9cab2a181f3cfd43d89f379a39124
a5fb3f7f73f51b17cfe90f6fc26c529b7e8e6c2d
refs/heads/master
2023-06-22T01:36:55.745033
2023-06-15T22:03:09
2023-06-15T22:03:09
198,529,019
1
0
null
null
null
null
UTF-8
C++
false
false
1,617
hpp
TR_List_Reorder_Testing.hpp
#ifndef TR_List_Reorder_Testing_hpp #define TR_List_Reorder_Testing_hpp #include "TestResult.hpp" #include "TR_Full_List_Testing.hpp" namespace ame{ TestResult TR_List_Reorder_Testing(){ TestResult result; for(int x = 0; x < tipesOfLists(); x++){ RawList<int>* list = getList<int>(x); if(list == nullptr){ result.catchError(0, getListName(x) + Note(" Contructor creates a nullptr pointer")); continue; } list->setReorder(false); list->add(1); list->add(2); list->add(3); list->add(4); list->add(5); if(list->getPosition() != 5){ result.catchError(1, getListName(x) + Note(" add is not working")); } if( list->getByIndex(0) != 1 || list->getByIndex(1) != 2 || list->getByIndex(2) != 3 || list->getByIndex(3) != 4 || list->getByIndex(4) != 5 ){ result.catchError(2, getListName(x) + Note(" getByIndex not working")); } list->removeByIndex(1); list->removeByIndex(3); if(list->getPosition() != 5){ result.catchError(3, getListName(x) + Note(" removeByIndex is not working")); } if( list->getByPosition(1) != nullptr || list->getByPosition(3) != nullptr ){ result.catchError(4, getListName(x) + Note(" reorder not working")); } list->set(1, 2); list->set(3, 4); if( list->getByIndex(0) != 1 || list->getByIndex(1) != 2 || list->getByIndex(2) != 3 || list->getByIndex(3) != 4 || list->getByIndex(4) != 5 ){ result.catchError(5, getListName(x) + Note(" getByIndex not working")); } delete list; } return result; } } #endif
1ef13d4df19be6702b3b213d9e925daba54681c3
3bb59c7368e997077567b6b3a21c92ae02e36d9a
/Palindrome Number/Solution.cpp
45f75d59792d9d7d1819051004033ebfdd73c38c
[]
no_license
LittleFish33/MyLeetCode
ad0607fd34f145cdc04ed6a41f6059d4135d125e
5a019abea51e3d2e893524631f29372058a3202f
refs/heads/master
2020-03-28T02:00:35.602747
2018-10-07T09:03:49
2018-10-07T09:03:49
147,541,093
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
Solution.cpp
class Solution { public: bool isPalindrome(int x) { if(x < 0){ return false; } int arr[10]; int j = 0; while(x > 0){ arr[j++] = x%10; x/=10; } int temp = j-1; for(int i = 0;i < j/2;i++){ if(arr[i] != arr[temp--]){ return false; } } return true; } };
1fff2cfddf0600123b1cdc01770a1b93cb1c1b57
d05cfbb1443450e8bedc6fb8908b6a6b0d06db3c
/gfg_CPP/string4.cpp
0470323576df2dbf1306301646bca2a192b0539a
[]
no_license
mdyaseenahmed/CPP
bfbc1c63150e13d33d8d89fe036b4e623c95acf6
cbf66dbc12c6c1ed6f4cee1e233f0722e8b5e320
refs/heads/main
2023-01-30T15:55:05.328240
2020-12-03T09:01:13
2020-12-03T09:01:13
318,133,024
0
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
string4.cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { string s1("First"); string s2("second"); s1.append(s2); cout << s1 << endl; // Firstsecond // substr(a,b); string s3 = s1.substr(0, 7); cout << s3 << endl; // Firstse return 0; }
0b519922390e869f5996e8c876d74164cb06036c
a859e6906041ea350a5f1f40bacf0305a850073c
/overflow/overflow.cpp
76b347c7dd92ef828a05e449595f117027dd81d4
[]
no_license
asdfvar/misc
f9756d656123e99f6498e7d1b37645fe9d109b4f
84c9e2268898a77e2d7122adb20ad9deebe0f530
refs/heads/master
2022-02-24T20:21:51.354922
2022-02-11T22:49:58
2022-02-11T22:49:58
93,337,184
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
overflow.cpp
#include<iostream> int main() { unsigned long n = 1; // max is 4294967296; unsigned long k = 7; unsigned long p; p = n - k; std::cout << "1 - 7 = " << p << " > 10 " << (p > 10) << std::endl; return 0; }
bc475ea9da9e61ec947771a5bbd63ca1c5548873
f18ecfa88f3772e6924564e3e1ecd2f59d0051d9
/模版汇总/numberTheory-csuchenan.cpp
ab22ca851299eaa2ac43694135ccb17f145e5228
[]
no_license
howardchina/ACM_DIY_Library_code
813c39d67d920bea6baafc4073a0629979ccb04f
c01f2275349bbe4a5c967be47bb1092566aeff06
refs/heads/master
2020-04-01T21:23:56.605065
2018-10-18T18:25:52
2018-10-18T18:25:52
153,653,804
0
0
null
null
null
null
GB18030
C++
false
false
5,454
cpp
numberTheory-csuchenan.cpp
#include <stdio.h> #include <string.h> #include <algorithm> #include <math.h> typedef long long lint; #define MAX (1LL<<60) /*** A^B%C if(B > C) then B = B%(euler(c)) + euler(c); ***/ lint power_mod(lint A, lint B, lint C = MAX){ lint res = 1; for(;B;B>>=1){ if(B&1) res = res * A %C; A = A * A%C; } return res; } lint gcd(lint a, lint b){ return b==0?a:gcd(b, a%b); } void extgcd(lint a, lint b, lint &g, lint &x, lint &y){ if(b==0){ g = a, x = 1, y = 0; return; } extgcd(b, a%b, g, y, x); y-=a/b*x; } /***** prim[] ****/ const int maxn = 100005; bool ff[maxn]; int pm[maxn/5], tot; void init(){ for(int i = 2; i < maxn; i ++){ if(!ff[i]){ pm[tot ++] = i; for(int j = i+i; j < maxn; j += i){ ff[j] = 1; } } } } /***** factor n ****/ int factor(int n, int a[], int b[]){ int tot = 0; for(int i = 0; (lint)pm[i]*pm[i] <= n; i ++){ if(n%pm[i]==0){ a[tot] = pm[i]; for(b[tot] = 0; n%pm[i]==0; n/=pm[i]) b[tot] ++; tot ++; } } if(n!=1) a[tot] = n, b[tot ++] = 1; return tot; } /*ax = b (mod c) x = x0 + t*k ,t = c/g, then in [0, c) there g solutions */ lint solution(lint a, lint b, lint c){ lint x, y, g; extgcd(a, c, g, x, y); if(b%g) return -1; int t = c/g, s = b/g; x = x * s %t; return (x + t)%t; } /*** ax = 1 (mod c) ***/ lint inv(lint a, lint c){ //return power_mod(a, c-2, c); lint g, x, y; extgcd(a, c, g, x, y); return g == 1 ? (x%c + c)%c : -1; } /*** LCM ***/ lint LCM(lint a, lint b){ return a/gcd(a,b)*b; } /*** A * B % C; ***/ lint mul_mod(lint a, lint b, lint c){ a = a%n; lint res = 0; for(;b; b>>=1){ if(b&1){ res = res + a; if(res >= n) res = res - n; } a = a<<1; if(a>=n) a = a - n; } return res; } /*** A1x = B1 mod M1 A2x = B2 mod M2 A3x = B3 mod M3 ............... Anx = Bn mod Mn 转变为: x = b1 mod r1 x = b2 mod r2 x = b3 mod r3 ............. x = bn mod rn ***/ /** x = R[i]%A[i]; 0 =< i < n **/ pair<int, int> reminder(lint A[], lint R[], int n){ LL tm = A[0], tr = R[0], g, x, y; for(int i = 1; i < n; i ++){ extgcd(tm, A[i], g, x, y); if((tr-R[i])%g){ return make_pair(0, -1); } x = (R[i] - tr)/g * x; x = (x%(A[i]/g)+A[i]/g)%(A[i]/g); tr = tm * x + tr; tm = LCM(tm, A[i]); tr = (tr%tm + tm)%tm; } return make_pair(1, tr); } /*** m[i]两两互质 ***/ lint chineseReminder(lint a[], lint m[], lint n){ lint M = 1, ans = 0, x, y, g; for(int i = 0; i < n; i ++) M *= m[i]; for(int i = 0; i < n; i ++){ lint mi = M/m[i]; extgcd(mi, m[i], g, x, y); ans = (ans + a[i]*mi*x)%M; } return (ans%M+M)%M; } /*euler*/ lint euler(lint n){ lint res = n; for(int i = 2; i*i <= n; i ++){ if(n%i==0){ res = res/i*(i-1); while(n%i==0) n=n/i; } } if(n!=1) res = res /n*(n-1); return res; } /*** C(n, m)%p, n,m<10^9, p<100000; fac[k] = k!%p ***/ void init(lint p){ fac[0] = 1; for(int i = 1; i <= p; i ++){ fac[i] = fac[i-1]*i%p; } } lint C(lint n, lint m, lint p){ return n>=m? fac[n]*power_mod(fac[k]*fac[n-k]%p, p-2, p)%p:0; } lint lucas(lint n, lint m, lint p){ lint ans = 1; while(n&&m&ans){ ans = ans * C(n%p, m%p, p)%p; n/=p; m/=p; } return ans; } /*** 扩展BSGS ***/ const int SIZE = 65535; struct HashMap{ struct Edge{ lint y, L; Edge*next; }*ls[SIZE+1], g[SIZE+10]; int e; void init(){ e = 0; memset(ls, 0, sizeof(ls)); } void add(lint y, lint L){ if(find(y) != -1) return; g[e].y = y; g[e].L = L; g[e].next = ls[y&SIZE]; ls[y&SIZE] = &g[e ++]; } lint find(lint y){ for(Edge*t = ls[y&SIZE]; t; t = t->next){ if(t->y ==y) return t->L; } return -1; } }hash; lint BabyStepGiantStep(lint A, lint B, lint C){ hash.init(); lint tmp, D = 1%C, Giant, i, x, g, S; for(i = 0, tmp = 1%C; i <=100; tmp = tmp*A%C, i ++){ if(tmp == B) return i; } for(x = 0; (g = gcd(A, C))!=1; x ++){ if(B%g) return -1; C/=g , B/=g, D=D*(A/g)%C; } S = (Lint)Ceil(sqrt(C*1.0)); for(tmp = 1%C, i = 0; i <= S; i ++, tmp = tmp * A%C){ hash.add(tmp, i); } for(i = 0, Giant = power_mod(A, S, C); i <= S; D = D * Giant%C, i ++){ lint t = inv(D, B, C); if((tmp = hash.find(t))!= -1){ return S * i + tmp + x; } } return -1; } /**** find the root of C *****/ const int maxm = 205; int findRoot(int n, int phi){ static int a[maxm], b[maxm]; int t = factor(phi, a, b); for(int g = 2, i; g < n; g ++){ for(i = 0; i < t; i ++){ if(power_mod(g, phi/a[i], n)==1) break; } if(i==t) return g; } return -1; } /****** a^x = b(mod c) ******/ lint log_x(lint a, lint b, lint c){ map<lint, lint> hh; lint S = (int)ceil(sqrt(c*1.0)); //note that if gcd(a, c)!=1 then the inv should be caculated by extgcd lint t = 1, v = inv(power_mod(a, S, c), c); for(int i = 0; i < S; i ++){ if(hh.count(t)==0) hh.insert(make_pair(t, i)); t = t * a%c; } for(int i = 0; i < S; i ++){ if(hh.count(b)) return i * S + hh[b]; b = b * v %c; } } /***** caculate the number of solutions of equation x^a=b(mod c) first split c into pi^ai then for eact equation: x^a = b(moc pi^ai) suppose that there are ci distinct solutions for this equation then the number of solutions of original equation is the multiply of ci *****/ lint process(lint A, lint B, lint p, lint k){ lint P = pow_mod(p, k); if(B%=P, B){ return pow_mod(p, k - (int)ceil(k*1.0/A)); } lint d = 0; for(;B%p==0;B/=p) d ++, P/=p; if(d%A) return 0; lint r = findRoot(P, P/p*(p-1)); lint m = log_x(r, B, P); d = gcd(A, P/p*(p-1)); return m%d ? 0 : d; } /*** 佩尔方程 ***/
cec5f863556b5ce524cf7e001481e08094f9453d
34e5a86a2708aeaae750818062996af8b6043472
/src/Queue.cpp
61426f40eb645e725a9955a6c35e6c759643d419
[]
no_license
mitical99/OSProject
3bfdeda274febf0481ceae6b3046c2b89fe78747
431e01cda8829cabe1c25fbf7ddd6414e92b864e
refs/heads/main
2023-01-06T00:18:39.696326
2020-11-10T11:06:06
2020-11-10T11:06:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
Queue.cpp
/* * Queue.cpp * * Created on: Apr 18, 2020 * Author: Aleksa Mitic 0025/2018 */ #include"Queue.h" #include"System.h" #include"pcb.h" #include"SCHEDULE.H" extern int syncPrintf(const char* format,...); Queue::Queue() { //lock first=0; last=0; count=0; //unlock } int Queue::size() const { return this->count; } void Queue::put(PCB* p) { lock //syncPrintf("%d ",time); Elem *e=new Elem(p); if(first==0) { first=e; last=first; } else { last->next=e; last=last->next; } count++; unlock } PCB* Queue::get() { if(first==0) return 0; lock Elem *e=first; first=first->next; if(first==0) last=0; count--; PCB* tmp=e->pcb; delete e; unlock return tmp; } Queue::~Queue() { lock Elem* tek; while(first!=0) { tek=first; first=first->next; delete tek; count--; } last=0; first=0; unlock } PCB* Queue::get(unsigned id) { lock for(Elem* cur=first;cur!=0;cur=cur->next) { if((cur->pcb->getThread())->getID()==id) {unlock; return cur->pcb;} } unlock return 0; }
5ed3b35107ad9f7e9ebabbff1cbd7497be9f681e
794e310f8fa26a70f05d9d70cdf038f12889a6c5
/homework1/src/try.h
5e884d6358865ec3955085a3270710cb07f1d3bf
[]
no_license
xiangyu-peng/CS106b
e75ee41312a80f567a651275bbce5dab45bec2d6
72990d65252f3be43ac4743568e2b0b47b0b83a2
refs/heads/master
2021-09-09T12:42:48.957005
2018-03-16T06:57:25
2018-03-16T06:57:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
90
h
try.h
#ifndef TRY_H #define TRY_H class try { public: try(); }; #endif // TRY_H
b4c1640629c185ceb405564b2c122434b5419db3
c5b6317924cbb630ec2ae799f8ebbcb7966af5c0
/Practice2/Practice2/stack.cpp
b4a5b867d1f3d4de6667fe449d48566b7947e565
[]
no_license
beaming-sunshine/ds_exp
0ddd53928d6fba5e3edc9a1a4c4fb3088d271687
4eb12074a4175d2003c9d22f40b2b2a7d9d545da
refs/heads/master
2022-11-28T03:03:23.589520
2020-08-05T11:19:27
2020-08-05T11:19:27
285,264,459
0
0
null
null
null
null
GB18030
C++
false
false
796
cpp
stack.cpp
#include<iostream> #include "stack.h" using namespace std; const int Stack_init_size = 100; const int Stack_increment = 10; //构造函数 stack::stack() { str_arr = new char[Stack_init_size]; if (!str_arr){ cout << "arr malloc error!" << endl; } } //析构函数 stack::~stack() { if (str_arr){ delete[] str_arr; str_arr = NULL; } } //向栈中添加一个e元素 void stack::push(char e) { str_arr[stacksize++] = e; } //向栈中取出一个元素 char stack::getTop() { return str_arr[stacksize - 1]; } //在栈中删除一个元素 char stack::pop() { char top = str_arr[stacksize-1]; stacksize--; return top; } //求栈的长度 int stack::stack_size() { return stacksize; } //检验栈是否为空(1为空) int stack::isEmpty() { return stack_size() == 0; }
cac7cc9634f47a46fcb22e7d1fa7d64c62efd56d
8b6647df1a5bacfe1cc4e55e1310a4e95bf9f665
/RayTracerDemo/Attribute.h
a844bf98e03416e0dd2de44f0fbcec44a5821f84
[]
no_license
mumuxijili/RayTracerDemo
f9d9e408e16f8b4a9119cf341d078fe4028481ec
b3079c2c3ad2e9952b7661f55e35d031a2956c74
refs/heads/master
2021-01-23T05:09:48.225992
2017-03-31T07:34:07
2017-03-31T07:34:07
86,281,192
0
0
null
null
null
null
GB18030
C++
false
false
2,502
h
Attribute.h
#ifndef __ATTRIBUTE_H__ #define __ATTRIBUTE_H__ #include "Shapes.h" #include <random> #include <ctime> #define SHADOW_SAMPLE 10 class Color { public: float r, g, b; Color(); Color(float _r, float _g, float _b); virtual ~Color(); Color add(const Color& c); Color multiply(float s) const; Color modulate(const Color& c) const; Color divide(float d) const; void saturate(); static inline Color black() { return Color(0, 0, 0); } static inline Color white() { return Color(1, 1, 1); } static inline Color red() { return Color(1, 0, 0); } static inline Color green() { return Color(0, 1, 0); } static inline Color blue() { return Color(0, 0, 1); } static inline Color shadow() { return Color(0.2, 0.2, 0.2); } }; class Ray; //Base class for materials class Attribute { public: Attribute(); Attribute(float _reflectiveness); void setRef(float _reflectiveness); float getRef(); // 采样,光线ray在法向为normal,位置为position的点上的颜色 virtual Color sample(Ray& ray, glm::vec3& position, glm::vec3& normal); virtual ~Attribute(); protected: float reflectiveness; }; //Chess Board Material class ChessMat : public Attribute { public: ChessMat(); ChessMat(float _scale, float _reflectiveness = 0); Color sample(Ray& ray, glm::vec3& position, glm::vec3& normal); ~ChessMat(); private: float scale; }; //temporary global settings static glm::vec3 lightDir = glm::normalize(glm::vec3(0, 1.5, 1)/*(1, 1, 1)*/); // parallel light static Color lightColor = Color::white(); //Blinn-Phong Material class PhongMat : public Attribute { public: PhongMat(); //pointLight PhongMat(const Color& _diffuse, const Color& _specular, float _shininess, bool _usePointLight, glm::vec3 _pointLightPos, Color _pointLightColor, float _reflectiveness = 0.0f); //directLight PhongMat(const Color& _diffuse, const Color& _specular, float _shininess, float _reflectiveness = 0.0f); //faceLight PhongMat(const Color& _diffuse, const Color& _specular, float _shininess, bool _useFaceLight, glm::vec3 _faceLightPos, Color _faceLightColor, glm::vec3 _dx, glm::vec3 _dy, float _reflectiveness = 0.0f); glm::vec3 randPoint(); Color sample(Ray& ray, glm::vec3& position, glm::vec3& normal); ~PhongMat(); private: Color diffuse; Color specular; float shininess; bool usePointLight = false; glm::vec3 pointLightPos; Color pointLightColor; bool useFaceLight = false; glm::vec3 faceLightPos; glm::vec3 dx; glm::vec3 dy; Color faceLightColor; }; #endif // __ATTRIBUTE_H__
986cdf0d8a8cf954e5eb07523ac8daa76420b6e9
1bb356c30e9d18404138d2b12ff2ad7d6de656b2
/canscope/device/data_collecter.h
5fd39c6dd7e608f1389bec79677538c94aa272be
[]
no_license
cha63506/device_operate
b6bd9f82dfd2f093ea1ef8a2600113f65e9ff2e6
0e8af1ad0552754f942217189029d773b52e21cf
HEAD
2018-05-05T13:53:33.634646
2014-06-16T08:33:52
2014-06-16T08:33:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
data_collecter.h
#pragma once #include "base/memory/ref_counted.h" #include "base/callback.h" #include "base/single_thread_task_runner.h" #include "base/observer_list_threadsafe.h" #include "canscope/device/threaded_loop_run.h" // call Start() Stop() according thread and get notify at each thread // the add observer class DataCollecter : public ThreadedLoopRun { public: DataCollecter() {} // data collect freq void SetFreq(double freq); double Freq() const; // call when back online void ReRun(); void set_stop_by_offine(bool value) { stop_by_offine_ = value; } bool stop_by_offine() const { return stop_by_offine_; } enum LoopState { // call loop next message loop NEXT_LOOP, // call loop in this message loop IMMEDIATE, // stop, wait for some one call star again. STOP, }; protected: virtual ~DataCollecter() {} virtual LoopState OnLoopRun() = 0; private: // implement ThreadLoopRun virtual bool LoopRunImp() OVERRIDE; bool stop_by_offine_; base::Lock lock_; };
6148d36c59268fa6f7498819f7e5d072a590d021
1e0d7f4789c3ee7b5457ae24a50e3269b749eb3b
/Client/login.cpp
a1387223dcb85f4b9eb97cdb563d32016136f30c
[]
no_license
VlullabyV/LinChat
72f4b6b2e05414b1c5370dea90b2ec828264cfcf
41c5e953a2879b432697edfe9bf122604f558f48
refs/heads/master
2021-05-07T22:06:28.100264
2017-04-24T03:03:53
2017-04-24T03:03:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,265
cpp
login.cpp
#include "login.h" #include <QMessageBox.h> CLogin::CLogin(QWidget *parent) : QDialog(parent) { ui.setupUi(this); port = 7750; } CLogin::CLogin(QTcpSocket *s) :Socket(s) { ui.setupUi(this); port = 7750; } CLogin::~CLogin() { } void CLogin::receiveMessage(void) { QDataStream oStream(Socket); qint32 msgID; oStream >> msgID; switch (msgID) { case SC_Login: msg_login(oStream); break; default: break; } } void CLogin::on_button_login_clicked() { QHostAddress addr(ui.edit_addr->text()); Socket->connectToHost(addr, port); connect(Socket, SIGNAL(connected()), this, SLOT(processConnection())); connect(Socket, SIGNAL(readyRead()), this, SLOT(receiveMessage())); quint32 uid = ui.edit_uid->text().toUInt(); QString pwd = ui.edit_password->text(); QByteArray datagram; QDataStream iStream(&datagram, QIODevice::WriteOnly); iStream << CS_Login << uid << pwd; Socket->write(datagram); } void CLogin::msg_login(QDataStream &oStream) { bool bRes; oStream >> bRes; if (!bRes) { QMessageBox::warning(this, tr("Warning"), tr("username or password error!"), QMessageBox::Yes); ui.edit_uid->setText(""); ui.edit_password->setText(""); return; } accept(); }
0f6c05b588f7586e45d0447df996e1ea0056c062
dd7dbf840773ce4fd67637a32ed2a3b3c15a39b9
/src/dort/dot_renderer.cpp
a1773d24d6fd44e9b3efca7c7c4d3bce38ce18ad
[]
no_license
honzasp/dort
5549cd7ee3bf22eaf1348cbb72cb63614c3ce243
7050e24f293a6762230d964616e58904cab3c8f2
refs/heads/master
2021-01-22T11:07:20.827738
2017-06-29T10:07:23
2017-06-29T10:07:23
50,340,154
3
1
null
null
null
null
UTF-8
C++
false
false
1,628
cpp
dot_renderer.cpp
#include "dort/bsdf.hpp" #include "dort/camera.hpp" #include "dort/dot_renderer.hpp" #include "dort/film.hpp" #include "dort/primitive.hpp" #include "dort/scene.hpp" #include "dort/spectrum.hpp" #include "dort/vec_2i.hpp" namespace dort { void DotRenderer::render(CtxG& ctx, Progress&) { bool jitter = this->iteration_count > 1; for(uint32_t i = 0; i < this->iteration_count; ++i) { this->iteration_tiled(ctx, [&](Vec2i pixel, Vec2& film_pos, Sampler& sampler) { Vec2 pixel_pos = jitter ? sampler.random_2d() : Vec2(0.5f, 0.5f); film_pos = Vec2(pixel) + pixel_pos; Ray ray; float ray_pos_pdf; float ray_dir_pdf; Spectrum importance = this->camera->sample_ray_importance(Vec2(this->film->res), film_pos, ray, ray_pos_pdf, ray_dir_pdf, CameraSample(sampler.rng)); Spectrum color = this->get_color(ray); return color * importance / (ray_pos_pdf * ray_dir_pdf); }); } } Spectrum DotRenderer::get_color(Ray& ray) const { Intersection isect; if(!this->scene->intersect(ray, isect)) { return Spectrum(0.f); } auto bsdf = isect.get_bsdf(); float isect_dot = dot(-normalize(ray.dir), isect.world_diff_geom.nn); bool emittor = !isect.eval_radiance(ray.orig).is_black(); bool specular = bsdf->bxdf_count(BSDF_MODES | BSDF_DELTA) > 0; bool backside = isect_dot < 0.f; float red = backside ? 0.8f : 0.5f; float green = emittor ? 0.8f : 0.5f; float blue = specular ? 0.8f : 0.5f; Spectrum color = Spectrum::from_rgb(red, green, blue); return color * abs(isect_dot); } }
4bf2e249db1b2a1c0dea6b1e8fc91aadb1cf1131
8ae31e5db1f7c25b6ce1c708655ab55c15dde14e
/比赛/学校/2019-11-11测试2/source/PC34_HB-与董小/chessboard.cpp
8dbbd9e12d0ccc5fc581ad281e358cf4bb7fe006
[]
no_license
LeverImmy/Codes
99786afd826ae786b5024a3a73c8f92af09aae5d
ca28e61f55977e5b45d6731bc993c66e09f716a3
refs/heads/master
2020-09-03T13:00:29.025752
2019-12-16T12:11:23
2019-12-16T12:11:23
219,466,644
1
0
null
null
null
null
UTF-8
C++
false
false
2,154
cpp
chessboard.cpp
#pragma GCC optimize(3) #pragma GCC optimize("Ofast") #pragma GCC target("avx") #include<cstdio> #include<cstring> #include<cstdlib> #include<cassert> #include<climits> #include<ctime> #include<cmath> #include<algorithm> #include<bitset> #include<iostream> #include<stack> #include<map> #include<queue> #include<vector> #define ll long long #define INF 0x3f3f3f3f inline int read() { int out=0,fh=1; char cc=getchar(); if (cc=='-') fh=-1; while (cc>'9'||cc<'0') cc=getchar(); while (cc>='0'&&cc<='9') { out=out*10+cc-'0'; cc=getchar(); } return out*fh; } inline void write(int x) { register int i; if(x==0) { putchar('0'); putchar('\n'); return; } if(x<0) { putchar('-'); x=-x; } char s[22]; int l=0; while(x^0) { s[++l]=x%10+48; x/=10; } for(i=l;i>=1;--i) putchar(s[i]); putchar(' '); } struct que { int opt,k,sx,sy,tx,ty; }que[100010]; int n,m,a[1001][1001]; int vec[100010],tot; struct edit { int k,sx,sy,tx,ty; edit(){} edit(int k,int sx,int sy,int tx,int ty):k(k),sx(sx),sy(sy),tx(tx),ty(ty){} }seq[100010]; int len(0); signed main() { freopen("chessboard.in","r",stdin); freopen("chessboard.out","w",stdout); n=read(); m=read(); m=read(); register int i,j; for(i=1;i<=m;i++) { #define q(p) que[i].p char opt[5]; scanf("%s",opt); if(opt[0]=='P') { q(opt)=1; q(k)=read(); q(sx)=read(); q(sy)=read(); q(tx)=read(); q(ty)=read(); q(sx)++; q(sy)++; q(tx)++; q(ty)++; } else if(opt[0]=='S') { q(opt)=2; vec[++tot]=i; } else { q(k)=read(); q(opt)=3; } #undef q } for(i=m;i>=1;i--) { #define q(p) que[i].p if(q(opt)==2) continue; if(q(opt)==3) { i=vec[q(k)]; continue; } seq[++len]=edit(q(k),q(sx),q(sy),q(tx),q(ty)); #undef q } std::reverse(seq+1,seq+len+1); for(i=1;i<=n;i++) for(j=1;j<=n;j++) a[i][j]=1; for(register int p=1;p<=len;p++) { edit S=seq[p]; for(i=1;i+S.sx-1<=S.tx;i++) for(j=1;j+S.sy-1<=S.ty;j++) if(!((i&1)^(j&1))) a[i+S.sx-1][j+S.sy-1]=S.k; } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) write(a[i][j]); putchar('\n'); } return 0; }
d898d4292e027b8d3306e52d3f6b004f0027f1c0
dccc8885ff0e21721b1f4d3dbbe167f0e1d954fa
/leetcode/ContainsDuplicateII.cpp
e1274fc8e0e55c2438acd1584e6cf1015c578f0e
[]
no_license
XiaoxiongZheng/Algorithms
289721177a2336d08fe5ba29593beabbf57e3023
7be8767511f99c27d54076c4cc996f709efce305
refs/heads/master
2020-05-03T07:07:58.557835
2015-08-13T06:26:45
2015-08-13T06:26:45
24,021,322
0
0
null
null
null
null
UTF-8
C++
false
false
556
cpp
ContainsDuplicateII.cpp
// // Created by zhengxx on 15/8/5. // #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> um; for (int i = 0; i < nums.size(); i++) { if (um.find(nums[i]) == um.end()) { um[nums[i]] = i; } else { if (abs(um[nums[i]] - i) <= k) return true; um[nums[i]] = i; } } return false; } };
e706498d38339a8fe991815b74c14e6cd5eb8617
6f5a72debacfacab4adc1d26a11de06f9f898fda
/tvapp/Classes/GameCamera.h
5a4dbafc3b9ac7ea9c857f8e0134d64e842280bf
[ "MIT" ]
permissive
iacopocheccacci/cocos2dx-helloWorld-tvOS
5c51b2aa098cc7997c54e53112e2d63477cdcaaf
ae08efb0b1a52e8b5fd0bbeea397f3c56c33f58e
refs/heads/master
2021-01-09T06:59:17.063539
2015-10-20T17:03:16
2015-10-20T17:03:16
44,961,103
0
0
null
2015-10-26T10:20:38
2015-10-26T10:20:36
null
UTF-8
C++
false
false
10,023
h
GameCamera.h
// // GameCameraNew.h // SongOfPan // // Created by Leonardo Passeri on 02/04/15. // // #ifndef __SongOfPan__GameCameraNew__ #define __SongOfPan__GameCameraNew__ #include "cocos2d.h" #include "LinearInterpolation.h" USING_NS_CC; class GameCamera { public: enum class SizeConstraint { WIDTH = 0, HEIGHT, BOTH }; virtual ~GameCamera(); GameCamera(Node * target, const Rect worldBoundaries, const bool clampOnBoundaries); // // GENERAL // void update(float dt); // // FOLLOW // /* Imposta il nodo da seguire, alla velocità data e, eventualmente, con movimento smussato. */ void setFollowNode(Node * followedNode, const float speed, const bool smoothMovement); /* Imposta l'offset che definisce il punto da inquadrare rispetto al followed node */ void setFollowedNodeOffset(const Point offset); /* Imposta il nodo da seguire, lasciando invariati velocità e opzione di movimento smussato. */ void setFollowNode(Node * followedNode); /* Imposta la velocità con cui la telecamera si avvicina al followed node, con eventuale opzione di movimento smussato. */ void setFollowedNodeSpeed(const float speed, const bool smoothMovement); /* Imposta il rettangolo, relativo alla telecamera, entro il quale non avviene follow */ void setFollowedArea(const Rect followArea); /* Attiva/Disattiva la modalità follow */ void setFollowEnabled(const bool followEnabled); /* Forza l'aggiornamento della destinazione di panning sul followNode + offset. */ void resetFollow(); // // ZOOM // /* Effettua lo zoom della telecamera (scale del target) al valore dato alla velocità data e, eventualmente, con effetto smussato. */ void zoomToScale(const float scale, const float speed, const bool smoothMovement); /* Aggiorna il valore di zoom da raggiungere, lasciando inalterati la velocità e la preferenza per il movimento smussato precedentemente indicati. */ void setZoomScale(const float scale); /* Aggiorna il valore di velocità dello zoom, con eventuale opzione di movimento smussato. */ void setZoomSpeed(const float speed, const bool smoothMovement); /* Forza istantaneamente la telecamera ad uno specifico zoom. Non altera i valori di speed e smooth precedentemente assegnati. NOTA: settare forzatamente lo zoom viola le regole comportamento della telecamera, per cui usare limitatamente (es.: inizializzazione) */ void forceZoomToScale(const float scale); // // PANNING // /* Effettua il panning della telecamera alla posizione data alla velocità data e, eventualmente, con movimento smussato. */ void panToLocation(const Point location, const float speed, const bool smoothMovement); /* Effettua il panning istantaneo della telecamera sul nodo dato, con l'offset dato. */ void centerCameraOnNode(const Node * node, const Point offset); // Utilities float zoomClampToSizeForScale(const float scale); // // ATTRACTORS // /* Aggiunge un attrattore con posizione, raggio interno ed esterno dati. Lo zoom che si avrà all'interno del raggio interno sarà quello fa coincidere lo schermo dentro al size dato, vincolandolo in ampiezza, altenzza o entrambi in base al sizeConstraint dato. La chiave data verrà utilizzata per l'eventuale rimozione dell'attrattore. */ void addAttractor(const Point position, const Size targetScreenSize, const float innerRadius, const float outerRadius, const SizeConstraint sizeConstraint, const std::string key); /* Aggiunge un attrattore con posizione, zoom, raggio interno ed esterno dati. La chiave data verrà utilizzata per l'eventuale rimozione dell'attrattore. */ void addAttractor(const Point position, const float zoom, const float innerRadius, const float outerRadius, const std::string key); /* Rimuove l'attrattore corrispondente alla chiave data */ void removeAttractor(const std::string key); /* Attiva/disattiva gli attrattori */ void setAttractorsEnabled(const bool enabled); // // RAILS // void addRail(const Rect areaOfEffect, const Point startProjectionPoint, const Point endProjectionPoint, const std::vector<Point> pathPoints, const Size pathScreenSize, const std::string key); void removeRail(const std::string key); void setRailsEnabled(const bool enabled); // // ACCESSORS // Node * getTarget() { return _target; }; float getCurrentZoom(); Point getCurrentPosition(); void setWorldBoundaries(const Rect worldBoundaries); Rect getWorldBoundaries() { return _worldBoundaries; }; void setClampOnBoundaries(const bool clamp) { _clampOnBoundaries = clamp; }; bool isClampOnBoundaries() { return _clampOnBoundaries; }; void setSoftBoundariesX(const bool soft); void setSoftBoundariesY(const bool soft); bool isSoftBoundariesX() { return _softBoundariesX; } bool isSoftBoundariesY() { return _softBoundariesX; } Rect getFollowBoundingArea() { return _followBoundingArea; }; Point getFollowedNodeOffset() { return _followedOffset; }; float getMinZoomScaleForBoundaries(); float getMinZoomScaleForSize(Size size); Point getPanningDestination() { return _panningDestination; }; float getZoomDestination() { return _zoomDestination; }; // // DEBUG // /* Attiva/disattiva la modalità debug: - Draw della followBoundingArea (rect bianco); - Draw dei bordi del mondo - con un padding di 10 pixel perché sennò non si vedono (rect bianco); - Draw del centro dello schermo (pallino bianco); - Draw della destinazione di panning (pallino grande rosso) - Draw dell'offset del followNode (pallino piccolo verde) - Draw dell'anchor point del target (pallino molto grande ciano) */ void setDebugEnable(const bool enable); private: class Attractor { public: Attractor(Point position, float zoom, float innerRadius, float outerRadius); Point getPosition() {return _position;} float getZoom() {return _zoom;} float getInnerRadius() {return _innerRadius;} float getOuterRadius() {return _outerRadius;} private: Point _position; float _zoom; float _innerRadius; float _outerRadius; }; class Rail { public: Rail(Rect area, Point startProjectionPoint, Point endProjectionPoint, std::vector<Point> railPoints, float railZoom); bool isPointOnRail(Point position); bool getPositionOnRail(Point position, Point& positionOnRail); bool getZoomOnRail(float& zoomOnRail); private: Rect _area; Point _startProjectionPoint; Point _endProjectionPoint; float _projectionLength; LinearInterpolation _railPath; float _railZoom; }; Node * _target; Rect _worldBoundaries; bool _clampOnBoundaries; bool _softBoundariesX; bool _softBoundariesY; bool _softBoundariesScheduledX; bool _softBoundariesScheduledY; // Screen Info per accesso rapido Point _screenOrigin; Size _screenSize; Point _screenCenter; // Follow Node * _followedNode; bool _followEnabled; Point _followedOffset; float _followSpeed; bool _followSmoothMovement; Rect _followBoundingArea; // Zoom float _zoomDestination; float _zoomSpeed; bool _zoomSmoothMovement; // Panning Point _panningDestination; float _panningSpeed; bool _panningSmoothMovement; // Attractors std::unordered_map<std::string, std::shared_ptr<Attractor>> _attractors; bool _attractorsEnabled; // Rails std::unordered_map<std::string, std::shared_ptr<Rail>> _rails; bool _railsEnabled; // Debug bool _debugEnabled; // // PRIVATE METHODS // // Updates void updateZoom(float dt); void updatePanning(float dt); void updateFollow(float dt); void updateAttractors(float dt); void updateRails(float dt); // Utilities void handleBoundaries(); void setScaleAndAdjustPosition(const float newScale); bool checkFollowedNodeInAreaX(); bool checkFollowedNodeInAreaY(); // Wrappers void setTargetPosition(const Point newPosition); void setTargetScale(const float newScale); void setPanningDestinationX(const float newDestinationX); void setPanningDestinationY(const float newDestinationY); Point getFollowedNodePositionOnScreen(); Point getFollowedNodePositionOnTarget(); // DEBUG void initDebugDrawScreenCenter(); void initDebugDrawBoundingWorld(); void initDebugDrawFollowArea(); void initDebugDrawPanDestination(); void updateDebug(); void updateDebugDrawPanDestination(); void updateDrawTargetAnchorPoint(); void updateDrawFollowedNodeOffset(); void updateDrawAttractors(); }; #endif /* defined(__SongOfPan__GameCameraNew__) */
da6f78bab513e8852b707c35eb2d3f5b4a7e4b99
6999cadecfcaeac4ab5d33e4645395c9e34c43cc
/framework/src/BoundingBox.h
b5b8176748abc7226f116bc1bf44a8ec35392a33
[]
no_license
fgan/cs184
f18d341ef263ae4b7567d5e26f9f2b0f4af2a192
3b4bc93c49a8d3efdff94839c8f2aa60f8c69130
refs/heads/master
2020-06-06T12:02:33.086406
2011-05-10T23:02:41
2011-05-10T23:02:41
1,726,534
0
1
null
null
null
null
UTF-8
C++
false
false
909
h
BoundingBox.h
/* * BoundingBox.h * * Created on: Mar 5, 2011 * Author: Yu Gan */ #ifndef BOUNDINGBOX_H_ #define BOUNDINGBOX_H_ #include "global.h" #include "UCB/SceneInfo.h" #include "Primitives.h" #include "Viewport.h" #include "UCB/Scene.h" #include <stack> /** * The World forms a container for lights and primitives * in our scene. */ class BoundingBox { public: BoundingBox::BoundingBox(); BoundingBox(vector<Sphere> _spheres, int axis); ~BoundingBox(); // recursively tests a ray for intersection with the BoundingBox, and fills in t, n, and m with info from the surface it hit bool intersect(Ray & r, double & t, vec3 &n, MaterialInfo &m); private: vector<Sphere> _spheres; // holds the spheres of this BB if it is a leaf BoundingBox *_leftChild; BoundingBox *_rightChild; vec3 upperCorner, lowerCorner; static const bool _DEBUG_INIT = false; }; #endif /* BOUNDINGBOX_H_ */
03443b3971adb6b07e587a8e8da42a3d2fdb11a6
13a2b49cd7e158a40e89f5dd6d5fd32677e60857
/ElectricalAccessories/pathdialog.h
3104226a77bdb87203e47b6c95e9fe39a0aa2c58
[]
no_license
ColTam/EAT2
90fa760fb6f39ba8fd8f68d5bc843070adb55d0e
014eaf640c385533727407fe086c002d1ed36325
refs/heads/master
2022-08-20T23:32:39.503275
2017-08-11T01:32:59
2017-08-11T01:32:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
h
pathdialog.h
#ifndef PATHDIALOG_H #define PATHDIALOG_H #include <QDialog> #include <QLabel> #ifdef _MSC_BUILD #pragma execution_character_set("utf-8") #endif class QLineEdit; /*! * \brief The path dialog class */ class pathDialog : public QDialog { Q_OBJECT public: explicit pathDialog(QWidget *parent = 0); ~pathDialog(); signals: public slots: void defaultClicked(); /*!* \brief 按键点击槽函数 */ void currentClicked(); /*!* \brief */ void saveClicked(); /*!* \brief */ public: QLabel* pathLabel; /*!* \brief 默认路径便签 */ QLineEdit* defaultPathLineEdit;/*!* \brief 默认路径输入框 */ QPushButton* pathPushButton; /*!* \brief 默认路径浏览按钮 */ QLabel* pathLabel_2; /*!* \brief 当前路径便签 */ QLineEdit* currentPathLineEdit;/*!* \brief 当前路径输入框 */ QPushButton* pathPushButton_2; /*!* \brief 当前路径浏览按钮 */ QPushButton* savePushButton; /*!* \brief 保存按钮 */ QPushButton* closePushButton; /*!* \brief 界面关闭按钮 */ }; #endif // PATHDIALOG_H
ba6e77dce968caadf14afd15c717c9046905a8b6
ab0db493b0fddb9bce8dc27d0d325618cfbcf885
/clp/Manager.cpp
4e9a089ddc14eab3b640f1802eeca878ee1b69f8
[]
no_license
Brillist/Optimizer-History
e2e44adbbe3e4f297aebf7b80e447ddc0c6787a9
5061bf4f4a15f65b2c0011ca0cc8c3c879ef1959
refs/heads/master
2020-05-26T18:32:55.284730
2019-04-27T03:49:08
2019-04-27T03:49:08
188,334,196
0
0
null
null
null
null
UTF-8
C++
false
false
21,646
cpp
Manager.cpp
#include "libclp.h" #include "BoundPropagator.h" #include "ChoicePoint.h" #include "ConstrainedVar.h" #include "FailEx.h" #include "IntSpan.h" #include "Or.h" #include "Manager.h" //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_NS_USE; LUT_NS_USE; //////////////////////////////////////////////////////////////////////////////////////////////////// UTL_CLASS_IMPL(clp::Manager); //////////////////////////////////////////////////////////////////////////////////////////////////// CLP_NS_BEGIN; //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::add(const Goal& goal) { add(goal.clone()); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::add(Goal* goal) { _goalStack.push(goal); goal->addRef(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::reset() { backtrack(uint_t_max - 2); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::restart() { ASSERTD(!_cpStack.empty()); backtrack(uint_t_max - 1); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool Manager::nextSolution() { bool firstSearch = (_cpStackSize == 1); // first search? if (firstSearch) { // create root choice point pushChoicePoint(); // reverse the goal stack (to execute goals in the order they were added) goal_stack_t goalStack; while (!_goalStack.empty()) { auto goal = _goalStack.top(); _goalStack.pop(); goalStack.push(goal); } _goalStack = goalStack; } // otherwise backtrack to continue the search else { if (!backtrack()) { return false; } } // empty the goal stack while (!_goalStack.empty()) { // pop a goal auto goal = _goalStack.top(); _goalStack.pop(); // Or goal? if (goal->isA(Or)) { // top CP is not for this Or? auto orGoal = utl::cast<Or>(goal); auto cp = _topCP; if (cp->orGoal() != orGoal) { // push a new CP for this Or cp = pushChoicePoint(); cp->set(orGoal, _goalStack); } // push the next alternative goal for this Or auto goal = cp->nextChoice(); _goalStack.push(goal); goal->addRef(); // orGoal was removed from _goalStack orGoal->removeRef(); } else // regular goal { try { // execute the goal and propagate goal->execute(); propagate(); goal->removeRef(); } catch (FailEx& failEx) { // backtrack (or return false to signal failure to the caller) goal->removeRef(); if (!backtrack(failEx.label())) { return false; } } } } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::propagate() { _boundPropagator->propagate(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::pushState() { pushChoicePoint(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::popState() { // must be choice point below root ASSERTD(_cpStackSize >= 2); auto cp = _topCP; // clear propagation queue _boundPropagator->clearPropQ(); // backtrack on the choice point backtrackCP(cp); // remove the choice point popChoicePoint(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::add(const Constraint& ct) { const_cast<Constraint&>(ct).mclone(); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool Manager::add(Constraint* ct) { if (_cts.find(ct) != _cts.end()) { return false; } ASSERTD(!_cpStack.empty() && (_topCP == _cpStack.top())); revAdd(ct); ct->setManaged(true); _cts.insert(ct); ct->addRef(); try { ct->postExpConstraints(); ct->post(); propagate(); } catch (FailEx&) { throw; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::remove(Constraint* ct) { ct->unpost(); if (_cts.erase(ct) != 0) { ct->removeRef(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::add(ConstrainedVar* var) { ASSERTD(!var->managed()); _vars.insert(var); var->setManaged(true); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::remove(ConstrainedVar* var) { _vars.erase(var); delete var; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::setBoundPropagator(BoundPropagator* bp) { delete _boundPropagator; _boundPropagator = bp; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::init() { _cpStackSize = 0; _topCP = nullptr; _revLongsSize = 0; _revLongArraysSize = 0; _revLongsIndSize = 0; _revLongArraysIndSize = 0; _revLongs = _revLongsPtr = _revLongsLim = nullptr; _revLongArrays = _revLongArraysPtr = _revLongArraysLim = nullptr; _revLongsInd = _revLongsIndPtr = _revLongsIndLim = nullptr; _revLongArraysInd = _revLongArraysIndPtr = _revLongArraysIndLim = nullptr; _revIntsSize = 0; _revIntArraysSize = 0; _revIntsIndSize = 0; _revIntArraysIndSize = 0; _revDeltaVarsSize = 0; _revTogglesSize = 0; _revCtsSize = 0; _revActionsSize = 0; _revAllocationsSize = 0; _revInts = _revIntsPtr = _revIntsLim = nullptr; _revIntArrays = _revIntArraysPtr = _revIntArraysLim = nullptr; _revIntsInd = _revIntsIndPtr = _revIntsIndLim = nullptr; _revIntArraysInd = _revIntArraysIndPtr = _revIntArraysIndLim = nullptr; _revDeltaVars = _revDeltaVarsPtr = _revDeltaVarsLim = nullptr; _revToggles = _revTogglesPtr = _revTogglesLim = nullptr; _revCts = _revCtsPtr = _revCtsLim = nullptr; _revActions = _revActionsPtr = _revActionsLim = nullptr; _revAllocations = _revAllocationsPtr = _revAllocationsLim = nullptr; // init skip-list delta array _skipListDepthArray = new SkipListDepthArray(CLP_INTSPAN_MAXDEPTH); // create bound propagator _boundPropagator = new BoundPropagator(this); // create root choice point pushChoicePoint(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::deInit() { goalStackClear(); for (auto ct : _cts) { ct->setPosted(false); } removeRefCont(_cts); deleteCont(_vars); delete _skipListDepthArray; delete _boundPropagator; deleteCont(_storedCPs); removeRefArray(_revCts, _revCtsPtr); deleteArray(_revAllocations, _revAllocationsPtr); delete[] _revLongs; delete[] _revLongArrays; delete[] _revLongsInd; delete[] _revLongArraysInd; delete[] _revInts; delete[] _revIntArrays; delete[] _revIntsInd; delete[] _revIntArraysInd; delete[] _revDeltaVars; delete[] _revToggles; delete[] _revCts; delete[] _revActions; delete[] _revAllocations; } //////////////////////////////////////////////////////////////////////////////////////////////////// ChoicePoint* Manager::pushChoicePoint() { propagate(); uint_t d = depth(); while (_storedCPs.size() <= d) { _storedCPs.push_back(nullptr); } auto cp = _storedCPs[d]; if (cp == nullptr) { cp = new ChoicePoint(); _storedCPs[d] = cp; } cp->setManager(this); cp->setRevLongsIdx(_revLongsPtr - _revLongs); cp->setRevLongArraysIdx(_revLongArraysPtr - _revLongArrays); cp->setRevLongsIndIdx(_revLongsIndPtr - _revLongsInd); cp->setRevLongArraysIndIdx(_revLongArraysIndPtr - _revLongArraysInd); cp->setRevIntsIdx(_revIntsPtr - _revInts); cp->setRevIntArraysIdx(_revIntArraysPtr - _revIntArrays); cp->setRevIntsIndIdx(_revIntsIndPtr - _revIntsInd); cp->setRevIntArraysIndIdx(_revIntArraysIndPtr - _revIntArraysInd); cp->setRevDeltaVarsIdx(_revDeltaVarsPtr - _revDeltaVars); cp->setRevTogglesIdx(_revTogglesPtr - _revToggles); cp->setRevCtsIdx(_revCtsPtr - _revCts); cp->setRevActionsIdx(_revActionsPtr - _revActions); cp->setRevAllocationsIdx(_revAllocationsPtr - _revAllocations); _cpStack.push(cp); ++_cpStackSize; _topCP = cp; return cp; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::popChoicePoint() { auto cp = _topCP; cp->clear(); _cpStack.pop(); --_cpStackSize; _topCP = _cpStack.top(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::goalStackClear() { while (!_goalStack.empty()) { auto goal = _goalStack.top(); _goalStack.pop(); goal->removeRef(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetLong(size_t& i) { // grow if necessary if (_revLongsPtr == _revLongsLim) { utl::arrayGrow(_revLongs, _revLongsPtr, _revLongsLim, utl::max(utl::KB(4), (_revLongsSize + 1))); _revLongsSize = _revLongsLim - _revLongs; } *_revLongsPtr++ = (size_t)&i; *_revLongsPtr++ = (size_t)i; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetLongArray(size_t* array, uint_t size) { // grow if necessary uint_t growth = size + 2; uint_t room = (_revLongArraysLim - _revLongArraysPtr); if (room < growth) { size_t curSize = (_revLongArraysPtr - _revLongArrays); utl::arrayGrow(_revLongArrays, _revLongArraysPtr, _revLongArraysLim, utl::max(utl::KB(4), curSize + growth)); _revLongArraysSize = _revLongArraysLim - _revLongArrays; } // copy array into _revLongArrays auto lhs = _revLongArraysPtr; auto rhs = array; _revLongArraysPtr += size; while (lhs < _revLongArraysPtr) { *lhs++ = *rhs++; } // size and start address *_revLongArraysPtr++ = size; *_revLongArraysPtr++ = (size_t)array; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetLongInd(size_t*& array, uint_t idx) { // grow if necessary uint_t room = (_revLongsIndLim - _revLongsIndPtr); if (room < 3) { size_t curSize = (_revLongsIndPtr - _revLongsInd); utl::arrayGrow(_revLongsInd, _revLongsIndPtr, _revLongsIndLim, utl::max(utl::KB(4), curSize + 3)); _revLongsIndSize = _revLongsIndLim - _revLongsInd; } *_revLongsIndPtr++ = array[idx]; *_revLongsIndPtr++ = idx; *_revLongsIndPtr++ = (size_t)&array; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetLongArrayInd(size_t*& array, uint_t idx, uint_t size) { // grow if necessary uint_t growth = size + 3; uint_t room = (_revLongArraysIndLim - _revLongArraysIndPtr); if (room < growth) { size_t curSize = (_revLongArraysIndPtr - _revLongArraysInd); utl::arrayGrow(_revLongArraysInd, _revLongArraysIndPtr, _revLongArraysIndLim, utl::max(utl::KB(4), curSize + growth)); _revLongArraysIndSize = _revLongArraysIndLim - _revLongArraysInd; } // copy array into _revLongArraysInd size_t* lhs = _revLongArraysIndPtr; size_t* rhs = array + idx; _revLongArraysIndPtr += size; while (lhs < _revLongArraysIndPtr) { *lhs++ = *rhs++; } // size, index, and start address *_revLongArraysIndPtr++ = size; *_revLongArraysIndPtr++ = idx; *_revLongArraysIndPtr++ = (size_t)&array; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetInt(uint_t& i) { // grow if necessary if (_revIntsPtr == _revIntsLim) { utl::arrayGrow(_revInts, _revIntsPtr, _revIntsLim, utl::max(utl::KB(4), (_revIntsSize + 2))); _revIntsSize = _revIntsLim - _revInts; } *_revIntsPtr++ = (size_t)&i; *_revIntsPtr++ = i; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetIntArray(uint_t* array, uint_t size) { // grow if necessary uint_t growth = size + 2; uint_t room = (_revIntArraysLim - _revIntArraysPtr); if (room < growth) { size_t curSize = (_revIntArraysPtr - _revIntArrays); utl::arrayGrow(_revIntArrays, _revIntArraysPtr, _revIntArraysLim, utl::max(utl::KB(4), curSize + growth)); _revIntArraysSize = _revIntArraysLim - _revIntArrays; } // copy array into _revIntArrays size_t* lhs = _revIntArraysPtr; uint_t* rhs = array; _revIntArraysPtr += size; while (lhs < _revIntArraysPtr) { *lhs++ = *rhs++; } // size and start address *_revIntArraysPtr++ = size; *_revIntArraysPtr++ = (size_t)array; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetIntInd(uint_t*& array, uint_t idx) { // grow if necessary uint_t room = (_revIntsIndLim - _revIntsIndPtr); if (room < 3) { size_t curSize = (_revIntsIndPtr - _revIntsInd); utl::arrayGrow(_revIntsInd, _revIntsIndPtr, _revIntsIndLim, utl::max(utl::KB(4), curSize + 3)); _revIntsIndSize = _revIntsIndLim - _revIntsInd; } *_revIntsIndPtr++ = array[idx]; *_revIntsIndPtr++ = idx; *_revIntsIndPtr++ = (size_t)&array; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::revSetIntArrayInd(uint_t*& array, uint_t idx, uint_t size) { // grow if necessary uint_t growth = size + 3; uint_t room = (_revIntArraysIndLim - _revIntArraysIndPtr); if (room < growth) { size_t curSize = (_revIntArraysIndPtr - _revIntArraysInd); utl::arrayGrow(_revIntArraysInd, _revIntArraysIndPtr, _revIntArraysIndLim, utl::max(utl::KB(4), curSize + growth)); _revIntArraysIndSize = _revIntArraysIndLim - _revIntArraysInd; } // copy array into _revIntArraysInd size_t* lhs = _revIntArraysIndPtr; uint_t* rhs = array + idx; _revIntArraysIndPtr += size; while (lhs < _revIntArraysIndPtr) { *lhs++ = *rhs++; } // size, index, and start address *_revIntArraysIndPtr++ = size; *_revIntArraysIndPtr++ = idx; *_revIntArraysIndPtr++ = (size_t)&array; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool Manager::backtrack(uint_t label) { ASSERTD(!_cpStack.empty()); _boundPropagator->clearPropQ(); for (uint_t depth = _cpStackSize; depth != 0; depth--) { auto cp = _topCP; // backtrack on the choice point backtrackCP(cp); // can we resume the search at this choice point? if (cp->hasRemainingChoice() && (!cp->hasLabel() || (label == uint_t_max) || (label == cp->label()))) { auto orGoal = cp->orGoal(); _goalStack.push(orGoal); orGoal->addRef(); return true; } else if (depth > 1) // never get rid of root choice point { popChoicePoint(); } } return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Manager::backtrackCP(ChoicePoint* cp) { // backtrack the choice point cp->backtrack(_goalStack); // backtrack rev-long-arrays auto revLongArraysBegin = _revLongArrays + cp->revLongArraysIdx(); while (_revLongArraysPtr != revLongArraysBegin) { auto array = reinterpret_cast<size_t*>(*--_revLongArraysPtr); auto size = *--_revLongArraysPtr; // copy array auto rhsLim = _revLongArraysPtr; _revLongArraysPtr -= size; auto lhs = array; auto rhs = _revLongArraysPtr; while (rhs != rhsLim) { *lhs++ = *rhs++; } } // backtrack rev-longs auto revLongsBegin = _revLongs + cp->revLongsIdx(); while (_revLongsPtr != revLongsBegin) { auto val = *--_revLongsPtr; auto ptr = reinterpret_cast<size_t*>(*--_revLongsPtr); *ptr = val; } // backtrack indirect rev-long-arrays auto revLongArraysIndBegin = _revLongArraysInd + cp->revLongArraysIndIdx(); while (_revLongArraysIndPtr != revLongArraysIndBegin) { auto arrayPtr = reinterpret_cast<size_t**>(*--_revLongArraysIndPtr); auto idx = *--_revLongArraysIndPtr; auto size = *--_revLongArraysIndPtr; // copy array auto rhsLim = _revLongArraysIndPtr; _revLongArraysIndPtr -= size; auto lhsPtr = *arrayPtr + idx; auto rhsPtr = _revLongArraysIndPtr; while (rhsPtr != rhsLim) { *lhsPtr++ = *rhsPtr++; } } // backtrack indirect rev-longs auto revLongsIndBegin = _revLongsInd + cp->revLongsIndIdx(); while (_revLongsIndPtr != revLongsIndBegin) { auto arrayPtr = reinterpret_cast<size_t**>(*--_revLongsIndPtr); auto idx = *--_revLongsIndPtr; auto val = *--_revLongsIndPtr; (*arrayPtr)[idx] = val; } // backtrack rev-int-arrays auto revIntArraysBegin = _revIntArrays + cp->revIntArraysIdx(); while (_revIntArraysPtr != revIntArraysBegin) { auto array = reinterpret_cast<uint_t*>(*--_revIntArraysPtr); auto size = *--_revIntArraysPtr; // copy array auto rhsLim = _revIntArraysPtr; _revIntArraysPtr -= size; auto lhsPtr = array; auto rhsPtr = _revIntArraysPtr; while (rhsPtr != rhsLim) { *lhsPtr++ = *rhsPtr++; } } // backtrack rev-ints auto revIntsBegin = _revInts + cp->revIntsIdx(); while (_revIntsPtr != revIntsBegin) { auto val = static_cast<uint_t>(*--_revIntsPtr); auto ptr = reinterpret_cast<uint_t*>(*--_revIntsPtr); *ptr = val; } // backtrack indirect rev-int-arrays auto revIntArraysIndBegin = _revIntArraysInd + cp->revIntArraysIndIdx(); while (_revIntArraysIndPtr != revIntArraysIndBegin) { auto arrayPtr = reinterpret_cast<uint_t**>(*--_revIntArraysIndPtr); auto idx = *--_revIntArraysIndPtr; auto size = *--_revIntArraysIndPtr; // copy array auto rhsLim = _revIntArraysIndPtr; _revIntArraysIndPtr -= size; auto lhsPtr = *arrayPtr + idx; auto rhsPtr = _revIntArraysIndPtr; while (rhsPtr != rhsLim) { *lhsPtr++ = *rhsPtr++; } } // backtrack indirect rev-ints auto revIntsIndBegin = _revIntsInd + cp->revIntsIndIdx(); while (_revIntsIndPtr != revIntsIndBegin) { auto arrayPtr = reinterpret_cast<uint_t**>(*--_revIntsIndPtr); auto idx = *--_revIntsIndPtr; auto val = static_cast<uint_t>(*--_revIntsIndPtr); (*arrayPtr)[idx] = val; } // backtrack changed variables auto revDeltaVarsBegin = _revDeltaVars + cp->revDeltaVarsIdx(); while (_revDeltaVarsPtr != revDeltaVarsBegin) { auto var = *--_revDeltaVarsPtr; var->backtrack(); } // toggle flags that were toggled auto revTogglesBegin = _revToggles + cp->revTogglesIdx(); while (_revTogglesPtr != revTogglesBegin) { auto flagPtr = *--_revTogglesPtr; *flagPtr = !*flagPtr; } // remove constraints that were added auto revCtsBegin = _revCts + cp->revCtsIdx(); while (_revCtsPtr > revCtsBegin) { auto ct = *--_revCtsPtr; remove(ct); ct->removeRef(); } // run backtracking actions auto revActionsBegin = _revActions + cp->revActionsIdx(); while (_revActionsPtr != revActionsBegin) { auto action = *--_revActionsPtr; action->execute(); delete action; } // delete objects that were allocated auto revAllocationsBegin = _revAllocations + cp->revAllocationsIdx(); while (_revAllocationsPtr != revAllocationsBegin) { auto object = *--_revAllocationsPtr; delete object; } } //////////////////////////////////////////////////////////////////////////////////////////////////// CLP_NS_END;
3531ea35291eed61b001d15bead4d15dda69be38
805206825d15f30177fd64b7967bb7d7283d5212
/数据结构/-5_二项堆和斐波那契堆/斐波那契堆/斐波那契堆/head.cpp
76ded1ae144f836e1b958a4fc46069f22623cf10
[]
no_license
Benshakalaka/DataStructure
71cdfb7a0543b358e4d40c73e97e3b09fe11158b
40e699e91eb8d5c5adbc60d1ed0fc5a3e07d5bed
refs/heads/master
2020-07-08T12:00:32.195392
2016-11-18T13:47:06
2016-11-18T13:47:10
74,025,323
0
0
null
null
null
null
UTF-8
C++
false
false
10,271
cpp
head.cpp
#include <malloc.h> #include <stdio.h> #include "head.h" #include "queue.h" #include <stdlib.h> //为一个堆的整体、参数等分配空间 void Make_Fib_Heap(FibonacciHeap &heap) { heap = (FibonacciHeap)malloc(sizeof(FibonacciHeapNode)); heap->min = 0; heap->keynum = 0; // heap->maxdegree = 0; } //在堆中插入一个关键字(节点) void fib_heap_add(Fibopnode head,Fibopnode node) //比较简洁的在双向链表中插入一个节点 { node->right = head->right; node->left = head; head->right->left = node; head->right = node; } void Fib_Heap_Insert(FibonacciHeap &heap,Fibopnode node) { node->child = node->parent = 0; //设置一些新节点的默认值 node->degree = 0; node->marked = false; //尝试插入 if(heap->min == 0) //本为空 那么直接放入 { node->left = node->right = node; //十分有必要加上这句话 不然会导致在不断插入过程中一侧出现问题 heap->min = node; } else //否则,要判断关键字大小与本堆中原最小比较 { fib_heap_add(heap->min,node); if(heap->min->key > node->key) heap->min = node; } heap->keynum++; } //将两个斐波那契堆合并(这里主要将F2释放,合并为最终的新F1) //在执行此操作前,默认F1,F2两个堆已分配空间,只是有无关键字不明确 void fibo_heap_union(Fibopnode x,Fibopnode y) //这里可以自己画图看的自习点 将两条根链首尾相连 { Fibopnode temp = x->right; x->right = y->right; y->right->left = x; temp->left = y; y->right = temp; } FibonacciHeap Fib_Heap_Union(FibonacciHeap &F1,FibonacciHeap &F2) { if(F1->min == 0) { free(F1); F1 = F2; } else if(F2->min == 0) free(F2); else { fibo_heap_union(F1->min,F2->min); //相连后 只需做一些细微的调整 if(F1->min->key > F2->min->key) F1->min = F2->min; F1->keynum += F2->keynum; } return F1; } //抽取整个堆的最小节点(取出 = 删掉 + 返回) void fibo_heap_remove(FibonacciHeap heap,Fibopnode parent,Fibopnode node) //将一个节点从一条双向链表中删去 { //首先将此节点拿出来 node->right->left = node->left; node->left->right = node->right; //拿出来之后做一些调整 // 此时分为是根链还是普通双链两种,如果是根链,那么应该处理的是min if(node->right == node) { if(parent == 0) heap->min = 0; else parent->child = 0; } else //如果还有节点存在,那么将指针指向下一个节点 { if(parent == 0) heap->min = node->right; else parent->child = node->right; } } void fib_heap_link(FibonacciHeap &heap,Fibopnode &x,Fibopnode &y) //将y插入到x的child的双向链表中去 { //先将y从原先链中删去(这里可以肯定y是在根链中的) if(x->child == 0) { x->child = y; y->left = y->right = y; //这一步必须要注意啊 因为在插入的时候如果没有净身的话 将来将节点继续插在这个节点后面 就无法组成双向链表 无法组成环了 } else fib_heap_add(x->child,y); y->parent = x; x->degree ++; y->marked = false; //首先请看关于mark的定义。 这里满足定义中的“当节点x成为另一个节点的孩子时,它便成为未被标记的节点” } void fib_heap_restruct(FibonacciHeap &heap) ////这个很重要!!!!!利用了散列表(哈希)的方法来对度数相同的堆进行合并 { int D = heap->keynum+1; Fibopnode *A = (Fibopnode *)malloc(sizeof(Fibopnode) * (D));//分配哈希空间 for(int i=0;i<D;i++) A[i] = 0; Fibopnode temp,x,y; int d = 0; int remove_count = 0; while(heap->min) //将根链上所有的都放到这个哈希表上去 { x = heap->min; d = x->degree; fibo_heap_remove(heap,0,x); //从原来的里面移除 最后再还回去 while(A[d] != 0) //一旦发现该位置已经被占据了,那么处理冲突的办法就是将这两个合并 移至下一个位置 这样循环递归 { y = A[d]; //合并的这一部分 比较复杂 在合并拆成一个度为2的树后,如果再与一个相同度的树合并 那么这个树是放在第一个孩子旁边 而非第二个孩子后面,这样看起来就并不是二项堆中二项树的样子了 不过因为是双向链表 所以所以换个方向就又是二项树的样子了 if(x->key > y->key) //这里保证x的关键字是小的(因为最小堆的性质),这样不仅可以省空间,还可以确保每次处理的都是x { temp = x; x = y; y = temp; if(!remove_count) //为什么有这个变量呢?因为合并的话可能不止一次 但是从原来的链表中删去点只能进行一次 fibo_heap_remove(heap,0,y); } else if(!remove_count) fibo_heap_remove(heap,0,x); //*******************************************这里把fibo_heap_remove提出来分情况是有必要的。因为一旦x和y交换后 要从原链中删去的就是y 然而不交换的话 删掉的是x fib_heap_link(heap,x,y); //这里的link将y连到x身上,一并处理了一些细节 A[d] = 0; d ++; //两个节点合并,会引起度的增加,当然对应的处理哈希表对象也要变化 remove_count++; } remove_count = 0; A[d] = x; } for(int j=0;j<D;j++) //将哈希表中的所有节点都返回堆中 if(A[j] != 0) { if(heap->min == 0) { heap->min = A[j]; heap->min->left = heap->min->right = heap->min; //这句话很有必要 不然导致一侧无法构成环 } else { fib_heap_add(heap->min,A[j]); if(heap->min->key > A[j]->key) heap->min = A[j]; } } } Fibopnode Fib_Heap_Extract_Min(FibonacciHeap &heap) { if(heap->min == 0) return 0; Fibopnode min = heap->min; Fibopnode child = 0; while(min->child) { child = min->child; fibo_heap_remove(heap,min,child); fib_heap_add(heap->min,child); //在这里的时候 我想为什么不用Union呢? 这里就可以简化了,因为普通堆有一条根链,而我要加进去的堆是一个根节点(就是说只有一个节点的链),这样的话还要用Union吗 不用了,直接当成节点插进去 但也用不到Insert 内容已经配置好 只要add就行了 child->parent = 0; } fibo_heap_remove(heap,0,min); if(heap->min != 0) fib_heap_restruct(heap); //这一步是在将最小节点删除后对整个堆进行的一次重新整合 heap->keynum --; return min; } //将heap堆中node节点中的关键字降至x void fibo_heap_cut(FibonacciHeap &heap,Fibopnode node,Fibopnode parent) //这个函数是用来将某个节点从双链表中删去,然后将此节点加入根链表,并且处理marked这个变量 { fibo_heap_remove(heap,parent,node); fib_heap_add(heap->min,node); node->parent = 0; node->marked = false; } void fibo_heap_cascading(FibonacciHeap &heap,Fibopnode parent) //级联切断操作 如果非根链表中节点被删去一个子节点后就被标记为true了,之后如果再次被删去一个子节点,那么该节点本身就被删去并加入根链表了 { Fibopnode pp = parent->parent; if(pp != 0) //如果是根链表中的节点,那么就退出级联操作 { if(parent->marked == false) parent->marked = true; else { fibo_heap_cut(heap,parent,pp); fibo_heap_cascading(heap,pp); } } } void FibonacciNode_Decrease(FibonacciHeap &heap,Fibopnode node,Keytype x) { if(node==0 || node->key < x) //在操作前首先看替换的关键字是否满足函数的目的 return; node->key = x; Fibopnode parent = node->parent; if(parent && node->key < parent->key) //如果是根链里的节点被decrease 那么就不必进行种种操作了 { fibo_heap_cut(heap,node,parent); fibo_heap_cascading(heap,parent); //这个过程里可能有许许多多节点被移到根链中去,但是不需要与min进行比较,因为根据堆的性质 又没有新的关键字进来 所以最终最小的依旧是原来的min。当然,这个操作的本意是decrease某个关键字 所以就需要与min比较 就是下面两行 } if(heap->min->key > x) //因为被换了关键字 所以要进行比较。 heap->min = node; } //将heap堆中node节点中的关键字增至x (Increase的程序和Decrease的程序类似 不过是Increase的程序里需要将该节点的所有子树都放到根链中去) void FibonacciNode_Increase(FibonacciHeap &heap,Fibopnode node,Keytype x) { if(node==0 || node->key > x) return; node->key = x; Fibopnode child = 0; while(node->child) //将所有节点都放到根链中去 { child = node->child; fibo_heap_remove(heap,node,child); fib_heap_add(heap->min,child); child->parent = 0; } node->degree = 0; Fibopnode parent = node->parent; //然后将该节点Cut以及Cascading-cut if(parent != 0) { fibo_heap_cut(heap,node,parent); fibo_heap_cascading(heap,parent); } if(heap->min == node) //如果正好这个点是最小的点 那么需要更新以下这个min的指向 { Fibopnode temp = node->right; while(temp != node) { if(temp->key < heap->min->key) heap->min = temp; temp = temp->right; } } } //删除某个节点,与二项堆里的一样 很简单 利用到了decrease 和 extract 当然 有个free没有写下来。。。 void Fibonacci_Heap_Delete(FibonacciHeap &heap,Fibopnode &node) { FibonacciNode_Decrease(heap,node,0); //降到最小 这里的0代表无穷小 当然可以用-999之类的 Fib_Heap_Extract_Min(heap); } //输出斐波那契堆 void Print(FibonacciHeap heap) { pss Queue = (pss)malloc(sizeof(ss)); init(Queue); Fibopnode temp = heap->min,temp2 = 0,temp3 = 0; do { en_queue(Queue,temp); while(!is_empty(Queue)) { out_queue(Queue,temp2); if(temp2->parent != 0) printf("%d is %d's child \n",temp2->key,temp2->parent->key); else printf("%d is a root\n",temp2->key); if(temp2->child) { temp3 = temp2 = temp2->child; do { en_queue(Queue,temp2); temp2 = temp2->right; }while(temp2!=temp3); } } temp = temp->right; }while(temp!=heap->min); puts("That's all-------------------------------------------\n"); }